在其他栏目中分组并计算外观

时间:2015-06-24 15:01:21

标签: sql-server sql-server-2008-r2

我的表格如下:

----------------------------------------------
|id    | action   |  building   | date       |
----------------------------------------------
|1     | IN       | 1000        | 01-01-2015 |
|2     | OUT      | 1000        | 01-01-2015 |
|3     | OUT      | 1000        | 05-01-2015 |
|4     | IN       | 2000        | 01-01-2015 |
----------------------------------------------

我想通过构建和计算存在多少IN和OUT操作来对结果进行分组。数据和ID在结果中并不重要。结果应该是:

-------------------------
| Building   | IN | OUT |
-------------------------
| 1000       | 1  | 2   |
| 2000       | 1  | 0   |
-------------------------

操作列只能包含IN和OUT。

我最好的尝试是:

select distinct (action), building, count(*)
from table
group by action, building

输出:

-------------------------------------
| action     | Building  | count(*) |
-------------------------------------
| IN         | 1000      | 1        |
| OUT        | 1000      | 2        |
| IN         | 2000      | 1        |
-------------------------------------

2 个答案:

答案 0 :(得分:2)

使用条件聚合:

select Building,
       sum(case when action = 'IN' then 1 else 0 end) as [IN],
       sum(case when action = 'OUT' then 1 else 0 end) as [OUT],
from TableName
group by Building

答案 1 :(得分:0)

您需要使用条件聚合

select building, 
       count(CASE WHEN action = 'IN' THEN 1 END) AS 'IN',
       count(CASE WHEN action = 'OUT' THEN 1 END) AS 'OUT'
from table
group by building