计数后将行转换为列

时间:2013-07-26 07:15:33

标签: sql sql-server sql-server-2008

我有以下表格:

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语句,但无法获得所需的输出。请帮忙。提前谢谢。

3 个答案:

答案 0 :(得分:7)

尝试使用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

答案 1 :(得分:5)

SELECT Type1, 
       SUM(CASE WHEN Type2='T1' THEN 1 ELSE 0 END) AS T1,
       SUM(CASE WHEN Type2='T2' THEN 1 ELSE 0 END) AS T2,
       SUM(CASE WHEN Type2='T3' THEN 1 ELSE 0 END) AS T3
FROM your_table
GROUP BY Type1

答案 2 :(得分:3)

这将有效

SELECT 
(SELECT count(*) FROM table1 WHERE type2 = 'T1' AND type1 = mTable1.type1) AS T1,
(SELECT count(*) FROM table1 WHERE type2 = 'T2' AND type1 = mTable1.type1) AS T2,
(SELECT count(*) FROM table1 WHERE type2 = 'T3' AND type1 = mTable1.type1) AS T3
FROM table1 mTable1 GROUP BY type1