如何在按日期进行分组时让MySQL返回空白日?

时间:2009-10-29 22:39:25

标签: php mysql

我有一个像这样的MySQL查询:

SELECT DAYNAME(CreatedAt) AS TheDay, SUM(Amount) AS TheSum
FROM OrderTransactions
GROUP BY TheDay

# Returns an array like:
# Array
# (
#     [0] => Array
#         (
#             [TheDay] => Thursday
#             [TheSum] => 0.02
#         )
# 
#     [1] => Array
#         (
#             [TheDay] => Wednesday
#             [TheSum] => 0.02
#         )
# 
# )

我还有一个条款可以选择上周的交易。如果某些日子没有交易,我怎样才能让每个空日返还$ 0.00金额?

1 个答案:

答案 0 :(得分:1)

一般来说,这里的技术是UNION与你选择的相反。

假设您有一个表格日期,其值为“星期一”,“星期二”......字段name中的“星期日”。

SELECT DAYNAME(CreatedAt) AS TheDay, SUM(Amount) AS TheSum
  FROM OrderTransactions
  GROUP BY TheDay
UNION
SELECT `name`, 0 FROM daynames
  WHERE daynames.name NOT IN (SELECT DISTINCT DAYNAME(CreatedAt) FROM OrderTransactions) 

如果没有日期功能,通常不需要日期名称查找表。在这种情况下,我不知道避免它的捷径。