问题描述
select count(*) from db1 where grade = 0;select count(*) from db1 where grade = 1;select count(*) from db1 where grade = 2;select count(*) from db1 where grade = 3; 以上4条sql,合成一条可以实现吗? 为什么在mysql中可以这样实现:SELECT (SELECT COUNT(*) FROM db1 WHERE gread = 1) AS g1,(SELECT COUNT(*) FROM db1WHERE gread = 2) AS g2; 而DB2中不可以。。。
解决方案
select grade,count(*) from db1 where grade = 0 or grade = 1 or grade = 2 or grade = 3 group by grade;
解决方案二:
这样写貌似好一点..mysql,db2,oracle等都通用..select count(case when grade = 1 then 1 else null end) as g1, count(case when grade = 2 then 1 else null end) as g2, count(case when grade = 3 then 1 else null end) as g3, count(case when grade = 4 then 1 else null end) as g4from db1;
时间: 2024-10-01 12:06:22