SQL Server Rowcount列值

时间:2017-02-02 11:41:09

标签: sql sql-server

我正在尝试编写一个可以从此表中获得所需输出的简单SQL代码 -

原始表:

id | type
123  0
123  1
123  1
345  0
345  0

我想要的是:

id | zeroCount | oneCount
123     1          2
345     2          0

我尝试group by id并输入,但是,它们都给出了同样的东西!

如何获得所需的输出?

2 个答案:

答案 0 :(得分:4)

这是一种简单的方法,假设值只有0和1:

select id, sum(1 - type) as zerocount, sum(type) as onecount
from t
group by id;

更典型的方法是使用case(甚至pivot):

select id, sum(case when type = 0 then 1 else 0 end) as zerocount,
       sum(case when type = 1 then 1 else 0 end) as onecount
from t
group by id;

答案 1 :(得分:0)

你可能会喜欢并使用枢轴功能。但这会奏效:

Select id, 
 sum(case when type = 0 then 1 else 0 end) as ZeroCount,
 Sum(case when type = 1 then 1 else 0 end) as OneCount
 from table
group by id
order by id