日期:2014-05-18  浏览次数:20520 次

count条件查询求解
SQL code

CREATE TABLE [rjh] (
    [id] [decimal](18, 0) IDENTITY (1, 1) NOT NULL ,
    [d_id] [decimal](18, 0) NOT NULL ,
    [rq] [datetime] NOT NULL ,
    [jth] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [bcl] [int] NULL ,
    [zhong] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [ye] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [zao] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [bz] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL 
) ON [PRIMARY]

insert into rjh(d_id,rq,jth,bcl,zhong,ye,zao,bz) values(1,'2012-3-26','c11',550,'','停','','')
insert into rjh(d_id,rq,jth,bcl,zhong,ye,zao,bz) values(5,'2012-3-26','c12',650,'','','停','停')
insert into rjh(d_id,rq,jth,bcl,zhong,ye,zao,bz) values(5,'2012-3-26','c13',750,'','停','','停')
insert into rjh(d_id,rq,jth,bcl,zhong,ye,zao,bz) values(4,'2012-3-26','c14',850,'','','','停')
insert into rjh(d_id,rq,jth,bcl,zhong,ye,zao,bz) values(5,'2012-3-26','c15',550,'','','停','')
insert into rjh(d_id,rq,jth,bcl,zhong,ye,zao,bz) values(5,'2012-3-26','c16',450,'','','','')
insert into rjh(d_id,rq,jth,bcl,zhong,ye,zao,bz) values(4,'2012-3-26','c14',850,'','','','停')
insert into rjh(d_id,rq,jth,bcl,zhong,ye,zao,bz) values(5,'2012-3-26','c15',550,'','','停','')
insert into rjh(d_id,rq,jth,bcl,zhong,ye,zao,bz) values(6,'2012-3-26','c16',450,'','','','')

GO
需要查询出 where d_id=5 ,  zhong,ye,zao 3个字段等于'停'的个数总和  结果应该是 6 ,求教怎么写sql语句





------解决方案--------------------
SQL code
select sum(case when zhong='停' then 1 else 0 end)
+ sum(case when ye='停' then 1 else 0 end)
+ sum(case when zao='停' then 1 else 0 end)
 from tb 
 where d_id=5