SQL多行到单行多列

时间:2015-10-30 18:28:06

标签: sql join

我包含一个SQLFiddle作为我目前所处位置的示例。在示例图像中,您可以看到,根据用户的状态以及他们拥有的状态数量,只需将每个用户最多分为两行。

enter image description here

http://sqlfiddle.com/#!3/9aa649/2

我希望它出来的方式如下图所示。每个用户有一行,有两个总计列,一个用于Fail Total,另一个用于Pass Total。我已经能够接近,但由于BOB只有Fails而不是Passes,因此查询会将BOB排除在结果之外。我想用他的6次失败和0次传球来显示BOB

    select a.PersonID,a.Name,a.Totals as FailTotal,b.Totals as PassTotals from (
 select PersonID,Name,Status, COUNT(*) as Totals from UserReport
 where Status = 'Fail'
group by PersonID,Name,Status) a
join 
(
 select PersonID,Name,Status, COUNT(*) as Totals from UserReport
 where Status = 'Pass'
group by PersonID,Name,Status) b
on a.PersonID=b.PersonID

下图是我想要的样子。这是另一个SQL Fiddle,它显示了上面的查询 http://sqlfiddle.com/#!3/9aa649/13

enter image description here

3 个答案:

答案 0 :(得分:2)

如果status列的值的数量固定,则使用条件聚合。

Fiddle

select PersonID,Name, 
sum(case when "status" = 'Fail' then 1 else 0 end) as failedtotal,
sum(case when "status" = 'Pass' then 1 else 0 end) as passedtotals 
from UserReport
group by PersonID,Name

答案 1 :(得分:1)

使用条件聚合:

select PersonID, Name,
       sum(case when Status = 'Fail' then 1 else 0 end) as FailedTotal,
       sum(case when Status = 'Pass' then 1 else 0 end) as PassedTotal
from UserReport
group by PersonID, Name;

答案 2 :(得分:1)

使用条件聚合:

select PersonID, 
       Name,
       sum(case when Status = 'Fail' then 1 end) as Failed,
       sum(case when Status = 'Passed' then 1 end) as Passed
from UserReport
group by PersonID, Name