我有一个类似的查询:
SELECT count( * ) AS total, remaining
FROM cold_clients, (
SELECT count( * ) AS remaining
FROM cold_clients
WHERE sic_code = '754901'
AND STATUS = 'COLD'
) AS r
WHERE sic_code = '754901';
我得到了正确的sic代码和剩余的sic代码的正确结果。 但是,它特定于sic代码的特定价值。 我希望得到所有的sic代码,包括它的总值和剩余值。
我尝试过group by,但是,它给了我错误的价值。
答案 0 :(得分:4)
使用条件聚合:
SELECT count( * ) AS total,
sum(STATUS = 'COLD') as remaining
FROM cold_clients
WHERE sic_code = '754901';
对于所有sic_code
,请使用聚合:
SELECT sic_code, count(*) AS total,
sum(STATUS = 'COLD') as remaining
FROM cold_clients
GROUP BY sic_code;