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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With