0

我需要收集某个类别项目的销售额总和,按选定日期范围(可能是从一周到 12 周)按天分组,并在没有发生交易的天返回 0 而不是 NULL。

我最初的想法是使用一个名为“日历”的预填充表(如下所示),它有大约 10 年的日期,我可以将其加入我的“产品”表,以获得没有销售发生的天数为 0 SUM。

结果太大而无法处理,因此我尝试首先将选定的日期范围复制到一个名为“datetable”的空表中,该表与“日历”具有相同的列名。所以我有3张桌子:

日历”表。它有 10 年的日期,并带有以下列名称:

IsoDate       DayNameOfWeek

2012-01-01       Sun
2012-01-02       Mon
2012-01-03       Tue
2012-01-04       Wed
2012-01-05       Thu
2012-01-06       Fri
2012-01-07       Sat
2012-01-08       Sun
2012-01-09       Mon
2012-01-10       Tue
etc for 10yrs

datetable ” 表(这是创建为空的,有两列从“日历”表中预填充,因此 LEFT JOIN 的日期范围数据更紧​​凑):

IsoDate        DayNameOfWeek

产品”表。这是我为每个 ProductCat 存储销售额的地方:

ExpDate     ProductCat  Amount

2012-01-03    28          232
2012-01-04    29          100
2012-01-04    29          1002
2012-01-06    12          12
2012-01-06    29          9
2012-01-07    10          100
2012-01-07    29          122
2012-01-07    29          17

我正在寻找基于单个“ProductCat”编号的输出,在本例中为 29:

IsoDate     DayNameOfWeek   AmountSummed

2012-01-01     Sun      0
2012-01-02     Mon      0
2012-01-03     Tue      0
2012-01-04     Wed      1102
2012-01-05     Thu      0
2012-01-06     Fri      9
2012-01-07     Sat      139
2012-01-08     Sun      0
2012-01-09     Mon      0
2012-01-10     Tue      0

我的代码如下。初始插入工作正常,但我不确定使第二部分与 JOIN 和 SUM 一起工作的语法:

INSERT INTO datetable (IsoDate, DayNameOfWeek)
SELECT IsoDate, DayNameOfWeek
FROM calendar
WHERE IsoDate 
BETWEEN '2012-07-01' AND '2012-07-10'

SELECT ExpDate, SUM(IFNULL(Amount, 0))
AS AmountSummed
FROM products
WHERE ProductCat = 29
AND ExpDate BETWEEN '2012-07-01' AND '2012-07-10'
LEFT JOIN products 
ON datetable.IsoDate=products.ExpDate
    GROUP BY datetable.IsoDate

编辑

这是现在有效的代码:

SELECT C.IsoDate,IFNULL(SUM(P.Amount),0) AS AmountSummed
FROM calendar C LEFT OUTER JOIN products P ON C.IsoDate=P.ExpDate
AND P.ProductCat = 29
WHERE C.IsoDate BETWEEN '2012-07-01' AND '2012-07-10'
GROUP BY C.IsoDate, C.DayNameOfWeek
ORDER BY C.IsoDate
4

1 回答 1

0

你几乎得到了你需要的东西。但是,您不需要datetable

您的查询应如下所示:

SELECT C.IsoDate, C.DayNameOfWeek, IFNULL(SUM(P.Amount),0) AS AmountSummed
FROM calendar C LEFT JOIN products P ON C.IsoDate=P.ExpDate
WHERE C.IsoDate BETWEEN '2012-07-01' AND '2012-07-10'
  AND P.ProductCat = 29
GROUP BY C.IsoDate, C.DayNameOfWeek
ORDER BY C.IsoDate

如果你真的想使用你的datetable,只需将它替换为calendar并删除C.IsoDate BETWEEN '2012-07-01' AND '2012-07-10'(假设datetable你开始之前是空的),因为datetime已经有了你正在寻找的所有日期。

于 2012-07-10T00:58:50.047 回答