需要一点帮助。我已经开始了一个计算日期范围的选择,我想在其中计算每个代理的销售额。每个代理有不同的日期范围。但是销售额存储在另一个表中。
SELECT [bID]
,[pID]
,[aID] AS 'AgentID'
,[NAME]
,[aStart]
,'2021-03-01' AS 'Date_from'
,case when DATEADD(DAY, 364, aStart) <= '2022-02-28' then DATEADD(DAY, 364, aStart) else '2022-02-28' END) AS 'Date_end'
,'' AS 'Sales'
FROM [Agents] as a
WHERE STATUS = 'Active'
AND aStart >= '2020-03-02'
销售表如下所示:
SELECT [aID] AS 'AgentID'
,[SalesDate]
,[Product]
,[Kind]
,[SalesSum]
FROM [Sales] as s
我想要做的是计算每个代理的所有 SalesSum 的 SUM,但在特定的计算日期范围内。换句话说,我应该在某处为 s.SalesDate BETWEEN a.Date_from AND a.Date_end 添加 WHERE 子句。我知道答案很接近,但我的大脑不想关注它。
答案 0 :(得分:1)
您可以使用连接或子查询来执行此操作。
使用子查询:
ELECT [bID]
,[pID]
,[aID] AS 'AgentID'
,[NAME]
,[aStart]
,'2021-03-01' AS 'Date_from'
,case when DATEADD(DAY, 364, aStart) <= '2022-02-28' then DATEADD(DAY, 364, aStart) else '2022-02-28' END) AS 'Date_end'
,(select sum(salessum) from [Sales] s where a.aid=s.aid and s.[SalesDate] between '2020-02-01' and '2020-02-15') AS 'Sales'
FROM [Agents] as a
WHERE STATUS = 'Active'
AND aStart >= '2020-03-02'
(请根据需要更改子查询中的日期范围)
答案 1 :(得分:1)
您可以使用外部申请获得每个代理的总和,例如
select a.<columns>, s.Tot
from Agents a
outer apply (
select Sum(SalesSum) Tot
from Sales s
where s.aId=a.aId and s.salesdate between @StartDate and @EndDate
)s
where a.[status]='Active'
and a.aStart>='20200302'