SQL Server:将多行值合并到一行中
我有一个场景,在基于状态和id的SQL Server数据库中,我必须对行进行分组并显示计数。我试过了,但是我得到了下面这样的单独行中的值SQL Server:将多行值合并到一行中,sql,sql-server,aggregate-functions,Sql,Sql Server,Aggregate Functions,我有一个场景,在基于状态和id的SQL Server数据库中,我必须对行进行分组并显示计数。我试过了,但是我得到了下面这样的单独行中的值 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
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
结果是
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
(状态仅供参考)
但我需要这样的结果:
bid accept rejected noResp
-----------------------------------
1 1 0 0
2 1 2 0
3 1 1 0
我从stackoverflow中获得了许多示例,我尝试了MAX()
,SUM()
,CASE
,但无法使其工作
请建议..,因为您正以状态为中心,因此我建议它不应出现在
GROUP BY
列表中。相反,在req\u id
上进行聚合,然后对当前的CASE
表达式使用MAX()
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
由于您以状态为中心,因此我建议它不应出现在
分组依据
列表中。相反,在req\u id
上进行聚合,然后对当前的CASE
表达式使用MAX()
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
对于bid=1,如何拒绝=0,这不是逻辑上的问题吗?这是一个基于状态的计数有多少人拒绝了从数据库条目中提取的bid=1,如何拒绝=0,这不是逻辑上的问题吗?这是一个基于状态的计数有多少人拒绝了从数据库条目中提取的bid