在一个查询中获取两个完全不同的列

时间:2013-09-24 08:31:22

标签: sql sql-server

我正在开发一个asp.net项目。我需要使用两种不同的条件过滤数据库,并在饼图中显示每个条件。所以我需要在一个查询中获得两列。

第1栏:

select COUNT (*) 'OAS' from atmterminalfile (nolock) where Atstatu='2' and atlinestat ='1'

第2栏:

select COUNT (*) 'OFS'  from atmterminalfile (nolock) where Atstatu='2' and atlinestat ='2'

我搜索了很多解决方案,我尝试了UNION,但结果是这个

|      OAS       |
|----------------|
| Column 1 Count |
| Column 2 Count |

我只需要这个。

|      OAS         |        OFS       |
---------------------------------------
| Column 1 Count   |  Column 2 Count  |

2 个答案:

答案 0 :(得分:5)

select sum(case when atlinestat = 1 then 1 else 0 end) 'OAS',
       sum(case when atlinestat = 2 then 1 else 0 end) 'OFS' 
from atmterminalfile (nolock) 
where Atstatu='2' 
and atlinestat in (1,2)

答案 1 :(得分:0)

虽然接受的答案可行,但这似乎是PIVOT查询的主要案例。

select * 
from atmterminalfile 
pivot (count(id) for atlinestat in ([1],[2])) p