Follow on - Multiple Sums in SQL Query
Thanks to Quassnoi before who gave me the answer I was looking for - this led to a seperate problem though. Current code:
SELECT i.CONCOM, COALESCE (SUM(t.LOGMINS), 0) AS TotalWithoutNew
FROM INQUIRY AS i INNER JOIN
TIMELOG AS t ON t.INQUIRY_ID = i.INQUIRY_ID INNER JOIN
PROD AS P ON i.PROD_ID = P.PROD_ID INNER JOIN
CATEGORY AS C ON P.CATEGORY_ID = C.CATEGORY_ID
WHERE (DATEPART(month, i.ESCDATE) = DATEPART(month, GETDATE()) - 1) AND (DATEPART(year, i.ESCDATE) = DATEPART(year, DATEADD(m, - 1, GETDATE()))) AND
(C.CATEGORY_ID <> '30')
GROUP BY i.CONCOM
ORDER BY TotalWithoutNew DESC
This brings back exactly what I want (C.CATEGORY_ID <> 30) is not included in the initial column marked as TotalWithoutNew. I also need the value WITH it in as well though. Is there any way to have another column called TotalWithNew that includes all CATEGORY_IDs? I am certain learning a lot of new query langua开发者_运维问答ge today!
SELECT i.CONCOM,
COALESCE (SUM(CASE WHEN C.CATEGORY_ID = '30' THEN 0 ELSE t.LOGMINS END), 0) AS TotalAllID,
COALESCE (SUM(t.LOGMINS), 0) AS TotalWithoutNew
FROM INQUIRY AS i INNER JOIN
TIMELOG AS t ON t.INQUIRY_ID = i.INQUIRY_ID INNER JOIN
PROD AS P ON i.PROD_ID = P.PROD_ID INNER JOIN
CATEGORY AS C ON P.CATEGORY_ID = C.CATEGORY_ID
WHERE (DATEPART(month, i.ESCDATE) = DATEPART(month, GETDATE()) - 1) AND (DATEPART(year, i.ESCDATE) = DATEPART(year, DATEADD(m, - 1, GETDATE())))
GROUP BY i.CONCOM
ORDER BY TotalWithoutNew DESC
Note: I haven't tried but I hope you get the idea of using CASE WHEN ...
.
SELECT i.CONCOM
, COALESCE(SUM(CASE WHEN C.CATEGORY_ID <> 30 THEN t.LOGMINS END), 0)
AS TotalWithoutNew
, COALESCE(SUM(t.LOGMINS), 0) AS TotalWithNew
FROM INQUIRY AS i INNER JOIN
TIMELOG AS t ON t.INQUIRY_ID = i.INQUIRY_ID INNER JOIN
PROD AS P ON i.PROD_ID = P.PROD_ID INNER JOIN
CATEGORY AS C ON P.CATEGORY_ID = C.CATEGORY_ID
WHERE (DATEPART(month, i.ESCDATE) = DATEPART(month, GETDATE()) - 1)
AND (DATEPART(year, i.ESCDATE) = DATEPART(year, DATEADD(m, - 1, GETDATE())))
GROUP BY i.CONCOM
ORDER BY TotalWithoutNew DESC
精彩评论