SQL - 将两个计数显示为同一个表中的列

时间:2014-04-17 18:35:17

标签: sql sql-server select

我刚开始编写SQL并遇到问题。这是我的疑问:

select count(*) as new_column1
  from table1
 where column1 = 'x' and column2 = 'y' and column3 = 'z'`

 select count(*) as new_column2
 from table 1
 where column1 = 'xx' and column2 = 'yy' and column3 = 'zz'

查询2的结果显示在查询1下面。如何在查询1的结果旁边获得查询2的结果?使用SQL Server Management Studio 2008.感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您想使用条件聚合:

select sum(case when column1 = 'x' and column2 = 'y' and column3 = 'z' then 1 else 0
           end) as new_column1,
       sum(case when column1 = 'xx' and column2 = 'yy' and column3 = 'zz' then 1 else 0
           end) as new_column2
from table1 ;

如果您碰巧在所有三列上都有复合索引,那么以下方法可能会更快:

select (select count(*)
        from table1
        where column1 = 'x' and column2 = 'y' and column3 = 'z'
       ) as new_column1,
       (select count(*) 
        from table 1
        where column1 = 'xx' and column2 = 'yy' and column3 = 'zz'
       ) as as new_column2;