感谢Quassnoi之前谁给了我正在寻找的答案 - 这导致了一个单独的问题。目前的代码:
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
这确切地说明了我想要的内容(C.CATEGORY_ID&lt;&gt; 30)未包含在标记为TotalWithoutNew的初始列中。我也需要值WITH WITH。有没有办法让另一个名为TotalWithNew的列包含所有CATEGORY_ID?我肯定今天学习了很多新的查询语言!
答案 0 :(得分:2)
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
注意:我没有尝试,但我希望您能够使用CASE WHEN ...
。
答案 1 :(得分:0)
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