Could you please help me out in building a Query. I Have a table as below
Id Info_Id Type
1 2 2
2 6 2
3 5 3
4 8 3
5 2 3
6 2 2
7 5 2
8 8 2
9 5 2
10 8 2
11 8 2
12 5 3
13 6 3
14 8 3
a query need to be framed so as to group by “Info_Id”.
I need output as below for eg:
Info_Id CountOfRec Type2 Type3
2 3 2 1
5 4 2 2
6 2 1 1
8 5 3 2
I Tried as below but I m not able to get the efficient output
select Info_Id, count(Id)as CountOfRec,
(select count(Id)from tbl_TypeInfo where Info_Id = 5 AND Type = 2) as Type2,
(select count(Id)from tbl_ TypeInfo where Info_Id = 5 AND Type = 3) as Type3
from tbl_TypeInfo
where Info_Id = 5
group by Info_Id
output was this ,
Info_Id CountOfRec Type2 Type3
5 4 2 2
(I have to loop for each “Info_id” to get desired OP, there is thousand of records and its time consuming)
I wanted to get the highlighted output from the table. The query I have framed is not efficient and there would be good solution for this can you help me out.
You can use the
CASEexpression to only count the rows for a specific type:Add a
WHERE Info_Id = 5to retrieve results for a specific ID only.Update: as per comments, if you do not store a table of ID’s, You need to change your IN
(..)list to a virtual “table”: