gpt4 book ai didi

mysql - 我如何使用 mysql 获得 0 表示没有记录?

转载 作者:行者123 更新时间:2023-11-29 03:07:26 26 4
gpt4 key购买 nike

我是 mySql 的新手。我必须根据工作日计算表格中的点击次数。

这里的周期取决于数据库。但是如果上周没有记录,它就不在列表中。但我需要它作为 0。那么我该怎么做呢?

SELECT CASE 
WHEN PERIOD >= NOW() - INTERVAL 4 WEEK
AND PERIOD < NOW() - INTERVAL 3 WEEK THEN '22-28 days ago'

WHEN PERIOD >= NOW() - INTERVAL 3 WEEK
AND PERIOD < NOW() - INTERVAL 2 WEEK THEN '15-21 days ago'

WHEN PERIOD >= NOW() - INTERVAL 2 WEEK
AND PERIOD < NOW() - INTERVAL 1 WEEK THEN '8-14 days ago'

WHEN PERIOD >= NOW() - INTERVAL 1 WEEK
THEN 'up to 7 days ago'
END WeekPeriod, IFNULL(count(CLICKS),0) TotalClicks

FROM TABLE

WHERE PERIOD >= NOW() - INTERVAL 4 WEEK

GROUP BY CASE
WHEN PERIOD >= NOW() - INTERVAL 4 WEEK
AND PERIOD < NOW() - INTERVAL 3 WEEK THEN '22-28 days ago'

WHEN PERIOD >= NOW() - INTERVAL 3 WEEK
AND PERIOD < NOW() - INTERVAL 2 WEEK THEN '15-21 days ago'

WHEN PERIOD >= NOW() - INTERVAL 2 WEEK
AND PERIOD < NOW() - INTERVAL 1 WEEK THEN '08-14 days ago'

WHEN PERIOD >= NOW() - INTERVAL 1 WEEK
THEN '01 to 7 days ago'

END
ORDER BY WeekPeriod";

答案应该是这样的

1-7 0 
8-15 14
16-21 34
21-28 45

最佳答案

SELECT uq.timespan, COALESCE(tsq.TotalClicks, 0) as Clicks FROM (
SELECT '22-28 days ago' as timespan
union SELECT '15-21 days ago'
union SELECT '8-14 days ago'
union SELECT 'up to 7 days ago'
)uq LEFT JOIN (
SELECT CASE
WHEN PERIOD >= NOW() - INTERVAL 4 WEEK
AND PERIOD < NOW() - INTERVAL 3 WEEK THEN '22-28 days ago'
WHEN PERIOD >= NOW() - INTERVAL 3 WEEK
AND PERIOD < NOW() - INTERVAL 2 WEEK THEN '15-21 days ago'
WHEN PERIOD >= NOW() - INTERVAL 2 WEEK
AND PERIOD < NOW() - INTERVAL 1 WEEK THEN '8-14 days ago'
WHEN PERIOD >= NOW() - INTERVAL 1 WEEK THEN 'up to 7 days ago'
END WeekPeriod,
count(CLICKS) TotalClicks
FROM TABLE
WHERE PERIOD >= NOW() - INTERVAL 4 WEEK
GROUP BY WeekPeriod
/*ORDER BY WeekPeriod -- unnecessary, GROUP BY implicits ORDER BY*/
)tsq ON uq.timespan = tsq.WeekPeriod

关于mysql - 我如何使用 mysql 获得 0 表示没有记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13232097/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com