当您需要所有日期的查询结果时,需要有 Dates 表(帮助不大)。我给你答案并且不使用日期表。
SQLFIDDLEExample 1 with Date Table
询问:
SELECT
DATE_FORMAT(td.TimeKey, '%Y-%m-%d') as Date,
SUM(Amount/(SELECT COUNT(tdc.TimeKey)
FROM Table1 t1c, TDate tdc
WHERE t1c.StartDate<= tdc.TimeKey
AND t1c.Enddate >= tdc.TimeKey
AND t1c.ID = t1.ID )) as Total_Amount
FROM Table1 t1, TDate td
WHERE t1.StartDate<= td.TimeKey
AND t1.Enddate >= td.TimeKey
GROUP BY Date
ORDER BY Date
结果:
| DATE | TOTAL_AMOUNT |
-----------------------------
| 2012-01-01 | 2 |
| 2012-01-02 | 2 |
| 2012-01-03 | 2 |
| 2012-01-04 | 12 |
| 2012-01-05 | 12 |
不使用日期表的结果相同:
仅使用 SQL 的 SQLFiddle 示例(没有日期表)