Search code examples
mysqlsqlleft-joininner-join

SQL - How to count the number of subscriptions in table1 and join datas from table2


I Have 2 tables:

TABLE 1 (Subscriptions)

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

TABLE 2 (COURSE Description)

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

I need this:

RESULT TABLE:

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 

I TRY LEFT JOIN:

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 

But I got only the courses with subscription.

what is wrong?


Solution

  • This query will do what you want. It uses conditional aggregation (the SUM of a CASE statement) to determine the number of subscriptions with a status of 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
    

    Output:

    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 Demo