将仅有2个不同列值的两行合并为一行

时间:2017-10-24 12:15:34

标签: sql

我有一张表,记录工作场所事故。每个IncidentNo都应该是唯一的。以这样的方式向我提供数据的组织:每个IncidentNo都有两个条目,每个条目对应一个性别。表的格式是这样的。 (表格大约有110列,我只是展示了与问题相关的列。所有列都是varchar

+------------+--------+----------------+
| IncidentNo | Gender | PersonnelCount |
+------------+--------+----------------+
|     123456 | M      |            150 |
|     123456 | F      |            100 |
|     789012 | M      |             31 |
|     789012 | F      |             42 |
+------------+--------+----------------+

我需要的是以这样的方式组合这些列:如果它在同一个表上或插入到新表中则无关紧要是这样的:

+------------+----------------------+--------------------+
| IncidentNo | FemalePersonnelCount | MalePersonnelCount |
+------------+----------------------+--------------------+
|     123456 |                  100 |                150 |
|     789012 |                   42 |                 31 |
+------------+----------------------+--------------------+

我想用Left Outer Join将数据插入到新表中,但无法弄清楚如何。

2 个答案:

答案 0 :(得分:3)

只需使用条件聚合:

select incidentno, sum(PersonnelCount) as total_PersonnelCount,
       sum(case when gender = 'M' then PersonnelCount else 0 end) as nummales,
       sum(case when gender = 'F' then PersonnelCount else 0 end) as numfemales,
from t
group by incidentno;

我也会计算总数,只是为了确保总数与'M''F'之和相匹配。

答案 1 :(得分:1)

以其最新的形式,您可以自我加入:

select x.IncidentNo, 
       sum(a.personelcount) as Female, 
       sum(b.personelcount) as Male
from Accidents x
left join Accidents a
  on a.incidentno = x.incidentno
  and a.Gender = 'F'
left join Accidents b
  on b.incidentno = x.incidentno
  and b.Gender = 'M'
group by x.IncidentNo -- I left this out originally because I'm an idiot