日期:2014-05-16  浏览次数:20570 次

获取一条记录全部由子查询某个条件的记录数构成该如何写呢
select count (1) where flag=1
select count (1) where flag=2
select count (1) where flag=3
......
这样的数据写到一条记录里,该如何做呢?

------解决方案--------------------
select count (1) [count] where flag=1
union all 
select count (1) where flag=2
union all 
select count (1) where flag=3
------解决方案--------------------
SELECT SUM(CASE WHEN FLAG=1 THEN 1 ELSE 0 END) AS F1, SUM(CASE WHEN FLAG=2 THEN 1 ELSE 0 END) AS F2, SUM(CASE WHEN FLAG=3 THEN 1 ELSE 0 END) AS F3
FROM T 
------解决方案--------------------

select sum(case when flag=1 then 1 else 0 end) 'flag1_qty',
            sum(case when flag=2 then 1 else 0 end) 'flag2_qty',
            sum(case when flag=3 then 1 else 0 end) 'flag3_qty'
 from [表名]
 where [条件]