简体   繁体   中英

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..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM