我有下表:
Type1 Type2 A T1 A T2 A T1 A T1 A T2 A T3 B T3 B T2 B T3 B T3
我希望输出为:
Type1 T1 T2 T3 A 3 2 1 B 0 1 3
我尝试使用ROW_NUMBER()OVER(ORDER BY)和CASE语句,但无法获得所需的输出。请帮忙。提前致谢。
尝试使用PIVOT-
查询1:
DECLARE @temp TABLE (Type1 CHAR(1), Type2 CHAR(2)) INSERT INTO @temp (Type1, Type2) VALUES ('A', 'T1'),('A', 'T2'), ('A', 'T1'),('A', 'T1'), ('A', 'T2'),('A', 'T3'), ('B', 'T3'),('B', 'T2'), ('B', 'T3'),('B', 'T3') SELECT * FROM @temp PIVOT ( COUNT(Type2) FOR Type2 IN (T1, T2, T3) ) p
查询2:
SELECT Type1 , T1 = COUNT(CASE WHEN Type2 = 'T1' THEN 1 END) , T2 = COUNT(CASE WHEN Type2 = 'T2' THEN 1 END) , T3 = COUNT(CASE WHEN Type2 = 'T3' THEN 1 END) FROM @temp GROUP BY Type1
输出:
Type1 T1 T2 T3 ----- ----------- ----------- ----------- A 3 2 1 B 0 1 3