我有一个查询,它返回不止一次出现的不同device_type的行数。
SELECT COUNT(*) AS C1,device_type FROM stat
WHERE stat_date = '2012-02-08'
GROUP BY 2 HAVING C1 > 1
ORDER BY 1 DESC
我想将剩余的(HAVING count = 1)行总结为'others'
如何将COUNT(*)和'others'的总和添加为以下查询的第二列?
SELECT COUNT(*) AS C2,device_type FROM stat
WHERE stat_date = '2012-02-08'
GROUP BY 2 HAVING C2 = 1
ORDER BY 1 DESC
DB中的示例数据
device_type
dt1
dt1
dt1
dt2
dt2
dt3
dt4
dt5
预期结果
3 dt1
2 dt2
3 other
答案 0 :(得分:4)
我会这样做。
SELECT COUNT(*) AS C1,device_type FROM stat
WHERE stat_date = '2012-02-08'
GROUP BY 2 HAVING C1 > 1
ORDER BY 1 DESC
Union
SELECT Sum(1),'OTHERS'FROM stat
WHERE stat_date = '2012-02-08'
GROUP BY 2 HAVING C1 =1
ORDER BY 1 DESC
答案 1 :(得分:3)
您也可以尝试:
SELECT SUM(C1) AS C1, CASE WHEN C1 = 1 THEN 'other' ELSE device_type END as device_type
FROM ( SELECT COUNT(*) AS C1,
device_type
FROM stat
WHERE stat_date = '2012-02-08'
GROUP BY device_type) A
GROUP BY CASE WHEN C1 = 1 THEN 'other' ELSE device_type END