【发布时间】:2022-01-25 01:00:05
【问题描述】:
我有两张桌子。
具有 CustomerID、InternalID 和 AsOfDate 的表 A。
具有 InternalID、Spend、StoreNum 和 AsOfDate 的表 B。
我希望创建一个输出,以便我获得过去 12 个月每月最后一天的每个 CustomerID 的支出总和。一个月的最后一天不是 30 或 31,它是按工作日计算的,所以我想要一个查询,查找每个月内的 MAX 日期以确定最后一天。
带有数据和查询的示例表。
Declare @MAXDATE DATETIME
Select @MAXDATE = MAX (as_of_date) from table2
select
s.customerID,
sum(case when s.asofdate = CAST('11/29/21' AS DATETIME) then hn.spend end) as val_prevmonth,
sum(case when s.asofdate = @MAXDATE then hn.spend end) as val_curr
from table1 s
join table2 hn on hn.asofdate = s.asofdate
and hn.internalID = s.internalID
where
and (s.asofdate = CAST('11/30/21' AS DATETIME) or s.asofdate = @MAXDATE)
group by s.customerID
order by s.customerID;
表 A
| CustomerID | InternalID | AsOfDate |
|---|---|---|
| 610 | 016 | 11/30/2021 |
| 610 | 016 | 11/29/2021 |
| 610 | 016 | 11/28/2021 |
| 610 | 016 | 10/29/2021 |
| 610 | 016 | 10/15/2021 |
| 610 | 016 | 9/15/2021 |
| 610 | 016 | 9/14/2021 |
| 610 | 016 | 8/10/2021 |
| 725 | 527 | 11/30/2021 |
| 725 | 527 | 11/29/2021 |
| 725 | 527 | 11/28/2021 |
| 725 | 527 | 10/29/2021 |
| 725 | 527 | 10/15/2021 |
| 725 | 527 | 9/15/2021 |
| 725 | 527 | 9/14/2021 |
| 725 | 527 | 8/10/2021 |
表 B
| Spend | InternalID | StoreNum | AsOfDate |
|---|---|---|---|
| 5000 | 016 | 123 | 11/30/2021 |
| 4000 | 016 | 321 | 11/30/2021 |
| 3000 | 016 | 456 | 11/28/2021 |
| 4500 | 016 | 654 | 10/29/2021 |
| 5000 | 016 | 789 | 10/15/2021 |
| 4000 | 016 | 756 | 9/15/2021 |
| 9000 | 016 | 987 | 9/15/2021 |
| 1000 | 016 | 545 | 8/10/2021 |
| 6000 | 527 | 124 | 11/30/2021 |
| 4500 | 527 | 354 | 11/30/2021 |
| 9000 | 527 | 745 | 11/28/2021 |
| 8500 | 527 | 846 | 10/29/2021 |
| 7500 | 527 | 646 | 10/29/2021 |
| 6000 | 527 | 311 | 9/14/2021 |
| 3000 | 527 | 211 | 9/14/2021 |
| 2500 | 527 | 121 | 8/10/2021 |
表 C。注意 CustomerID 725 从 9 月开始丢失,因为他们在 9 月的最后一个工作日(即 15 日)没有进行任何交易。列名也不需要包含日期,为了清楚起见,我把它放在那里。
| CustomerID | 11/30/2021 TotalSpend | 10/29/2021 TotalSpend | 9/15/2021 TotalSpend | 8/10/2021 TotalSpend |
|---|---|---|---|---|
| 610 | 9000 | 4500 | 1300 | 1000 |
| 725 | 10500 | 16000 | 2500 |
【问题讨论】:
-
您想要每个月只有一天的数据?您希望列出所有客户,即使他们没有数据?将 TableC 结果加入到所有客户的表中。列名必须具有使其唯一性。
-
你是对的 - 它是 sql-server!感谢您指出这一点
-
好的,标签已更改。还有一个额外的答案。
标签: sql sql-server