sql-如何计算表1中的订阅数并连接表2中的数据

yqyhoc1h  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(285)

我有两张table:
表1(订阅)

ID - NAME - COURSEID - STATUS
1  - JOHN -    1     - 0
2  - MIKE -    1     - 0
3  - JANE -    2     - 0
4  - PAUL -    1     - 1

表2(课程描述)

COURSEID - COURSE - NAME   - UNIT
1        - EXCEL  - BASIC  - XYZ Street
2        - WORD   - MASTER - ABC Street
3        - PPOINT - BASIC  - MNO Street

我需要这个:
结果表:

COURSEID - COURSE - NAME   - UNIT       - TOTAL SUBSCRIPTIONS WITH STATUS = 0
1        - EXCEL  - BASIC  - XYZ Street  -   2
2        - WORD   - MASTER - ABC Street  -   1
3        - PPOINT - BASIC  - MNO Street  -   0

我尝试左连接:

SELECT TABLE2.COURSEID, TABLE2.COURSE, TABLE2.NAME, TABLE2.UNITY COUNT(*) TOTAL FROM TABLE1 LEFT JOIN TABLE2 ON TABLE1.ID = TABLE2.ID GROUP BY TABLE1.ID

但我只订了课程。
怎么了?

kadbb459

kadbb4591#

此查询将执行您想要的操作。它使用条件聚合(conditional aggregation,即 SUMCASE 语句)以确定状态为0的订阅数。

SELECT c.COURSEID, c.COURSE, c.NAME, c.UNIT, SUM(CASE WHEN s.STATUS = 0 THEN 1 ELSE 0 END) AS Subs_with_0_status
FROM table2 c
LEFT JOIN table1 s ON s.COURSEID = c.COURSEID
GROUP BY c.COURSEID

输出:

COURSEID    COURSE  NAME    UNIT        Subs_with_0_status
1           EXCEL   BASIC   XYZ Street  2
2           WORD    MASTER  ABC Street  1
3           PPOINT  BASIC   MNO Street  0

sqlfiddle演示

相关问题