我尝试为我的查询选择日期,但我也希望在我的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);
我要发生什么是选择星期一到星期天,即使没有星期天,我仍然想要选择moday,如果空的话它会显示零值?有可能吗?
我希望这个输出成为星期一 - 星期日,如果没有星期日,那么星期日将显示零。
答案 0 :(得分:0)
你的意思是这样吗?
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中的示例结果如下图所示:
答案 1 :(得分:0)
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)and
DATENAME(dw , @date) <> 'Monday'
GROUP BY DATE(log_date);
只需将其添加到clouse中即可将其排除。 DATENAME(dw , @date) <> 'Monday'
这是内置的功能MSSQL。