How to get data of current date using sum in SQL? - sql-server

I'm working on a SQL query trying to fetch sum data for the current day/date. Can anyone have a look at my query, and find me a working solution?
SELECT SUM(amount)
FROM tbl_expense_record
WHERE dateonly = CAST(GETDATE() AS Date)
But I get data when mentioning a specific date in where condition like
SELECT SUM(amount) AS total
FROM tbl_expense_record
WHERE dateonly = '2020-06-12'
I want the a code to auto pick current date. Also I would like to fetch sum of ranged dates like a whole week, and a month!

select datename(month, '2020-06-12'), datename(month, getdate());
--1week
SELECT SUM(amount) AS total
FROM tbl_expense_record
WHERE dateonly >= dateadd(week, -1, cast(getdate() as date))
and dateonly <= cast(getdate() as date)
--1month
SELECT SUM(amount) AS total
FROM tbl_expense_record
WHERE dateonly >= dateadd(month, -1, cast(getdate() as date))
and dateonly <= cast(getdate() as date)
--build muscle memory (it is always safe to check for < date+1 instead of <= date)
--1month
SELECT SUM(amount) AS total
FROM tbl_expense_record
WHERE dateonly >= dateadd(month, -1, cast(getdate() as date))
and dateonly < dateadd(day, 1, cast(getdate() as date));
--6months
SELECT SUM(amount) AS total
FROM tbl_expense_record
WHERE dateonly >= dateadd(month, -6, cast(getdate() as date))
and dateonly < dateadd(day, 1, cast(getdate() as date));
if not exists
(
select *
FROM tbl_expense_record
WHERE dateonly >= dateadd(month, -1, cast(getdate() as date))
and dateonly < dateadd(day, 1, cast(getdate() as date))
)
begin
select 'no rows within the last month'
end
else
begin
select 'there are rows within the last month';
end;
Examples:
declare #tbl_expense_record table(dateonly date, amount decimal(9,2));
insert into #tbl_expense_record
values ('20200501', 10), ('20200612', 10), ('20200613', 11), ('20200614', 12),
('20200710', 5), ('20200720', 6), ('20200820', 20), ('20200825', 30),
('20201102', 1), ('20201110', 2), ('20201120', 3);
--aggregation per month, for all rows
select year(dateonly) as _year, month(dateonly) as _month, sum(amount) as sum_amount_per_month, count(*) as rows_per_month
from #tbl_expense_record
group by year(dateonly), month(dateonly);
--aggregation per iso-week
select year(dateonly) as _year, datepart(iso_week, dateonly) as _isoweek, sum(amount) as sum_amount_per_isoweek, count(*) as rows_per_isoweek
from #tbl_expense_record
group by year(dateonly), datepart(iso_week, dateonly);
--aggregation per month, for all rows with a dateonly that falls in the last month
--check the difference between aggregation per month earlier and this..
--filter rows first == where .... and then aggregate
--there are two rows with dateonly > 06 november (the row at 05 is filtered out by the where clause)
select year(dateonly) as _year, month(dateonly) as _month, sum(amount) as sum_amount_per_month, count(*) as rows_per_month
from #tbl_expense_record
where dateonly >= dateadd(month, -1, cast(getdate() as date))
and dateonly < dateadd(day, 1, cast(getdate() as date))
group by year(dateonly), month(dateonly);
--aggregate per week diff from today/getdate()
select
datediff(week, getdate(), dateonly) as week_diff_from_today,
dateadd(day,
--datepart(weekday..) is used...account for ##datefirst setting / set datefirst
1-(##datefirst+datepart(weekday, dateadd(week, datediff(week, getdate(), dateonly), cast(getdate() as date))))%7,
dateadd(week, datediff(week, getdate(), dateonly), cast(getdate() as date)))
as startofweek,
dateadd(day, 6, --add 6 days to startofweek
dateadd(day,
--datepart(weekday..) is used...account for ##datefirst setting / set datefirst
1-(##datefirst+datepart(weekday, dateadd(week, datediff(week, getdate(), dateonly), cast(getdate() as date))))%7,
dateadd(week, datediff(week, getdate(), dateonly), cast(getdate() as date)))
) as endofweek,
sum(amount) as sum_amount, count(*) as rows_within_week
from #tbl_expense_record
group by datediff(week, getdate(), dateonly);

Related

Return 6 previous Month select last month

SELECT DISTINCT itemcode,
itemdescription,
unitofmeasure,
Sum([current]) AS [Ending Balance]
WHERE transactiondate >= Dateadd(month, Datediff(month, 0,
Dateadd(m, -6, '2019-01-31'
)), 0)
Your code is missing FROM and GROUP BY clause and the Date Diff (Six Mont considering End Date = '2019-01-31') can be calculated as shown in the below script-
SELECT
itemcode,
itemdescription,
unitofmeasure,
Sum([current]) AS [Ending Balance]
FROM <your_table> -- FROM is missing. Please add appropriate table name
WHERE transactiondate Between
DATEADD(month, -6, '2019-01-31')
AND '2019-01-31'
GROUP BY itemcode,itemdescription,unitofmeasure
-- GROUP BY is required as you applied Aggregation on column [current]
If you wants only records from the 6th Previous month, WHERE condition will be as below-
WHERE YEAR(transactiondate) = YEAR(DATEADD(month, -6, '2019-01-31'))
AND MONTH(transactiondate) = MONTH(DATEADD(month, -6, '2019-01-31'))
For getting results from last 6 month, WHERE will be as below-
WHERE transactiondate BETWEEN
CAST(LEFT(CAST(DATEADD(MM,-6,CAST('2019-01-31' AS DATE)) AS VARCHAR),7) + '-01' AS DATE)
AND
DATEADD(DD,-1,CAST(CAST(LEFT(CAST(CAST('2019-01-31' AS DATE) AS VARCHAR),7) + '-01' AS DATE) AS DATE))
-- This is basically: transactiondate BETWEEN '2018-07-01' AND '2018-12-31'

Get date with some criteria in SQL server

What I want is the EmployeeName from the emp_mst table with some condition which is given below:-
All EmployeeName for last 7 months from the current date and also less 15 days.
from the below query I am getting the result for the last month, but I want this for the last 6 months
select DATEADD(month, -1, GETDATE()- 15)
I am using sql server 2008
UPDATED PROCEDURE
SELECT * FROM (SELECT CASE
WHEN (SELECT Isnull(Sum(total_day), 0)
FROM xxacl_erp_ab_pl_count_view
WHERE emp_card_no = em.emp_card_no) > 7 THEN
'DOC Exteded By 1 month. Reason:- Taken leave='
+ CONVERT(VARCHAR, (SELECT Sum(total_day) FROM
xxacl_erp_ab_pl_count_view
WHERE emp_card_no = em.emp_card_no))
+
' which is > 7. Actual DOC='
+ CONVERT(VARCHAR, Dateadd(mm, em.probation_period, em.date_of_joining), 103)
+ ''
ELSE 'N/A'
END Remark,
em.*
FROM emp_mst em
LEFT JOIN company_mst comp
ON em.comp_mkey = comp.mkey
AND comp.fa_year = 2008
AND company_name NOT LIKE '%HELIK%'
WHERE em.status IN ( 'A' ) --and em.emp_type='E'
AND em.emp_card_no != 9999
AND em.resig_date IS NULL
AND CONVERT(DATETIME, em.date_of_joining, 103) >=
CONVERT(DATETIME,
Dateadd(m, -6, Getdate()), 103)
AND em.emp_card_no NOT IN (SELECT emp_card_no
FROM p_emp_confirmation_hdr
WHERE delete_flag = 'N'
AND hr_flag = 'Y')) pp
WHERE remark = 'N/A'
Casting to date to avoid calculating with timestamps
WHERE
yourdate >= dateadd(m, -6, datediff(d, 15, getdate())) and
yourdate < dateadd(d, -15, datediff(d, 0, getdate()))
Changed answer to adjust for you using sqlserver 2005 or older
Added 15 days extra to the interval
SELECT [emp_name]
FROM [TABLE]
WHERE [DateColumn] BETWEEN DATEADD(MONTH, -6, CAST(GETDATE() AS DATE))
AND DATEADD(DAY, -15, CAST(GETDATE() AS DATE))
This will show you employees who were added between six months ago and 15 days ago, for example, running that today would give you employees from the range 2014-12-24 and 2015-06-09.
EDIT: For SQL Server 2005 and earlier:
SELECT [emp_name]
FROM [TABLE]
WHERE [DateColumn] BETWEEN DATEADD(MONTH, -6, cast(convert(char(11), getdate(), 113) as datetime))
AND DATEADD(DAY, -15, cast(convert(char(11), getdate(), 113) as datetime))

SSRS loop over select by months

I am creating report in SSRS that should show event duration in a month. This report should do it 12 time for every calendar month separately. At the moment my select has 12 hardcoded selects, for every month each. How can I do this with one select repeated 12 times and just iterated start and end times, either in SQL language (applicable as a view) or even better from SSRS? Thank you.
SELECT DATEDIFF(mi, '2014-01-01 00:00:00.000', end_date) AS total_event
FROM MY_TABLE
WHERE (start_date <= '2014-01-01 00:00:00.000') AND (end_date BETWEEN '2014-01-01 00:00:00.000' AND '2014-02-01 00:00:00.000')
UNION ALL
SELECT DATEDIFF(mi, start_date, '2014-02-01 00:00:00.000') AS total_event
FROM MY_TABLE
WHERE (end_date >= '2014-02-01 00:00:00.000') AND (start_date BETWEEN '2014-01-01 00:00:00.000' AND '2014-02-01 00:00:00.000')
UNION ALL
SELECT DATEDIFF(mi, '2014-01-01 00:00:00.000', '2014-02-01 00:00:00.000') AS total_event
FROM MY_TABLE
WHERE (start_date <= '2014-01-01 00:00:00.000') AND (end_date >= '2014-02-01 00:00:00.000')
UNION ALL
SELECT DATEDIFF(mi, start_date, end_date) AS total_event
FROM MY_TABLE
WHERE (start_date BETWEEN '2014-01-01 00:00:00.000' AND '2014-02-01 00:00:00.000') AND (end_date BETWEEN '2014-01-01 00:00:00.000' AND '2014-02-01 00:00:00.000')
try using below script
declare #start datetime
declare #end datetime
set #start = '2014-01-01' --firstDay year
set #end = '2014-12-31' --last Day of year
;with cte as
(
select #start firstday, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,DATEADD(month, DATEDIFF(month, 0, #start), 0))+1,0)) lastday, 1 MM
union all
select DATEADD(month, DATEDIFF(month, 0, lastday + 1), 0) , DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,DATEADD(month, DATEDIFF(month, 0, lastday + 1), 0))+1,0)), MM + 1
from cte
where lastday < #end
)
SELECT * FROM CTE C
--LEFT OUTER JOIN MY_TABLE M ON (M.start_date <= firstday) AND (end_date BETWEEN firstday AND lastday)
just un-comment last line
--LEFT OUTER JOIN MY_TABLE M ON (M.start_date <= firstday) AND (end_date BETWEEN firstday AND lastday)
You could try this:
SELECT
DATEADD(MONTH, DATEDIFF(MONTH, 0, start_date), 0) AS [month], DATEDIFF(MINUTE, DATEADD(MONTH, DATEDIFF(MONTH, 0, start_date), 0), end_date) AS total_event
FROM
MY_TABLE
WHERE
YEAR(start_date) = 2014
ORDER BY
[month];

how to get data of current week only in SQL server?

I want records from table which stores the current date when a record is inserted with in current week only.
I have tried:
SELECT PId
,WorkDate
,Hours
,EmpId
FROM Acb
WHERE EmpId=#EmpId AND WorkDate BETWEEN DATEADD(DAY, -7, GETDATE()) AND GETDATE()
Do it like this:
SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT [...]
AND WorkDate >= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND WorkDate < dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
Explanation:
datepart(dw, getdate()) will return the number of the day in the current week, from 1 to 7, starting with whatever you specified using SET DATEFIRST.
dateadd(day, 1-datepart(dw, getdate()), getdate()) subtracts the necessary number of days to reach the beginning of the current week
CONVERT(date,getdate()) is used to remove the time portion of GETDATE(), because you want data beginning at midnight.
A better way would be
select datepart(ww, getdate()) as CurrentWeek
You can also use wk instead of ww.
Datepart Documentation
Its Working For Me.
Select * From Acb Where WorkDate BETWEEN DATEADD(DAY, -7, GETDATE()) AND DATEADD(DAY, 1, GETDATE())
You have to put this line After the AND Clause AND DATEADD(DAY, 1, GETDATE())
datepart(dw, getdate()) is the current day of the week, dateadd(day, 1-datepart(dw, getdate()), getdate()) should be the first day of the week, add 7 to it to get the last day of the week
You can use following query to extract current week:
select datepart(dw, getdate()) as CurrentWeek
SET DATEFIRST 1;
;With CTE
AS
(
SELECT
FORMAT(CreatedDate, 'MMMM-yyyy') as Months,
CASE
WHEN YEAR(DATEADD(DAY, 1-DATEPART(WEEKDAY, Min(CreatedDate)), Min(CreatedDate))) < YEAR(Min(CreatedDate))
THEN FORMAT(DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, 0 ,GETDATE())), 0) ,'MMM dd') + ' - ' + FORMAT(DATEADD(dd, 7-(DATEPART(dw, Min(CreatedDate))), Min(CreatedDate)) ,'MMM dd')
ELSE
FORMAT(DATEADD(DAY, 1-DATEPART(WEEKDAY, Min(CreatedDate)), Min(CreatedDate)) ,'MMM dd') + ' - ' + FORMAT(DATEADD(dd, 7-(DATEPART(dw, Min(CreatedDate))), Min(CreatedDate)) ,'MMM dd')
END DateRange,
Sum(ISNULL(Total,0)) AS Total,
sum(cast(Duration as int)) as Duration
FROM TL_VriandOPI_Vendorbilling where VendorId=#userID and CompanyId=#CompanyID
Group By DATEPART(wk, CreatedDate) ,FORMAT(CreatedDate, 'MMMM-yyyy')
)
SELECT Months,DateRange,Total,Duration,
case when DateRange=(select FORMAT(DATEADD(DAY, 1-DATEPART(WEEKDAY, Min(getdate())), Min(getdate())) ,'MMM dd') + ' - ' +
FORMAT(DATEADD(dd, 7-(DATEPART(dw, Min(getdate()))), Min(getdate())) ,'MMM dd'))
then 1 else 0 end as Thisweek
FROM CTE order by Months desc
Using DATEDIFF works as well, however a bit hacky since it doesn't care about datefirst:
set datefirst 1; -- set monday as first day of week
declare #Now datetime = '2020-09-28 11:00';
select *
into #Temp
from
(select 1 as Nbr, '2020-09-22 10:00' as Created
union
select 2 as Nbr, '2020-09-25 10:00' as Created
union
select 2 as Nbr, '2020-09-28 10:00' as Created) t
select * from #Temp where DATEDIFF(ww, dateadd(dd, -##datefirst, Created), dateadd(dd, -##datefirst, #Now)) = 0 -- returns 1 result
select * from #Temp where DATEDIFF(ww, dateadd(dd, -##datefirst, Created), dateadd(dd, -##datefirst, #Now)) = 1 -- returns 2 results
drop table #Temp

how to get the start and end dates of all weeks between two dates in SQL server?

I need to get all week start and end dates(weeks) between two dates and then run a query returning the number of records inserted in each of those weeks.
declare #sDate datetime,
#eDate datetime;
select #sDate = '2013-02-25',
#eDate = '2013-03-25';
--query to get all weeks between sDate and eDate
--query to return number of items inserted in each of the weeks returned
WEEK NoOfItems
-----------------------------------------
2013-02-25 5
2013-03-4 2
2013-03-11 7
You can use a recursive CTE to generate the list of dates:
;with cte as
(
select #sDate StartDate,
DATEADD(wk, DATEDIFF(wk, 0, #sDate), 6) EndDate
union all
select dateadd(ww, 1, StartDate),
dateadd(ww, 1, EndDate)
from cte
where dateadd(ww, 1, StartDate)<= #eDate
)
select *
from cte
See SQL Fiddle with Demo.
Then you can join this to your table, to return the additional details.
Here is my solution. Inspired by this answer
DECLARE #sDate DATE = DATEADD(MONTH, -6, GETDATE())
DECLARE #eDate DATE = GETDATE()
;WITH cte AS
(
SELECT DATEADD(WEEK, DATEDIFF(WEEK, 0, #sDate), 0) AS StartDate, DATEADD(WEEK, DATEDIFF(WEEK, 0, #sDate), 6) AS EndDate
UNION ALL
SELECT DATEADD(WEEK, 1, StartDate), DATEADD(WEEK, 1, EndDate)
FROM cte
WHERE DATEADD(WEEK, 1, StartDate) <= #eDate
)
SELECT * FROM cte

Resources