如何添加两个选择查询

时间:2014-10-15 16:02:56

标签: sql sql-server sql-server-2012

可以进行以下的sql查询。
我希望在不同列中的同一个表中有三个计数,只有一个查询。

select COUNT(Status) as attendedcount from Ebrahim_30359715 where Status='Attended' 
UNION 
select COUNT(Status) as notallocatedcount from Ebrahim_30359715  where Status='Not Allocated'
UNION 
select COUNT(Status) as allocatedbutnotcount from Ebrahim_30359715  where Status='Allocated But Not Attended'

2 个答案:

答案 0 :(得分:2)

更好地使用

select SUM(case when Status='Attended' then 1 end) as attendedcount,
       SUM(case when Status='Not Attended' then 1 end) as notallocatedcount,
       SUM(case when Status='Allocated But Not Attended' then 1 end) as allocatedbutnotcount
from Ebrahim_30359715

使用union,您必须创建3个不同的列,或者添加一个额外的列,指示您在column1中存储的值。

答案 1 :(得分:1)

试试这个。这也适用于新的状态。你不必明确提到状态

DECLARE @cols AS VARCHAR(max), 
        @sql  AS NVARCHAR(max) 

SELECT @cols = Stuff((SELECT ',' + Quotename(status) 
                      FROM   Ebrahim_30359715
                      GROUP  BY status 
                      FOR xml path(''), type).value('.', 'VARCHAR(MAX)'), 1, 1,'') 

SET @sql = 'select *  from  
                      (select count(1) as cnt ,status
                       from Ebrahim_30359715
                       group by status )
            src pivot (max(cnt) for status in (' + @cols + ')) piv' 

EXEC Sp_executesql 
     @sql