please consider table below (TableName: Registration)
| Type1 | Type2 | Type3 | Type4 | Registration |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| 0 | 1 | 0 | 0 | 2023-05-29 |
| 1 | 0 | 0 | 0 | 2023-04-29 |
| 0 | 0 | 1 | 0 | 2023-05-29 |
| 0 | 0 | 0 | 1 | 2023-06-29 |
I'm looking for a query which groups the data by Type1, Type2, Type3, and Type4 and shows the sums of Amount having each one month so that it returns:
Month | Type1 | Type2 | Type3 | Type4 | Total |
---|---|---|---|---|---|
April | 1 | 0 | 0 | 0 | 1 |
May | 0 | 1 | 1 | 0 | 2 |
June | 0 | 0 | 0 | 1 | 1 |
July | 0 | 0 | 0 | 0 | 0 |
Here is my current SQL
SELECT
DATEPART(month, x.RegistrationDateTime) AS Closing_Month
, COUNT (x.Type1) ,
COUNT (x.Type2),
COUNT (x.Type3),
COUNT (x.Type4)
FROM(
SELECT
'Type1' =
CASE
WHEN r.inp = 1
AND bp.BusinessPartnerID = 508
THEN 1 ELSE 0
END
, 'Type2' =
CASE
WHEN r.inp = 0
AND bp.BusinessPartnerID = 508
THEN 1 ELSE 0
END
,'Type3' =
CASE
WHEN r.inp = 1
AND bp.BusinessPartnerID = 509
THEN 1 ELSE 0
END
, 'Type4' =
CASE
WHEN r.inp = 0
AND bp.BusinessPartnerID = 509
THEN 1 ELSE 0
END, Registration
FROM Registration AS r
INNER JOIN BusinessPartner bp ON r.id = bp.RegistrationID
) AS x
GROUP BY DATEPART(month, x.RegistrationDateTime),Type1,Type2,Type3,Type4;
1条答案
按热度按时间yrefmtwq1#
I've created an example with this code:
Trying to replicate what you've done. And with this query:
I've created your desired output as you can see here: