Sql 如何统计不同条件和相同外键Id的发生次数?
假设我有一张桌子: 订单: 订单编号 数学书 科学书 英语书 学生 1. 1. 1. 2. 1. 1. 3. 1. 1. 4. 1. 2. 5. 1. 3. 6. 1. 3. 7. 1. 4. 8. 1. 4. 9 1. 5. 10 1. 5.Sql 如何统计不同条件和相同外键Id的发生次数?,sql,sql-server,Sql,Sql Server,假设我有一张桌子: 订单: 订单编号 数学书 科学书 英语书 学生 1. 1. 1. 2. 1. 1. 3. 1. 1. 4. 1. 2. 5. 1. 3. 6. 1. 3. 7. 1. 4. 8. 1. 4. 9 1. 5. 10 1. 5. 如果我没弄错的话,你想要的是组合——但要连续的。首先是学生层面的聚合;然后再次汇总: select sum(case when max > 0 and science > 0 and english > 0 then 1 else 0
如果我没弄错的话,你想要的是组合——但要连续的。首先是学生层面的聚合;然后再次汇总:
select sum(case when max > 0 and science > 0 and english > 0 then 1 else 0 end) as all,
sum(case when math > 0 and science > 0 then 1 else 0 end) as math_science,
sum(case when science > 0 and english > 0 then 1 else 0 end) as science_english
from (select studentid,
max(mathbook) as math,
max(sciencebook) as science,
max(englishbook) as english
from t
group by studentid
) s
为什么所有的书都是1,不是应该是3吗?不,桌子上只有一个学生有一本书谢谢!这正是我需要的。。。现在来复习一下子查询实践