Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert rows to columns after counting [duplicate]

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.

like image 523
harshit Avatar asked Jul 26 '13 07:07

harshit


1 Answers

Try to use PIVOT -

Query 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

Query 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

Output:

Type1 T1          T2          T3
----- ----------- ----------- -----------
A     3           2           1
B     0           1           3
like image 86
Devart Avatar answered Oct 29 '22 22:10

Devart