Malar
Malar

Reputation: 163

SQL Server : multiple rows values into a single row

I have a scenario where in a SQL Server database based on status and id I have to group the rows and display the count. I was trying but I am getting values in separate separate rows like below

select  
    req_id as bid, status,
    (case when status = 1 then 1 else 0 end) as accept,
    count(case when status = 2 then 1 else 0 end) as rejected,
    (case when status = 3 then 1 else 0 end) as noResp 
from 
    temp_allo
group by 
    req_id, status

Result is

bid status  accept  rejected    noResp
--------------------------------------
1     1       1        1        0
2     1       1        1        0
3     1       1        1        0
2     2       0        2        0
3     2       0        1        0

(status is only for reference)

but I need result like this:

bid     accept  rejected    noResp
-----------------------------------
1       1         0          0
2       1         2          0
3       1         1          0

I got many samples from stackoverflow I tried MAX(), SUM(), CASE but I couldn't make it work.

Please suggest..

Upvotes: 0

Views: 61

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521389

Because you are pivoting on the status, therefore I propose that it should not appear in the GROUP BY list. Instead, aggregate over the req_id and then use MAX() with your current CASE expressions.

select
    req_id as bid,
    max(case when status = 1 then 1 else 0 end) as accept,
    max(case when status = 2 then 1 else 0 end) as rejected,
    max(case when status = 3 then 1 else 0 end) as noResp
from temp_allo
group by req_id

Upvotes: 3

Related Questions