8

I have following table:

Type1 Type2
A      T1
A      T2
A      T1
A      T1
A      T2
A      T3
B      T3
B      T2
B      T3
B      T3

I want output as:

Type1 T1 T2 T3
A     3  2  1
B     0  1  3

I tried using ROW_NUMBER() OVER (ORDER BY) and CASE Statements but couldn't get desired output. Please Help. Thanks in advance.

4

3 回答 3

7

尝试使用 PIVOT -

查询一:

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
于 2013-07-26T07:22:48.487 回答
6
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
于 2013-07-26T07:21:54.187 回答
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
于 2013-07-26T07:30:13.960 回答