数据透视中聚合的条件

时间:2016-10-19 10:22:40

标签: sql-server pivot aggregate-functions

表#Temp:

ID    Name        Hobbies
1     xxx          Reading
1     xxx          Sports
1     xxx          Dance
2     xyz          Dance
3     yyy          Swimming
3     yyy          Reading

现在,我希望结果集为:

ID   Name    Reading  Sports  Dance  Swimming  
1    xxx      T        T      T        F
2    xyz      F        F      T        F
3    yyy      T        F      F        T

我写了以下查询:

SELECT * FROM
(
    SELECT * FROM #Temp
)SRC
PIVOT
(
    COUNT([ID]) 
    FOR [Hobbies] in ([Reading],[Sports],[Dance],[Swimming])
) piv;

我得到了以下结果:

ID   Name    Reading  Sports  Dance  Swimming  
1    xxx      1        1      1        0
2    xyz      0        0      1        0
3    yyy      1        0      0        1

所以,我想在聚合中使用条件,例如if(count(id)= 1然后' T' else' F')。是否有可能在Pivots中如何实现它?

3 个答案:

答案 0 :(得分:2)

试试这个

SELECT ID,NAME,
       CASE WHEN Reading=1 THEN 'T' ELSE 'F' END AS Reading,
       CASE WHEN Sports=1 THEN 'T' ELSE 'F' END AS Sports,
       CASE WHEN Dance=1 THEN 'T' ELSE 'F' END AS Dance,
       CASE WHEN Swimming =1 THEN 'T' ELSE 'F' END AS Swimming ,
FROM(
        --your query here
)t 

答案 1 :(得分:2)

SELECT 
    Name,
    CASE Reading WHEN 1 THEN 'T' ELSE 'F' END AS Reading,
    CASE Sports WHEN 1 THEN 'T' ELSE 'F' END AS Sports,
    CASE Dance WHEN 1 THEN 'T' ELSE 'F' END AS Dance,
    CASE Swimming WHEN 1 THEN 'T' ELSE 'F' END AS Swimming
FROM
(
    SELECT * FROM @tblTest
)SRC
PIVOT
(
    COUNT([ID]) 
    FOR [Hobbies] in ([Reading],[Sports],[Dance],[Swimming])
) piv;

答案 2 :(得分:1)

SELECT case when Reading >0 then 'T' else 'F' end Reading ,
       case when Sports >0 then 'T' else 'F' end Sports ,
       case when Dance >0 then 'T' else 'F' end Dance 

FROM
(
    SELECT * FROM #Temp
)SRC
PIVOT
(
    COUNT([ID]) 
    FOR [Hobbies] in ([Reading],[Sports],[Dance],[Swimming])
) piv;