Reputation: 443
I am trying to count the number of times [Tracking id] & [Tracking ID1] appear in a table.
The result should look like this.
This works great when I use a group by function.
select [Group], datename(month,[date]) as Month, count([Tracking ID]) + count([Tracking ID1]) as [Number of Record]
from [Table]
group by
[Group],
datename(month,[date])
I need to use a pivot function. How do I modify the code below to get the desired results
select *
from
(
select
[Group], datename(month,[date]) as Month, (count([Tracking ID])over () + count([Tracking ID1]) over () ) as [Number of Record]
From
[Table]
) sourcetbl
pivot
(count([Number of Record])
for [Month] in ([June], [July])
) as pivotTable;
Currently, my query returns 2 instead of 4.
Upvotes: 0
Views: 83
Reputation: 81
This should work based on the information provided:
SELECT
[Group],
ISNULL([June], 0) AS [June],
ISNULL([July], 0) AS [July]
FROM
(
SELECT
[Group],
DATENAME(MONTH, [Date]) AS [Date],
COUNT(Tracking_ID) + COUNT(Tracking_ID1) AS NumberOfRecords
FROM [Table]
GROUP BY [Group], [Date]
) AS D
PIVOT
(
MAX(NumberOfRecords)
FOR [Date] IN
(
[June],
[July]
)
) AS PIV
It seems the OVER() parts in your query were causing the COUNT functions to not behave as aggregate functions, thus your query works without a GROUP BY where in this case it needs to have a GROUP BY.
Upvotes: 0
Reputation: 1269583
Just use conditional aggregation:
select [Group],
sum(case when month([date]) = 6 then 1 else 0 end) as jun,
sum(case when month([date]) = 7 then 1 else 0 end) as jul
from [Table]
group by [Group];
Upvotes: 2