gpt4 book ai didi

php - 如何在mysql中选择整个星期的星期一到星期日?

转载 作者:搜寻专家 更新时间:2023-10-31 21:48:18 25 4
gpt4 key购买 nike

我尝试为我的查询选择日期,但我也想获得例如星期日,甚至在我的 sql 日期中没有星期日。周日为零。

这里是mysql

SELECT
DATE(log_date) DATE,
COUNT(users) active_users,
DATE_FORMAT(log_date,'%a') DAYNAME
FROM tbl_accounts
WHERE
DATE(log_date) BETWEEN DATE(:now) - INTERVAL 1 WEEK AND DATE(:now)
GROUP BY DATE(log_date);

我会发生什么是选择星期一到星期日,即使没有星期日我仍然想选择星期一,如果为空它会显示零值?可能吗?

示例输出: enter image description here

我希望此输出成为星期一-星期日,然后如果没有星期日,星期日将显示为零。

最佳答案

你是这个意思吗?

SELECT  t.DATE, IFNULL(t.active_users, 0) AS active_users, week.d 
FROM (
SELECT DATE(log_date) DATE,
COUNT(users) active_users,
DATE_FORMAT(log_date,'%a') DAYNAME
FROM tbl_accounts
WHERE DATE(log_date) BETWEEN DATE(NOW()) - INTERVAL 1 WEEK AND DATE(NOW())
GROUP BY DATE(log_date)) AS t
RIGHT OUTER JOIN (
SELECT 'Sun' AS d
UNION SELECT 'Mon' AS d
UNION SELECT 'Tue' AS d
UNION SELECT 'Wed' AS d
UNION SELECT 'Thu' AS d
UNION SELECT 'Fri' AS d
UNION SELECT 'Sat' AS d
) AS week ON week.d = t.DAYNAME

MySQL 中的示例结果如下图所示:

Example in MySQL

关于php - 如何在mysql中选择整个星期的星期一到星期日?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50672661/

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