当前位置: 代码迷 >> Sql Server >> 求SQL,依据条件统计信息
  详细解决方案

求SQL,依据条件统计信息

热度:61   发布时间:2016-04-24 10:21:43.0
求SQL,根据条件统计信息
表A的结构是:id, articleID, typeID
我想实现的是能不能用一条SQL直接把当typeID=1、2、3时分别统计出来
要这样:select count(typeID=1)  as down,t count(typeID=2)  as read,t count(typeID=3)  as show from a group by articleID  这种写法是错的,我的意思就是想这样,不知道各位大神们觉得能实现否?
------解决方案--------------------
select  articleid,
count(case when typeID=1 then 1 else null end)  as down,
count(case when typeID=2 then 1 else null end)  as read,
count(case when typeID=3 then 1 else null end)  as show 
from a 
group by articleID  
------解决方案--------------------
select articleID,
max(case when  typeID=1  then count (typeID)else 0 end ) as [down],
max(case when  typeID=2 then count (typeID) else 0 end)  as [read],
max(case when  typeID=3 then count (typeID) else 0 end) as  [show]
 from a group by articleID

------解决方案--------------------
select sum(case typeid when 1 then 1 else 0 end) down,
sum(case typeid when 2 then 1 else 0 end) read,
sum(case typeid when 3 then 1 else 0 end) show,
from a
------解决方案--------------------
引用:
 select count(CASE WHEN typeID=1 THEN 1 ELSE 0 END)  as down, count(CASE WHEN typeID=2 THEN 1 ELSE 0 END)  as read, count(CASE WHEN typeID=3 THEN 1 ELSE 0 END)  as show from a group by articleID  

额。。。错了。。select count(CASE WHEN typeID=1 THEN 1 ELSE null END)  as down, count(CASE WHEN typeID=2 THEN 1 ELSE null  END)  as read, count(CASE WHEN typeID=3 THEN 1 ELSE null END)  as show from a group by articleID 
--
 select SUM(CASE WHEN typeID=1 THEN 1 ELSE 0 END)  as down
, SUM(CASE WHEN typeID=2 THEN 1 ELSE 0  END)  as READ
, SUM(CASE WHEN typeID=3 THEN 1 ELSE 0 END)  as show 
from a group by articleID 
  相关解决方案