Taking sum of column based on date range in T-Sql - sql

I have a column called Work Done where on daily basis some amount of work is caarried out. It has columns
Id, VoucherDt, Amount
Now my report has scenario to print the sum of amount till date of the month. For example if Current date is 3rd September 2013 then the query will pick all records of 1st,2nd and 3rd Sept and return a sum of that.
I am able to get the first date of the current month. and I am using the following condition
VoucherDt between FirstDate and GetDate() but it doesnot givign the desired result. So kindly suggest me the proper where condition.

SELECT SUM(AMOUNT) SUM_AMOUNT FROM <table>
WHERE VoucherDt >= DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP), 0)
AND VoucherDt < DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 1)

I think that there might be a better solution but this should work:
where YEAR(VoucherDt) = YEAR(CURRENT_TIMESTAMP)
and MONTH(VoucherDt) = MONTH(CURRENT_TIMESTAMP)
and DAY(VoucherDt) <= DAY(CURRENT_TIMESTAMP)

Try to calc the number of months from the first date that you can store in a datetime an your target dates.
SELECT SUM(amount)
FROM
(
SELECT 100000 AS amount, '2013-09-03' AS dt
UNION ALL SELECT 10000, '2013-09-02'
UNION ALL SELECT 1000, '2013-09-01'
UNION ALL SELECT 100, '2013-08-02'
UNION ALL SELECT 10, '2013-01-31'
UNION ALL SELECT 2, '2012-09-03'
UNION ALL SELECT 2, '2012-09-02'
UNION ALL SELECT 1, '2012-09-01'
) SourceData
WHERE DATEDIFF(m, '1900-1-1', GETDATE()) = DATEDIFF(m, '1900-1-1', SourceData.dt)

Related

How to include month names with count as 0 for monthly data count?

I am running the below query to fetch monthly data count for last year till current month.
SELECT dateName(month,tn.processstarttime) as reqMonth, count(ID) as requestCount, year(tn.processstarttime) as reqYear
FROM table A tn WHERE year(tn.processstarttime) in (year(DATEADD(MONTH, 0, GETDATE())),year(DATEADD(MONTH, -12, GETDATE())))
AND tn.processstarttime>DATEADD(MONTH, -12, GETDATE())
GROUP BY dateName(month,tn.processstarttime),year(tn.processstarttime)
order by dateName(month,tn.processstarttime),year(tn.processstarttime)
But this query is not giving month names for which the data count is 0.
Please support to include months for which the data count is 0 with value as 0.
Thanks
The standard way is to use calendar table with all years nad month required and then LEFT JOIN to it your result. When there will be no corresponding record in your table to some meonth, you will use COALESCE to obtain 0 for those months. See below query (I used CTEs to get calendar table, IMO the easiest way):
;with MonthNames as (
select 1 MonthNo, 'January' MonthName
union all
select 2, 'February'
union all
select 3, 'March'
union all
select 4, 'April'
union all
select 5, 'May'
union all
select 6, 'June'
union all
select 7, 'July'
union all
select 8, 'August'
union all
select 9, 'September'
union all
select 10, 'October'
union all
select 11, 'November'
union all
select 12, 'December'
), Years as (
select 2017 Year union all select 2018 union all select 2019
), CalendarTable as (
select * from MonthNames cross join Years
)
select ct.MonthName,
ct.Year,
COALESCE(t.requestCount, 0) requestCount
from CalendarTable ct
left join (YOUR WHOLE SELECT) t
on t.Year = ct.Year and t.month = ct.MonthNo
This answer can be similar to Michal Turczyn's, but there are a couple of substantial differences:
Do not pay much attention on the differences creating the first two CTEs, as different they look as irrelevant, simply matter of styles.
The important difference is in the third CTE and the way of filter your query, the name of your column (processstarttime) is giving a clue that it can be a very large table, so if you use where clauses using functions for the selected table columns, it will work, but your query won't be indexed and the performance can be a further issue
Not top relevant but also important is that It cover the "monthly data count for last year till current month" PO's requirement without hardcoding dates, it can be within a view or function that doesn't need to be modifiied year by year...
WITH months AS (
SELECT 1 AS MonthNum, DATENAME(Month,DATEFROMPARTS(1,1,1)) AS MonthName
UNION ALL
SELECT MonthNum + 1, DATENAME(Month,DATEFROMPARTS(1, MonthNum + 1, 1)) AS MonthName
FROM months
WHERE MonthNum <= 11
),
years as (
SELECT YEAR(GETDATE())-1 AS Year
UNION ALL
SELECT Year + 1
FROM years
WHERE Year + 1 <= YEAR(GETDATE())
),
dates as (
SELECT Year, MonthNum, MonthName, DATEFROMPARTS(Year, MonthNum, 1) AS DateStart, DATEADD(MONTH, 1, DATEFROMPARTS(Year, MonthNum, 1)) AS DateEnd
FROM years
CROSS JOIN months
)
SELECT D.Year, D.MonthNum, D.MonthName, COUNT(ID) AS RequesCount
FROM dates D
LEFT JOIN YourTable A ON A.ProcessStartTime >= DateStart AND A.ProcessStartTime < DateEnd
WHERE DateStart < GETDATE()
GROUP BY D.Year, D.MonthNum, D.MonthName
ORDER BY Year, MonthNum
Try this
SELECT months.month_name AS reqMonth, COUNT(ID) AS requestCount, YEAR(tn.processstarttime) AS reqYear
FROM A tn
RIGHT JOIN (VALUES ('january'),('february'),('march'),('april'),
('may'),('june'),('july'),('august'),('september'),
('october'),('november'),('december')) as months(month_name)
ON DATENAME(month,tn.processstarttime) = months.month_name
AND YEAR(tn.processstarttime) in (YEAR(DATEADD(MONTH, 0, GETDATE())),year(DATEADD(MONTH, -12, GETDATE())))
AND tn.processstarttime>DATEADD(MONTH, -12, GETDATE())
GROUP BY months.month_name,YEAR(tn.processstarttime)
order by months.month_name,YEAR(tn.processstarttime)
In action here

How can I select the 1st of every month for the last 5 years in sql?

I am trying to get a list of the 1st of the Month for the last 5 years. How can i do that ?? I have a select statement:
select convert(varchar(10), dateadd(mm,Datediff(mm,0,getdate()),0),111) as StartDate
but i am not sure how to get a list for every month.
with dates
as (
select dateadd(month, datediff(month, 0, getdate()), 0) as date
union all
select dateadd(month, - 1, date)
from dates
)
select top 60 *
from dates
with cte as (
select DATEFROMPARTS ( datepart(yyyy,getdate()), datepart(mm,getdate()), 1 ) as startdate
union all
select dateadd(month,-1,startdate) from dates
where datediff(year,startdate,getdate()) <> 5 )
select CONVERT ( varchar(12), startdate , 107 ) from cte;

Select dates inside current month SQL

I have a table similar to one below. I'm trying to select only the rows where the Start Date is in the current month. Here is what I have so far, but it's not working.
SELECT *
FROM TABLE1
WHERE StartDate = MONTH(getdate())
How can I select only the values where the start date is in the current month?
Use this construct to avoid functions on the StartDate columns (like MONTH or YEAR). These functions will prevent any index or statistics being used/
SELECT *
FROM TABLE1
WHERE
StartDate >= DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
AND StartDate < DATEADD(month, 1+DATEDIFF(month, 0, GETDATE()), 0)
Any answer that puts a function on StartDate will not scale as expected. See error number 2 here. The filter is now non-sargable, and index/statistics can't be used. Every row will be looked at for a table scan.
You need to check the month of both fields
WHERE MONTH(startdate) = MONTH(getdate())

How to display Previous month total dates in sequence

I want to display Previous month dates.May i know the query which is used to display all dates
Expected Output:
Current date = '2012-09-13'
I want to display my result as
1
2
3
4
,
,
,
,
31
these dates should come from month 8
try this:
SELECT NUMBER
FROM MASTER..SPT_VALUES
WHERE TYPE='P'
AND NUMBER BETWEEN
DATEPART(DD,DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1,0))
AND DATEPART(DD,DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()),-1))
Replcae Getdate() with your date
Please try:
;WITH DATES (date)
AS(
SELECT DATEADD(month, DATEDIFF(month, 0, dateadd(month,-1,getdate())), 0)
UNION ALL
SELECT DATEADD(DAY,1,date)
FROM DATES
WHERE DATEADD(DAY,1,date)<=DATEADD(month, DATEDIFF(month, 0, getdate()), 0)-1
)SELECT DAY(date) AS DAYS FROM DATES

sql get count of month

In SQLExpress, I have a table that contains a datetime-column. It is formatted like this:
19.03.2012 00:00:00
Now, there are a lot of dates in there and I want to build a WPFChart, that shows me, how much dates are in march, in april and so on.
How can I manage this in sql that I get the count of one month?
Use:
select month(dateColumn), count(*)
from table
group by month(dateColumn)
You can extract the month of a date with Month() funciton.
than with a simple group by, you get the count for every month
To get only one month...
SELECT
COUNT(*),
SUM(valueColumn)
FROM
yourTable
WHERE
dateColumn >= '20120101'
AND dateColumn < '20120201'
To get multiple months, but grouped by month (and accounting for year).
SELECT
DATEADD(MONTH, DATEDIFF(MONTH, 0, dateColumn), 0),
COUNT(*),
SUM(valueColumn)
FROM
yourTable
WHERE
dateColumn >= '20110301'
AND dateColumn < '20120301'
GROUP BY
DATEADD(MONTH, DATEDIFF(MONTH, 0, dateColumn), 0)