i have a table where there's a user_id and a ticket_type. i want to create a sql statement that will return me the the count of each ticket_type that each user_id generate.
i have come up with this but this involves some hard-coding of ticket_type which i'm not fond of.
select b.user_id, b.TypeA, B.TypeB, (b.TypeA + b.TypeB) As "Total Tickets" from
(select user_id,
sum(case when ticket_type = '1' then 1 else 0 end) as "TypeA",
sum(case when ticket_type = '2' then 1 else 0 end) as "TypeB"
from
database
group by user_id
) as b;
is there a better way to do this? it would be really awesome if someone can provide the answer in linq query expression as well.
EDIT Sample Output
User_ID Type_A Type_B Total user1 3 5 8 user2 1 2 3 user3 6 8 14
Sample Database Table
DECLARE @Users As TABLE
(
SN int,
User_ID char(5),
Ticket_Type int
)
INSERT INTO @Users VALUES
(1, 'user1', 1),
(2, 'user1', 1),
(3, 'user2', 2),
(4, 'user3', 1),
(5, 'user1', 2),
(6, 'user1', 2),
(7, 'user2', 2),
(8, 'user2', 2)