选择中的计数条件

时间:2010-03-26 13:32:03

标签: sql-server count

我有一张这样的桌子:

Table(MissioneID, Type)

类型可以是1,2或3

我必须按类型值计算任务:

离。如果表的内容是:

MissioneID Type
1,1
1,2
1,1
2,3
1,2

查询结果是

MissioneID,Count1,Count2,Count3
1, 2,2,0
2,0,0,1

我该怎么办?

感谢

3 个答案:

答案 0 :(得分:4)

select
    MissioneID,
    SUM(CASE WHEN [type]=1 THEN 1 ELSE 0 END) as Count1,
    SUM(CASE WHEN [type]=2 THEN 1 ELSE 0 END) as Count2,
    SUM(CASE WHEN [type]=3 THEN 1 ELSE 0 END) as Count3
from
    [Table]
group by
    MissioneID

答案 1 :(得分:2)

看起来你在这里尝试进行数据透视查询:

SELECT MissioneID, [1], [2], [3]
FROM Table
PIVOT
(
    COUNT(Type)
    FOR Type IN ([1], [2], [3])
) AS pvt

答案 2 :(得分:0)

select type,count(*)
from table
group by MissioneID