我想我需要一个PIVOT,但我还没找到一个仅使用1列的例子 当前数据
CustID Value
1 A
1 B
1 C
2 A
3 B
4 A
4 C
我需要
StudentNumber A B C
1 Yes Yes Yes
2 Yes No No
3 No Yes No
4 Yes No Yes
我很欣赏它可能是一个非常简单的查询,但我真的很挣扎!
答案 0 :(得分:0)
试试这个。
SELECT custid,
Max(CASE
WHEN value = 'a' THEN 'YES' else 'NO'
END) A,
Max(CASE
WHEN value = 'b' THEN 'YES' else 'NO'
END) B,
Max(CASE
WHEN value = 'c' THEN 'YES' Else 'NO'
END) C
FROM <tablename>
GROUP BY CustID
答案 1 :(得分:0)
您可以在列列表中使用case语句检查null以获取所需的值。
select P.CustID,
case when P.A is null then 'No' else 'Yes' end as A,
case when P.B is null then 'No' else 'Yes' end as B,
case when P.C is null then 'No' else 'Yes' end as C
from YourTable as T
pivot (min(T.Value) for T.Value in (A,B,C)) as P
或者您可以在No
值的列列表中使用派生表和isnull。
select P.CustID,
isnull(P.A, 'No') as A,
isnull(P.B, 'No') as B,
isnull(P.C, 'No') as C
from (
select CustID,
Value,
'Yes' as S
from YourTable
) as T
pivot (min(T.S) for T.Value in (A,B,C)) as P