让多个变量显示在sql server中?

时间:2011-12-21 14:03:38

标签: sql sql-server-2008

我有两个问题:

Select count(*) as countOne where field = '1'
Select count(*) as countTwo where field = '2'

在结果查看器中执行这些查询后我想看到的内容:

countOne | countTwo
      23 |      123

如何通过仅运行一个查询来获取两个查询的结果?

2 个答案:

答案 0 :(得分:4)

SELECT COUNT(CASE WHEN field = '1' THEN 1 END) AS countOne,
       COUNT(CASE WHEN field = '2' THEN 1 END) AS countTwo
FROM   YourTable
WHERE  field IN ( '1', '2' )  

答案 1 :(得分:0)

最简单的方法是将每个作为子选项运行,例如。

SELECT 
(
Select count(*) where field = '1' as countOne,
Select count(*) where field = '2' as countTwo
)

BUt这不是最好的方式

另一种方法是按字段分组,然后按PIVOT选择每个组作为单独的列。