MySQL - 计算一周中每一天但每个发件人的所有行
Posted
技术标签:
【中文标题】MySQL - 计算一周中每一天但每个发件人的所有行【英文标题】:MySQL - Count all rows for each day of week but for each sender 【发布时间】:2015-07-21 14:32:52 【问题描述】:我有这个查询,它输出每天的行数,如果没有行,它输出 0。
我现在有一个额外的字段要添加到名为“发件人”的查询中。我需要对每个发件人执行完全相同的查询。
如何执行查询,以便每个发件人在一周中的每一天获取值?
SELECT DAYNAME(DATE_SUB(CURDATE(), INTERVAL Days.n DAY)) AS `day`,
COUNT(r.List_Date) AS `total`
FROM (SELECT 1 as n UNION ALL SELECT 2 as n UNION ALL
SELECT 3 as n UNION ALL SELECT 4 as n UNION ALL
SELECT 5 as n UNION ALL SELECT 6 as n UNION ALL
SELECT 7 as n
) Days LEFT JOIN
returns r
ON r.List_Date >= DATE_SUB(CURDATE(), INTERVAL Days.n DAY)
GROUP BY Days.n
ORDER BY Days.n DESC
【问题讨论】:
group by sender, days.n
我试过了,但没用
【参考方案1】:
您需要cross join
来获取所有行(每个发件人和一周中的每一天)。然后使用left join
:
SELECT s.sender, DAYNAME(DATE_SUB(CURDATE(), INTERVAL Days.n DAY)) AS `day`,
COUNT(r.List_Date) AS `total`
FROM (SELECT 1 as n UNION ALL SELECT 2 as n UNION ALL
SELECT 3 as n UNION ALL SELECT 4 as n UNION ALL
SELECT 5 as n UNION ALL SELECT 6 as n UNION ALL
SELECT 7 as n
) Days CROSS JOIN
(SELECT DISTINCT sender FROM returns) s LEFT JOIN
returns r
ON r.List_Date >= DATE_SUB(CURDATE(), INTERVAL Days.n DAY) and
r.sender = s.sender
GROUP BY s.sender, Days.n
ORDER BY s.sender, Days.n DESC;
这使用returns
表来获取适当的发件人。如果您有另一个表,则可以使用它。
【讨论】:
感谢@Gordon Linoff,。完全符合我的要求以上是关于MySQL - 计算一周中每一天但每个发件人的所有行的主要内容,如果未能解决你的问题,请参考以下文章