如何在MySQL中的SELECT语句中正确添加其他列?

时间:2018-02-27 18:59:25

标签: mysql sql mariadb

我想提取两个不同月份(三月和四月)发生的“演出”中“教练”的出席人数(即COUNT())。我设法创建了一个只在一个月内收集该数字的查询。此外,通过稍微修改查询,可以轻松找到第二个月的数字。但是如何将它们合并到一个包含两列的表中?

因此,考虑到下面的两个查询和结果表,如何将查询2的结果“追加”到查询1的结果中?换句话说,如何组合各自的SELECT语句?

我需要链接到SQL小提琴。

提前谢谢。

SQL Fiddle

查询1

SELECT C.*, COUNT(CIS.idCoach) AS MarchNumOfShows
FROM Coach AS C
  LEFT JOIN 
    (
        CoachInShow AS CIS
     LEFT JOIN
        TVShow AS S
     ON S.idShow = CIS.idShow
    )
  ON C.idCoach = CIS.idCoach AND S.airDate LIKE '_____04___'
  GROUP BY C.idCoach

Results

| idCoach |      name | surname | MarchNumOfShows |
|---------|-----------|---------|-----------------|
|       1 |   Stephen | Hawking |               5 |
|       2 |  Nicholas |    Cage |               7 |
|       3 | Sigourney |  Weaver |               6 |

查询2 (最小差异,查询四月而不是三月):

SELECT COUNT(CIS.idCoach) AS AprilNumOfShows
FROM Coach AS C
  LEFT JOIN 
    (
        CoachInShow AS CIS
     LEFT JOIN
        TVShow AS S
     ON S.idShow = CIS.idShow
    )
  ON C.idCoach = CIS.idCoach AND S.airDate LIKE '_____05___'
  GROUP BY C.idCoach

Results

| AprilNumOfShows |
|-----------------|
|               8 |
|               7 |
|              10 |

通缉

| idCoach |      name | surname | MarchNumOfShows | AprilNumOfShows |
|---------|-----------|---------|-----------------|-----------------|
|       1 |   Stephen | Hawking |               5 |               8 |
|       2 |  Nicholas |    Cage |               7 |               7 |
|       3 | Sigourney |  Weaver |               6 |              10 |

2 个答案:

答案 0 :(得分:1)

你非常接近,你错过的最后一步是simply combine MarchNumOfShows and AprilNumOfShows with left join

如下面的代码(或查看Sql Fiddle ):

SELECT C.idCoach, C.name, C.surname, COUNT(distinct CIS4.idShow) AS MarchNumOfShows
, COUNT(distinct CIS5.idShow) AS AprilNumOfShows
FROM Coach AS C
  LEFT JOIN 
    (
        CoachInShow AS CIS4
     LEFT JOIN
        TVShow AS S4
     ON S4.idShow = CIS4.idShow
    )
  ON C.idCoach = CIS4.idCoach AND S4.airDate LIKE '_____04___'
  LEFT JOIN 
    (
        CoachInShow AS CIS5
     LEFT JOIN
        TVShow AS S5
     ON S5.idShow = CIS5.idShow
    )
  ON C.idCoach = CIS5.idCoach AND S5.airDate LIKE '_____05___'
  GROUP BY C.idCoach;

以下是获得相同输出(或查看SQL Fiddle)的另一种方式:

SELECT C.idCoach, C.name, C.surname, 
  sum(case when DATE_FORMAT(airDate,'%M')='April' then 1 else null end ) AS AprilNumOfShows, 
  sum(case when DATE_FORMAT(airDate,'%M')='May' then 1 else null end ) AS MayNumOfShows
FROM Coach AS C
  LEFT JOIN 
    (
        CoachInShow AS CIS
     LEFT JOIN
        TVShow AS S
     ON S.idShow = CIS.idShow
    )
  ON C.idCoach = CIS.idCoach 
  GROUP BY C.idCoach;

答案 1 :(得分:0)

一种方法是使用案例:

select *,
  sum(case when airdate like "%03%" then 1 else 0 end) as March,
  sum(case when airdate like "%04%" then 1 else 0 end) as April
  ...