The_kite
2014-02-12 18:36
浏览 265
已采纳

关与DB2数据库将多个count语句合为一个。

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中不可以。。。

 

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • zyn010101 2014-02-12 19:16
    已采纳

    select grade,count(*) from db1 where grade = 0 or grade = 1 or grade = 2 or grade = 3 group by grade;

    已采纳该答案
    打赏 评论
  • joaboo 2014-02-13 00:04

    这样写貌似好一点..mysql,db2,oracle等都通用..
    [code="sql"]
    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 g4
    from db1;
    [/code]

    打赏 评论

相关推荐 更多相似问题