如何使用一个SQL查询获得多个计数?我想知道如何写这个查询。我知道这个实际的语法是假的,但是它会帮助你理解我想要什么。我需要这种格式,因为它是一个大得多的查询的一部分。SELECT distributor_id, COUNT(*) AS TOTAL, COUNT(*) WHERE level = 'exec', COUNT(*) WHERE level = 'personal'我需要在一个查询中返回所有这些。另外,它需要在一行中,因此以下内容无法工作:'SELECT distributor_id, COUNT(*)
GROUP BY distributor_id'
3 回答
幕布斯7119047
TA贡献1794条经验 获得超8个赞
CASE
PIVOT
select distributor_id, count(*) total, sum(case when level = 'exec' then 1 else 0 end) ExecCount, sum(case when level = 'personal' then 1 else 0 end) PersonalCountfrom yourtablegroup by distributor_id
幕布斯6054654
TA贡献1876条经验 获得超7个赞
SELECT a.distributor_id, (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount, (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount, (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCountFROM (SELECT DISTINCT distributor_id FROM myTable) a ;
编辑:
白板的微信
TA贡献1883条经验 获得超3个赞
SELECT distributor_id, COUNT(*) AS TOTAL, COUNT(IF(level='exec',1,null)), COUNT(IF(level='personal',1,null))FROM sometable;
COUNT
non null
DECODE
1
添加回答
举报
0/150
提交
取消