bin
发布于

如何链接 3 个 SQL 表并在值为 NULL 时传递 0 值

创建一个查询,以获取选定时间段内的活跃用户总数,并针对特定用户帐户 ID 进行筛选,筛选团队。

当前的查询有效,但没有特定的用户账户 ID,因此这是针对总用户数和每周时间段:

  WITH RECURSIVE Dates AS (
    SELECT CURDATE() - INTERVAL 6 DAY AS date
    UNION ALL
    SELECT date + INTERVAL 1 DAY
    FROM Dates
    WHERE date < CURDATE()
) 
SELECT 
    CASE 
        WHEN "weekly" = "biannually" THEN DATE_SUB(date, INTERVAL (DAYOFWEEK(Dates.date) - 1) DAY) 
        WHEN "weekly" = "yearly" THEN DATE_SUB(date, INTERVAL (DAYOFMONTH(Dates.date) - 1) DAY) 
        WHEN "weekly" = "daily" THEN DATE_FORMAT(date, "%Y-%m-%d %H:00:00") 
    ELSE 
        date
    END AS id, 
COALESCE(COUNT(activity_user), 0) AS users
FROM Dates 
    LEFT JOIN activity ON date = activity_date
    LEFT JOIN users ON activity_user = users_id
GROUP BY id
ORDER BY id ASC;

结果如下:

  +------------+-------+
| id         | users |
+------------+-------+
| 2024-10-02 |     25|
| 2024-10-03 |     64|
| 2024-10-04 |     10|
| 2024-10-05 |     22|
| 2024-10-06 |     27|
| 2024-10-07 |     16|
| 2024-10-08 |      3|
+------------+-------+

问题是,如果我尝试执行以下操作:

LEFT JOIN users ON activity_user = users_id WHERE users_account = 10对于我的第二次左联接,为了筛选 ID 为 10 的账户,我得到一个空集,而不是向我显示日期,而是为每个日期显示 0 个用户。预期结果应为:

  +------------+-------+
| id         | users |
+------------+-------+
| 2024-10-02 |      0|
| 2024-10-03 |      0|
| 2024-10-04 |      0|
| 2024-10-05 |      0|
| 2024-10-06 |      0|
| 2024-10-07 |      0|
| 2024-10-08 |      0|
+------------+-------+

如果这样做:

LEFT JOIN users ON activity_user = users_id AND users_account = 10,它被完全忽略并且不起作用,我得到了我的原始结果:

  +------------+-------+
| id         | users |
+------------+-------+
| 2024-10-02 |     25|
| 2024-10-03 |     64|
| 2024-10-04 |     10|
| 2024-10-05 |     22|
| 2024-10-06 |     27|
| 2024-10-07 |     16|
| 2024-10-08 |      3|
+------------+-------+

尝试对这些表使用各种类型的 SQL JOIN,但似乎都不起作用。我只想按字段进行筛选,并在没有活动用户的日期上显示 0。它适用于用户总数,但不适用于我想筛选特定团队 () 时。

  user_accountuser_account
浏览 (41)
点赞
收藏
1条评论
Klustron小助手
Klustron小助手
能试试这个 WITH RECURSIVE Dates AS (SELECT CURDATE() - INTERVAL 6 DAY AS date UNION ALL SELECT date + INTERVAL 1 DAY FROM Dates WHERE date &lt; CURDATE()) SELECT CASE WHEN &#34;weekly&#34; = &#34;biannually&#34; THEN DATE_SUB(date, INTERVAL (DAYOFWEEK(Dates.date) - 1) DAY) WHEN &#34;weekly&#34; = &#34;yearly&#34; THEN DATE_SUB(date, INTERVAL (DAYOFMONTH(Dates.date) - 1) DAY) WHEN &#34;weekly&#34; = &#34;daily&#34; THEN DATE_FORMAT(date, &#34;%Y-%m-%d %H:00:00&#34;) ELSE date END AS id, if(users_account is null, &#34;0&#34;, COALESCE(COUNT(activity_user), 0) ) AS users FROM Dates LEFT JOIN activity ON date = activity_date left JOIN users ON activity_user = users_id where users_account = 10 GROUP BY id ORDER BY id ASC;
点赞
评论