不使用HAVING,如果总计为5或更多,我怎样才能让SQL结果在COUNT列中显示总和?
SELECT DISTINCT
[ID],
COUNT(CASE WHEN [ICN] >=5 THEN 1 END) AS 'COUNT'
FROM DBO.[OFD]
WHERE [YEAR] = 2018
AND [LOCATION-ID] = '0021'
GROUP BY [ID],
[ICN]
当我输入以下代码时,我得到的结果与下面的例子类似......
SELECT DISTINCT
[ID],
[ICN]
FROM DBO.[OFD]
WHERE [YEAR] = 2018
AND [LOCATION-ID] = '0021'
GROUP BY [STUDENT-ID],
[INCIDENT-NO]
答案 0 :(得分:0)
请尝试此查询。希望这可能会有所帮助
;WITH cte_data (id,NumberOfrows)
AS
(
SELECT ID, COUNT(*)NumberOfrows
FROM DBO.[OFD] t
WHERE [YEAR] = 2018
AND [LOCATIONID] = '0021'
AND INNO>=5
GROUP BY ID
)
SELECT DISTINCT t.id, isnull(NumberOfrows ,0) NumberOfrows
FROM DBO.[OFD] t
LEFT JOIN cte_data t1 on t1.id = t.id
WHERE t.[YEAR] = 2018
AND t.[LOCATIONID] = '0021'
答案 1 :(得分:0)
您需要检查< 5并使用sum而不是count
SELECT DISTINCT
[ID],
SUM(CASE WHEN [INNO] >=5 THEN 1 ELSE 0 END) AS 'COUNT'
FROM DBO.[OFD]
WHERE [YEAR] = 2018
AND [LOCATION-ID] = '0021'
GROUP BY [ID],[INNO]
更改为
SELECT DISTINCT
SUM(CASE WHEN [INNO] >=5 THEN 1 ELSE 0 END) AS 'COUNT'
FROM DBO.[OFD]
WHERE [YEAR] = 2018
AND [LOCATION-ID] = '0021'