【问题标题】:Multiple Between Dates Aggregation多个日期之间的聚合
【发布时间】:2021-11-30 12:15:22
【问题描述】:

我有这个数据集,其结构或多或少类似于以下内容:

Product Sales Value Sales Qty Sales Date Period 1 start Period 1 end Period 2 start Period 2 end
XXX 6 2 2021-05-20 2021-05-15 2021-05-21 2021-05-22 2021-06-01
YYY 10 3 2021-05-21 2021-05-15 2021-05-21 2021-05-22 2021-06-01
XXX 3 1 2021-05-23 2021-05-15 2021-05-21 2021-05-22 2021-06-01
XXX 6 2 2021-05-24 2021-05-15 2021-05-21 2021-05-22 2021-06-01

我想对“销售价值”和“销售数量”列求和,然后再创建 4 个列,分别称为“期间 1 销售额”、“期间 1 数量”、“期间 2 销售额”和“期间 2 数量”。

例如,使用上面的数据,我将获得四个新列,而行将按产品分组:

Product Period 1 start Period 1 end Period 2 start Period 2 end Period 1 Sales Value Period 1 Sales Qty Period 2 Sales Value Period 2 Sales Qty
XXX 2021-05-15 2021-05-21 2021-05-22 2021-06-01 6 2 9 3
YYY 2021-05-15 2021-05-21 2021-05-22 2021-06-01 0 0 10 3

我正在使用 SQL Server,现在我几乎陷入困境。

到目前为止,我设法交叉连接我的日历表和销售表,以获得第一个矩阵中描述的表。

有人可以帮忙吗?

非常感谢!

【问题讨论】:

  • @DaleK,很抱歉这个不精确的问题。我在问题中添加了我想要的输出。至于我尝试了什么,我基本上尝试了多次内部加入我的日历表和我的销售表以获得不同的期间开始/结束销售日期。但它并没有真正起作用。
  • 我们需要看看你的尝试。

标签: sql sql-server tsql between


【解决方案1】:

以下提供了您想要的结果,但您的 YYY 值除外,在您的示例数据中,值位于周期 1 而不是周期 2。

select Product,
    Period1start, Period1end, Period1start, Period2end,
    Sum(P1sales) Period1Sales, Sum(P1Qty) Period1Qty, 
    Sum(P2sales) Period2Sales, Sum(P2Qty) Period2Qty
from t
cross apply(values(case when SalesDate between Period1start and Period1end then SalesValue else 0 end)  )p1s(P1sales)
cross apply(values(case when SalesDate between Period1start and Period1end then SalesQty else 0 end)    )p1q(P1Qty)
cross apply(values(case when SalesDate between Period2start and Period2end then SalesValue else 0 end)  )p2s(P2sales)
cross apply(values(case when SalesDate between Period2start and Period2end then SalesQty else 0 end)    )p2q(P2Qty)
group by product, Period1start, Period1end, Period1start, Period2end

example DB<>Fiddle

【讨论】:

    猜你喜欢
    • 2014-12-18
    • 2022-01-13
    • 2018-06-11
    • 2021-11-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    相关资源
    最近更新 更多