Sql server SQL Server:如何在WHERE子句中使用CTE中的变量值?
首先,如果我的标题不够明确,请纠正我 我已使用以下代码生成开始日期和结束日期:Sql server SQL Server:如何在WHERE子句中使用CTE中的变量值?,sql-server,common-table-expression,Sql Server,Common Table Expression,首先,如果我的标题不够明确,请纠正我 我已使用以下代码生成开始日期和结束日期: 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 sele
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
现在我有另一个名为sales
的表,它有3列sales\u id
、sales\u date
和sales\u 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
):
谢谢大家! 您的最终选择(在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
编辑:如果您想查看中缺少的日期,可以使用左连接
销售
将
sum(Sales)
更改为sum(Sales\u amount)
非常有效!谢谢大家!@韦斯利很乐意帮忙。谢谢你纠正我的疏忽。
+------------+------------+--------------+
| 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 |
+------------+------------+--------------+
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