组通过返回第一列值两次

时间:2016-03-07 10:11:21

标签: sql

我的数据看起来像:

ACC311  Female  3
ACC311  Female  1
ACC311  Female  4
ACC311  Male    4
ACC501  Male    4
ACC501  Male    4
ACC501  Male    4
ACC501  Male    4
.
.
.

现在我正在使用以下查询来获得结果

Select distinct coursecode, gender, Count(CQ) as CQ from Table1
group by Coursecode, gender
order by Coursecode

返回结果如下,显然不正确 根据要求的输出方式(见下文)

CourseCode Gender   CQ

ACC311     Male     45

ACC311     Female   22

ACC501     Female   228

ACC501     Male     485

我需要遵循的地方:

CourseCode  Total   Male    Female  CQ

ACC311      67      45      22      11

ACC501      713     485     228     111

1 个答案:

答案 0 :(得分:2)

您的查询会返回“两次”行,因为您按Coursecode, gender分组。 DISTINCT也无济于事。

获得所需结果的最简单方法是使用条件聚合:

SELECT Coursecode,
       Count(CQ) AS CQ,
       COUNT(gender) AS Total,
       COUNT(CASE WHEN gender = 'Male' THEN 1 END) AS Male,
       COUNT(CASE WHEN gender = 'Female' THEN 1 END) AS Female
FROM Table1
GROUP BY Coursecode