How to sum total by a field name by month for the previous six month - sql

I have a table with following fields
Status, branch, reason code description, year, month, day, count
I am trying to get a report like this for each branch:
Reason code desc.,July,August,sept.,October.,nov.,Dec.,Total,% of Total
Reason 1. 4. 6. 2. 5. 0. 2. 19 79.1
Reason 2. 1 0. 2. 1. 1. 0 5. 20.9
--------------------------
5. 6. 4. 6. 1. 2. 24 100.0

Assuming that your database is Oracle the query can be:
select RCMonth.*, RCTotal.Total, round(RCTotal.Total*100/Total.Total, 2) "Total%"
from
(
select reasoncode , to_char(createdon,'Mon') mon
from rc_report
where createdon > sysdate - 180
union all
select 'Sum' , to_char(createdon,'Mon') mon
from rc_report
where createdon > sysdate - 180
) pivot
( count(*)
for mon in ('Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan')
) RCMonth
join ( select count(*) Total,
reasoncode
from rc_report
where createdon > sysdate - 180
group by reasoncode
union all
select count(*) Total,
'Sum'
from rc_report
where createdon > sysdate - 180
) RCTotal
on RCTotal.ReasonCode = RCMonth.ReasonCode
cross join (
select count(*) Total
from rc_report
where createdon > sysdate - 180 ) Total
order by RCMonth.ReasonCode
Sample result is:
Row# REASONCODE 'Aug' 'Sep' 'Oct' 'Nov' 'Dec' 'Jan' TOTAL Total%
1 Reason1 2 2 0 3 2 0 9 81.82
2 Reason2 0 1 0 1 0 0 2 18.18
3 Sum 2 3 0 4 2 0 11 100
Table definition is :
create table rc_report
(reasoncode varchar2(20),
createdon date)
And also version for SQL Server in SQL Fiddle
It's only a little bit different.
select RCMonth.*, RCTotal.Total, round( cast ( RCTotal.Total as decimal) *100 /Total.Total,2) "Total%"
from
(
select reasoncode, [Aug], [Sep], [Oct], [Nov], [Dec], [Jan] from (
select reasoncode , left( datename(Month,createdon),3) mon
from rc_report
where createdon >= DATEADD(MONTH, -6, GETDATE())
union all
select 'Sum' , left( datename(Month, createdon),3) mon
from rc_report
where createdon >= DATEADD(MONTH, -6, GETDATE())
) Source
pivot
( count(Source.mon)
for mon in ([Aug], [Sep], [Oct], [Nov], [Dec], [Jan])
) as PivotTable
) RCMonth
join ( select count(*) Total,
reasoncode
from rc_report
where createdon >= DATEADD(MONTH, -6, GETDATE())
group by reasoncode
union all
select count(*) Total,
'Sum'
from rc_report
where createdon >= DATEADD(MONTH, -6, GETDATE())
) RCTotal
on RCTotal.ReasonCode = RCMonth.ReasonCode
cross join (
select count(*) Total
from rc_report
where createdon >= DATEADD(MONTH, -6, GETDATE()) ) Total
order by RCMonth.ReasonCode

Related

Count for each day return wrong value

The below code gives a count of 1 for each day, and accumulates from today (13/04/2021) til the end of the month and sums them for Saturdays, Sundays and Week days.
;WITH mycte AS (
SELECT GETDATE() DateValue
UNION ALL
SELECT DateValue + 1
FROM mycte
WHERE DateValue < EOMONTH(dateadd(day,-1, getdate()))
)
select
count(case when datepart(dw, DateValue) = 1 then 1 end) SunCount
, count(case when datepart(dw, DateValue) = 7 then 1 end) SatCount
, count(case when datepart(dw, DateValue) between 1 and 7 then 1 end) WeekCount
from mycte
For today (13/04/2021) I would expect the count to be Saturday = 2, Sunday = 2, and Weekdays to be 14 but instead I get 18 til the end of April - why is that?
I think it is because 'between' includes 1 and 7 again, below query should give you remaining 14 week days
;WITH mycte AS (
SELECT GETDATE() DateValue
UNION ALL
SELECT DateValue + 1
FROM mycte
WHERE DateValue < EOMONTH(dateadd(day,-1, getdate()))
)
select
count(case when datepart(dw, DateValue) = 1 then 1 end) SunCount
, count(case when datepart(dw, DateValue) = 7 then 1 end) SatCount
, count(case when datepart(dw, DateValue) between 2 and 6 then 1 end) WeekCount
from mycte

My count CTE returning blanks, how can I get it return as 0?

CTE created to count the number of days left from today's date to end of current month. So my report for today (30 March 2021) did not count tomorrow's date 31 March 2021.
declare #DespatchTo Date = '03-30-2021'
WITH mycte AS
(
SELECT CAST(Convert(date,getdate()) AS DATETIME) DateValue
UNION ALL
SELECT DateValue + 1
FROM mycte
WHERE DateValue < DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, #DespatchTo) + 1, 0)) --03-31-2021
)
SELECT SUN.Count as SunCount, SAT.Count as SatCount, WK.Count as WeekCount
FROM
(SELECT count(*) as Count
FROM mycte
WHERE DatePart("w",DateValue) = 1
group by DatePart("w",DateValue))
As SUN,
(SELECT count(*) as Count
FROM mycte
WHERE DatePart("w",DateValue) = 7
group by DatePart("w",DateValue))
As SAT,
(SELECT distinct SUM(COUNT(*)) OVER() AS Count
FROM mycte
WHERE DatePart("w",DateValue) > 1 AND DatePart("w",DateValue) < 7
group by DatePart("w",DateValue))
As WK
Which returns blank/null results. How can I return as 0?
here is what you need to do:
;WITH mycte AS (
SELECT GETDATE() DateValue
UNION ALL
SELECT DateValue + 1
FROM mycte
WHERE DateValue < EOMONTH(GETDATE())
)
select
count(case when datepart(dw, DateValue) = 1 then 1 end) SUN
, count(case when datepart(dw, DateValue) = 7 then 1 end) SAT
, count(case when datepart(dw, DateValue) between 2 and 6 then 1 end) WK
from mycte
if you want to exclude today, you can adjust cte :
;WITH mycte AS (
SELECT GETDATE() + 1 DateValue
WHERE GETDATE() <> EOMONTH(GETDATE())
UNION ALL
SELECT DateValue + 1
FROM mycte
WHERE DateValue < EOMONTH(GETDATE())
)
select
count(case when datepart(dw, DateValue) = 1 then 1 end) SUN
, count(case when datepart(dw, DateValue) = 7 then 1 end) SAT
, count(case when datepart(dw, DateValue) between 2 and 6 then 1 end) WK
from mycte

Counting distinct members based on number of months in duration of time

I have a membership table with the following columns:
Member_number | StartDate | EndDate
XYZ | 01-Jan-2002 | 01-March-2002
ABC | 01-Feb-2002 | 01-March-2002
Basically, I want to show how many members were present in specific month. My problem is I don't know how to break this time span into months. How can I see this result?
Month | NumberOfMembers
Jan | 1
Feb | 2
March | 2
Given a members table that looks something like this:
create table dbo.members
(
member_number int not null primary key ,
start_date datetime not null ,
end_date datetime not null ,
)
And a table-valued function that generates sequences of consecutive integers, like this:
create function dbo.IntegerRange ( #from int , #thru int )
returns #sequence table
(
value int not null primary key clustered
)
as
begin
declare #increment int = case when #from > #thru then -1 else 1 end ;
with sequence(value) as
(
select value = #from
union all
select value + #increment
from sequence
where value < #thru
)
insert #sequence
select value
from sequence
order by value
option ( MAXRECURSION 0 )
return
end
A query like this should give you what you want:
select [year] = period.yyyy ,
[month] = case period.mm ,
when 1 then 'Jan'
when 2 then 'Feb'
when 3 then 'Mar'
when 4 then 'Apr'
when 5 then 'May'
when 6 then 'Jun'
when 7 then 'Jul'
when 8 then 'Aug'
when 9 then 'Sep'
when 10 then 'Oct'
when 11 then 'Nov'
when 12 then 'Dev'
else '***'
end ,
member_cnt = sum( case when m.member_number is not null then 1 else 0 end )
from ( select yyyy = yyyy.value ,
mm = mm.value ,
dtFrom = dateadd( month , mm.value - 1 , dateadd( year , yyyy.value - 1900 , convert(date,'') ) ) ,
dtThru = dateadd( day , - 1 , dateadd( month , mm.value , dateadd( year , yyyy.value - 1900 , convert(date,'') ) ) )
from dbo.IntegerRange(2000,2013) yyyy
full join dbo.IntegerRange(1,12) mm on 1=1
) period
left join dbo.members m on period.dtFrom <= m.end_date
and period.dtThru >= m.start_date
group by period.yyyy ,
period.mm
order by period.yyyy ,
period.mm
The first table expression in the from clause creates a virtual table of the periods (months, in this case, but the technique doesn't limit itself to months or even weeks) covering the reporting period:
from ( select yyyy = yyyy.value ,
mm = mm.value ,
dtFrom = dateadd( month , mm.value - 1 , dateadd( year , yyyy.value - 1900 , convert(date,'') ) ) ,
dtThru = dateadd( day , - 1 , dateadd( month , mm.value , dateadd( year , yyyy.value - 1900 , convert(date,'') ) ) )
from dbo.IntegerRange(2000,2013) yyyy
full join dbo.IntegerRange(1,12) mm on 1=1
) period
That is then joined, via a left outer join, ensuring that all periods are reported, not just those periods with active members, to the members table to collect, for each reporting period in the virtual period table above, the set of members who were active during the period:
left join dbo.members m on period.dtFrom <= m.end_date
and period.dtThru >= m.start_date
We then group by the year and month of each period and then order the results by year/month number:
group by period.yyyy ,
period.mm
order by period.yyyy ,
period.mm
In creating the results set to be returned, we return the year of the period, the month number (converted to a friendly name), and the count of active members. Note that we have to use the sum() aggregate function here rather than count() as empty periods will have a single row returned (with null in all columns). Count(), unlike all other aggregate functions, includes null values in the aggregation. Sum() is applied to a case expression acting as a discriminant function returning 1 or 0 identifying whether the row indicates useful or missing data:
select [year] = period.yyyy ,
[month] = case period.mm ,
when 1 then 'Jan'
when 2 then 'Feb'
when 3 then 'Mar'
when 4 then 'Apr'
when 5 then 'May'
when 6 then 'Jun'
when 7 then 'Jul'
when 8 then 'Aug'
when 9 then 'Sep'
when 10 then 'Oct'
when 11 then 'Nov'
when 12 then 'Dev'
else '***'
end ,
member_cnt = sum( case when m.member_number is not null then 1 else 0 end )
Easy!
DECLARE #minMonth DATE
SELECT #minMonth = MIN(StartDate) FROM Table1
DECLARE #maxMonth DATE
SELECT #maxMonth = MAX(EndDate) FROM Table1
;WITH CTE_Months AS
(
SELECT #minMonth AS Mnth
UNION ALL
SELECT DATEADD(MM,1,Mnth) FROM CTE_Months
WHERE Mnth<#MaxMonth
)
SELECT Mnth AS Month, COUNT(*) as Members
FROM CTE_Months m
LEFT JOIN Table1 t on m.Mnth BETWEEN t.StartDate AND t.EndDate
GROUP BY Mnth
SQLFiddle Demo
CTE will find all months from min StartDate to max EndDate, if you need different min and max, just change how you get #MinMonth and #MaxMonth
If you don't want to show zeros for months that possibly don't have any members, replace LEFT JOIN with INNER at the end.
select t.Month, count(*) Members
from (
select case
when startdate <= to_date('01-Jan-2002', 'DD-MON-YYYY') AND enddate >= to_date('31-Jan-2002', 'DD-MON-YYYY') then ' Jan'
when startdate <= to_date('01-Feb-2002', 'DD-MON-YYYY') AND enddate >= to_date('28-Feb-2002', 'DD-MON-YYYY') then ' Feb'
when startdate <= to_date('01-Mar-2002', 'DD-MON-YYYY') AND enddate >= to_date('31-Mar-2002', 'DD-MON-YYYY') then ' Mar'
when startdate <= to_date('01-Apr-2002', 'DD-MON-YYYY') AND enddate >= to_date('30-Apr-2002', 'DD-MON-YYYY') then ' Apr'
when startdate <= to_date('01-May-2002', 'DD-MON-YYYY') AND enddate >= to_date('31-May-2002', 'DD-MON-YYYY') then ' May'
when startdate <= to_date('01-Jun-2002', 'DD-MON-YYYY') AND enddate >= to_date('30-Jun-2002', 'DD-MON-YYYY') then ' Jun'
when startdate <= to_date('01-Jul-2002', 'DD-MON-YYYY') AND enddate >= to_date('31-Jul-2002', 'DD-MON-YYYY') then ' Jul'
when startdate <= to_date('01-Aug-2002', 'DD-MON-YYYY') AND enddate >= to_date('31-Aug-2002', 'DD-MON-YYYY') then ' Aug'
when startdate <= to_date('01-Sep-2002', 'DD-MON-YYYY') AND enddate >= to_date('30-Sep-2002', 'DD-MON-YYYY') then ' Sep'
when startdate <= to_date('01-Oct-2002', 'DD-MON-YYYY') AND enddate >= to_date('31-Oct-2002', 'DD-MON-YYYY') then ' Oct'
when startdate <= to_date('01-Nov-2002', 'DD-MON-YYYY') AND enddate >= to_date('30-Nov-2002', 'DD-MON-YYYY') then ' Nov'
when startdate <= to_date('01-Dec-2002', 'DD-MON-YYYY') AND enddate >= to_date('31-Dec-2002', 'DD-MON-YYYY') then ' Dec'
end as Month
from member) t
group by t.Month
Where member is the table name.

SQL Results group by month

I'm trying to return some results spread over a rolling 12 month period eg:
MONTH IN OUT
January 210 191
February 200 111
March 132 141
April 112 141
May 191 188
etc...
How do I spread the results over a date range, populating the first column with the month name?
IN MSSQL it would be something like:
SELECT COUNT(problem.problem_type = 'IN') AS IN,
COUNT(problem.problem_type = 'OUT') AS OUT,
DATEPART(year, DateTime) as Year,
DATEPART(month, DateTime) as Month
FROM problem
WHERE (DateTime >= dbo.FormatDateTime('2010-01-01'))
AND
(DateTime < dbo.FormatDateTime('2010-01-31'))
GROUP BY DATEPART(year, DateTime),
DATEPART(month, DateTime);
But this is against an Oracle database so DATEPART and DateTime are not available.
My Problem table is roughly:
problem_ID Problem_type IN_Date OUT_Date
1 IN 2010-01-23 16:34:29.0 2010-02-29 13:06:28.0
2 IN 2010-01-27 12:34:29.0 2010-01-29 12:01:28.0
3 OUT 2010-02-13 13:24:29.0 2010-09-29 15:04:28.0
4 OUT 2010-02-15 16:31:29.0 2010-07-29 11:03:28.0
Use:
SELECT SUM(CASE WHEN p.problem_type = 'IN' THEN 1 ELSE 0 END) AS IN,
SUM(CASE WHEN p.problem_type = 'OUT' THEN 1 ELSE 0 END) AS OUT,
TO_CHAR(datetime, 'YYYY') AS year,
TO_CHAR(datetime, 'MM') AS month
FROM PROBLEM p
WHERE p.DateTime >= TO_DATE('2010-01-01', 'YYYY-MM-DD')
AND p.DateTime < TO_DATE('2010-01-31', 'YYYY-MM-DD')
GROUP BY TO_CHAR(datetime, 'YYYY'), TO_CHAR(datetime, 'MM')
You could also use:
SELECT SUM(CASE WHEN p.problem_type = 'IN' THEN 1 ELSE 0 END) AS IN,
SUM(CASE WHEN p.problem_type = 'OUT' THEN 1 ELSE 0 END) AS OUT,
TO_CHAR(datetime, 'MM-YYYY') AS mon_year
FROM PROBLEM p
WHERE p.DateTime >= TO_DATE('2010-01-01', 'YYYY-MM-DD')
AND p.DateTime < TO_DATE('2010-01-31', 'YYYY-MM-DD')
GROUP BY TO_CHAR(datetime, 'MM-YYYY')
Reference:
TO_CHAR
TO_DATE
You probably want something like
SELECT SUM( (CASE WHEN problem_type = 'IN' THEN 1 ELSE 0 END) ) in,
SUM( (CASE WHEN problem_type = 'OUT' THEN 1 ELSE 0 END) ) out,
EXTRACT( year FROM DateTime ) year,
EXTRACT( month FROM DateTime ) month
FROM problem
WHERE DateTime >= date '2010-01-01'
AND DateTime < date '2010-01-31'
GROUP BY EXTRACT( year FROM DateTime ),
EXTRACT( month FROM DateTime )

breakdown by weeks

Below is a simple query and the result: Is the a way to aggregate the total EVENTs by 7 days, then sum up the total EVENTs? Would a rollup function work? I am using SQL SERVER 05 & 08. Thanks again, folks.
SELECT DATE_SOLD, count(DISTINCT PRODUCTS) AS PRODUCT_SOLD
FROM PRODUCTS
WHERE DATE >='10/1/2009'
and DATE <'10/1/2010'
GROUP BY DATE_SOLD
RESULTS:
DATE_SOLD PRODUCT_SOLD
10/1/09 5
10/2/09 11
10/3/09 14
10/4/09 6
10/5/09 11
10/6/09 13
10/7/09 10
Total 70
10/8/09 4
10/9/09 11
10/10/09 8
10/11/09 4
10/12/09 7
10/13/09 4
10/14/09 9
Total 47
Not having your table design to work with here's what I think you are after (although I have to admit the output needs to be cleaned up). It should, at least, get you some way to the solution you are looking for.
CREATE TABLE MyTable(
event_date date,
event_type char(1)
)
GO
INSERT MyTable VALUES ('2009-1-01', 'A')
INSERT MyTable VALUES ('2009-1-11', 'B')
INSERT MyTable VALUES ('2009-1-11', 'C')
INSERT MyTable VALUES ('2009-1-20', 'N')
INSERT MyTable VALUES ('2009-1-20', 'N')
INSERT MyTable VALUES ('2009-5-23', 'D')
INSERT MyTable VALUES ('2009-5-23', 'E')
INSERT MyTable VALUES ('2009-5-10', 'F')
INSERT MyTable VALUES ('2009-5-10', 'F')
GO
WITH T AS (
SELECT DATEPART(MONTH, event_date) event_month, event_date, event_type
FROM MyTable
)
SELECT CASE WHEN (GROUPING(event_month) = 0)
THEN event_month ELSE '99' END AS event_month,
CASE WHEN (GROUPING(event_date) = 1)
THEN '9999-12-31' ELSE event_date END AS event_date,
COUNT(DISTINCT event_type) AS event_count
FROM T
GROUP BY event_month, event_date WITH ROLLUP
ORDER BY event_month, event_date
This gives the following output:
event_month event_date event_count
1 2009-01-01 1
1 2009-01-11 2
1 2009-01-20 1
1 9999-12-31 4
5 2009-05-10 1
5 2009-05-23 2
5 9999-12-31 3
99 9999-12-31 7
Where the '99' for month and '9999-12-31' for year are the totals.
SELECT DATEDIFF(week, 0, DATE_SOLD) Week,
DATEADD(week, DATEDIFF(week, 0, DATE_SOLD), 0) From,
DATEADD(week, DATEDIFF(week, 0, DATE_SOLD), 0) + 6 To,
COUNT(DISTINCT PRODUCTS) PRODUCT_SOLD
FROM dbo.PRODUCTS
WHERE DATE >= '2009-10-01'
AND DATE < '2010-10-01'
GROUP BY DATEDIFF(week, 0, DATE_SOLD) WITH ROLLUP
ORDER BY DATEDIFF(week, 0, DATE_SOLD)