首先请纠正我,如果我的标题不够具体/清楚。
我使用以下代码生成开始日期和结束日期:
DECLARE @start_date date, @end_date date;
SET @start_date = '2016-07-01';
with dates as
(
select
@start_date AS startDate,
DATEADD(DAY, 6, @start_date) AS endDate
union all
select
DATEADD(DAY, 7, startDate) AS startDate,
DATEADD(DAY, 7, endDate) AS endDate
from
dates
where
startDate < '2017-03-31'
)
select * from dates
以下是来自上述查询的部分输出:
+------------+------------+
| startDate | endDate |
+------------+------------+
| 2016-07-01 | 2016-07-07 |
| 2016-07-08 | 2016-07-14 |
| 2016-07-15 | 2016-07-21 |
| 2016-07-22 | 2016-07-28 |
| 2016-07-29 | 2016-08-04 |
+------------+------------+
现在我有另一个名为sales
的表,它有3列sales_id
,sales_date
和sales_amount
,如下所示:
+----------+------------+--------------+
| sales_ID | sales_date | sales_amount |
+----------+------------+--------------+
| 1 | 2016-07-04 | 10 |
| 2 | 2016-07-06 | 20 |
| 3 | 2016-07-13 | 30 |
| 4 | 2016-07-19 | 15 |
| 5 | 2016-07-21 | 20 |
| 6 | 2016-07-25 | 25 |
| 7 | 2016-07-26 | 40 |
| 8 | 2016-07-29 | 20 |
| 9 | 2016-08-01 | 30 |
| 10 | 2016-08-02 | 30 |
| 11 | 2016-08-03 | 40 |
+----------+------------+--------------+
如何创建查询以显示每周的总销售额(介于第一个表中的每个startDate
和endDate
之间)?我想我需要使用带有WHERE子句的递归查询来检查日期是否在startDate
和endDate
之间,但我找不到一个有效的例子。
以下是我的预期结果( startDate
和endDate
是第一张表中的记录):
+------------+------------+--------------+
| startDate | endDate | sales_amount |
+------------+------------+--------------+
| 2016-07-01 | 2016-07-07 | 30 |
| 2016-07-08 | 2016-07-14 | 30 |
| 2016-07-15 | 2016-07-21 | 35 |
| 2016-07-22 | 2016-07-28 | 65 |
| 2016-07-29 | 2016-08-04 | 120 |
+------------+------------+--------------+
谢谢!
答案 0 :(得分:1)
你的最终选择(在cte之后)应该是这样的
Select D.*
,Sales_Amount = sum(Sales)
From dates D
Join Sales S on (S.sales_date between D.startDate and D.endDate)
Group By D.startDate,D.endDate
Order By D.startDate
编辑:如果您想查看丢失的日期,可以使用左连接 销售