MySQL - 计算每周的每一天的所有行,但是为每个发件人计算

时间:2015-07-21 14:32:53

标签: mysql sql count union-all

我有这个查询,它输出每天的行数,如果没有行,则输出0。

我现在有一个额外的字段要添加到名为“Sender”的查询中。我需要查询对每个发件人执行完全相同的操作。

如何执行查询,以便每个发件人获取值中的每周的每一天?

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

1 个答案:

答案 0 :(得分: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表来获取适当的发件人。如果你有另一张桌子,你可以改用它。