如何使用一个SQL查询获得多个计数?我想知道如何写这个查询。我知道这个实际的语法是假的,但是它会帮助你理解我想要什么。我需要这种格式,因为它是一个大得多的查询的一部分。SELECT distributor_id, COUNT(*) AS TOTAL, COUNT(*) WHERE level = 'exec', COUNT(*) WHERE level = 'personal'我需要在一个查询中返回所有这些。另外,它需要在一行中,因此以下内容无法工作:'SELECT distributor_id, COUNT(*)
GROUP BY distributor_id'
3 回答
芜湖不芜
TA贡献1796条经验 获得超7个赞
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
繁星淼淼
TA贡献1775条经验 获得超11个赞
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贡献1820条经验 获得超10个赞
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
提交
取消