有日期间隔的建筑报告

时间:2019-02-13 11:02:16

标签: mysql sql

我需要在一定日期范围内与卖方的销售情况进行报告。 我的问题是该报告还应选择当天未进行任何销售的卖方。

供应商(表)

id | name
----------
 1 | John
 2 | Tom

销售(表)

id | vendor_id |    date        | status | price
------------------------------------------------
 1 |        1  |    2019-01-01  |    0   | 100
 2 |        1  |    2019-01-01  |    0   | 100 
 3 |        2  |    2019-01-01  |    0   | 100
 4 |        2  |    2019-01-02  |    0   | 100 

所需报告: 2019-01-01 2019-01-04

之间的总销售额
date        |vendor| total
--------------------------
2019-01-01  | John | 200
2019-01-01  | Tom  | 100
2019-01-02  | John | 0
2019-01-02  | Tom  | 100
2019-01-03  | John | 0
2019-01-03  | Tom  | 0
2019-01-04  | John | 0
2019-01-04  | Tom  | 0

要使用日期生成器here

生成天序列

当我交叉(左联接)时,用sales生成的日期得到以下信息:

SELECT date_generator.daily_date, vendors.name, sales.price
        FROM ( 
            SELECT DATE_ADD(@startDate, INTERVAL (@i:=@i + 1) - 1 DAY) AS daily_date   
            FROM information_schema.columns, (SELECT @i:=0) gen_sub   
            WHERE DATE_ADD(@startDate, INTERVAL @i DAY) BETWEEN @startDate AND @endDate 
        ) date_generator 
        LEFT JOIN sales ON DATE(sales.date) = DATE(date_generator.daily_date)
        LEFT JOIN vendors ON vendors.id = sales.vendor_id
ORDER BY date_generator.daily_date

date        |vendor| price
--------------------------
2019-01-01  | John | 100
2019-01-01  | John | 100
2019-01-01  | Tom  | 100
2019-01-02  | Tom  | 100
2019-01-03  | null | null
2019-01-04  | null | null

您能给我一些技巧来划分供应商和日期吗?

1 个答案:

答案 0 :(得分:1)

由于有些日子没有销售,因此您将获得NULL sales.vendor.id的值,因此JOINvendors的价值就没有了。为了确保在所有日期都能得到所有供应商,您需要从CROSS JOINdate_generator,然后从vendors到销售,进行LEFT JOIN。然后,您需要获取SUM中的sales.priceGROUP BY的日期和供应商,以获取所需的输出:

SELECT date_generator.daily_date, vendors.name, SUM(sales.price)
        FROM ( 
            SELECT DATE_ADD(@startDate, INTERVAL (@i:=@i + 1) - 1 DAY) AS daily_date   
            FROM information_schema.columns, (SELECT @i:=0) gen_sub   
            WHERE DATE_ADD(@startDate, INTERVAL @i DAY) BETWEEN @startDate AND @endDate 
        ) date_generator 
        CROSS JOIN vendors
        LEFT JOIN sales ON DATE(sales.date) = DATE(date_generator.daily_date) AND vendors.id = sales.vendor_id
GROUP BY date_generator.daily_date, vendors.name