来自行

时间:2016-02-27 18:08:41

标签: sql count group-by row

我有一张桌子

Sport    Name   gender
----------------------
tennis   John     M
football David    M
football Jane     F
football Brad     M

我希望的结果就像

Count Sport Gender
1      Tennis  M
0      tennis  F
2      football M
1      football F

到目前为止,我可以得到像

Count Sport Gender
4      Tennis  M
4      tennis  F
4      football M
4      football F

或者我只计算网球和男性等1个条件。

我已经阅读了聚合函数,但我仍然无法实现。我无法想出解决方案来单独计算。

1 个答案:

答案 0 :(得分:2)

以下是一种方式,CROSS JOIN + LEFT OUTER JOIN + COUNT

SELECT a.sport,
       b.gender,
       Count(c.sport) AS count
FROM   (SELECT DISTINCT sport
        FROM   yourtable) a
       CROSS JOIN (SELECT 'M' AS Gender
                   UNION ALL
                   SELECT 'F') b
       LEFT OUTER JOIN yourtable c
                    ON a.sport = c.sport
                       AND b.gender = c.gender
GROUP  BY a.sport,
          b.gender 

<强>演示:

表架构&amp;数据

CREATE TABLE yourtable
  (
     Sport  VARCHAR(50),
     NAME   VARCHAR(50),
     gender CHAR(1)
  );

INSERT INTO yourtable VALUES ('tennis','John','M' );
INSERT INTO yourtable VALUES ('football','David','M' );
INSERT INTO yourtable VALUES ('football','Jane','F' );
INSERT INTO yourtable VALUES ('football','Brad','M' ); 

<强>结果

╔══════════╦════════╦═══════╗
║  sport   ║ gender ║ count ║
╠══════════╬════════╬═══════╣
║ football ║ M      ║     2 ║
║ football ║ F      ║     1 ║
║ tennis   ║ M      ║     1 ║
║ tennis   ║ F      ║     0 ║
╚══════════╩════════╩═══════╝

这里的关键是,由于您希望能够获得0个计数,因此您需要CROSS JOIN才能获得所有可能的组合,即使表中没有符合该条件的行(例如,没有女网球运动员的行。)