简体   繁体   中英

Mysql Inner Join based on condition

I have two tables that I'm attempting to retrieve specific information from (duh I know). The first table seasons is semi-static data storage and the second table users_cards is used to store user choices.

The result I am hoping to achieve would go through each season, assign a "card_total" = 10 for seasons 1-3 and 11 for each season moving forward. The result would look something similar to:

SEASON_ID   |   TOTAL   |
------------ ------------
1           |   123
2           |   234
3           |   345
4           |   456

The abbreviated & pertinent columns / sample data is as follows:

# `seasons`:

ID  |   ACTIVE  |   COMPLETE    |
---- ----------- ---------------
1   |   0       |   1
2   |   0       |   1
3   |   0       |   1
4   |   1       |   0
5   |   0       |   0

# `users_cards`
# DESC: this table can store up to 10 choices per user for seasons 1-3 
#       and up to 11 choices for every season thereafter.

USER_ID     |   SEASON_ID   |
------------ ---------------
1           |   1
1           |   1
2           |   1
2           |   1
1           |   2
1           |   2
1           |   2

I've played around with a few variations of this query but nothing seems to be doing the trick. This query returns the total count for each season but it's not based off of the "card_total" I mentioned above.

SELECT
    c.season_id AS season_id,
    c.card_total AS card_total,
    c.total AS total
FROM seasons s
INNER JOIN (
    SELECT
        uc.season_id,
        COUNT(DISTINCT(user_id)) AS total,
        CASE WHEN 
                uc.season_id = 1
                OR uc.season_id = 2
                OR uc.season_id = 3
            THEN 10
            ELSE 11
        END AS card_total
    FROM users_cards uc
    GROUP BY uc.season_id
) AS c ON c.season_id = s.id
WHERE s.is_active = 1 
    OR s.is_complete = 1

SUM()放在您的CASE...END周围。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM