views:

40

answers:

3

Hi, i have a table like this:

Table(MissioneID, Type)

Type can be 1,2 or 3

i have to count missions by type value:

ex. if table's content is:

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

The result of query is

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

How can i do?

thanks

A: 
select type,count(*)
from table
group by MissioneID
Axarydax
I want a result with this columns:MissioneID,CountType1,CountType2,CountType3Not this Type,Count
Luca Romagnoli
oh sorry, my mistake for not reading your problem properly.
Axarydax
+4  A: 
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
Damien_The_Unbeliever
+1, correct answer. But you might want to encapsulate `type` in square brackets: `[type]` since it's a reserved word.
Codesleuth
True, although it doesn't cause any problems in context, for 2000 or 2008. (Only error in above concerns having a table called Table)
Damien_The_Unbeliever
+2  A: 

Looks like you're trying to do a pivot query here:

SELECT MissioneID, [1], [2], [3]
FROM Table
PIVOT
(
    COUNT(Type)
    FOR Type IN ([1], [2], [3])
) AS pvt
Aaronaught
Nice answer - I keep forgetting any facilities available > 2000, since that's where I'm still unhappily languishing.
Damien_The_Unbeliever
@Damien: Always good to remember your legacy workarounds, you never know when you'll need to use one. I would have posted the `CASE` version as an alternate (since the question author didn't specify the SQL Server version) but you got to it first. :)
Aaronaught