【问题标题】:SQL Rollup last 4 weeks total过去 4 周的 SQL 汇总总计
【发布时间】:2013-03-27 05:03:05
【问题描述】:

我有一个表,我想在查询中获取前四个星期的订单总数。但我想用 SELECT 将其返回(该行的前 4 周 Order1 列的总数 - 如果它们存在)

PurchasingID Order1              Date         FourWeekTotal
------------ ------------------- -------      ---------------
1            1.00                2013-04-21   14.00
2            2.00                2013-04-14   12.00
3            3.00                2013-04-07   9.00
4            4.00                2013-03-31   5.00
5            5.00                2013-03-24   0.00

【问题讨论】:

  • 从哪里获得 14.00 值
  • PurchasingID 2 + 3 + 4 + 5

标签: sql rollup


【解决方案1】:

我的理解是对于您表中的每条记录,您希望查看 Order1 本身的总和以及在主记录之前四个星期内具有 Date 值的每条记录。给你:

create table MysteryTable
(
    PurchasingId int not null primary key identity(1,1),
    Order1 money not null,
    [Date] date not null
)

insert MysteryTable( Order1, [Date] ) values ( 1.00, '2013-04-21' )
insert MysteryTable( Order1, [Date] ) values ( 2.00, '2013-04-14' )
insert MysteryTable( Order1, [Date] ) values ( 3.00, '2013-04-07' )
insert MysteryTable( Order1, [Date] ) values ( 4.00, '2013-03-31' )
insert MysteryTable( Order1, [Date] ) values ( 5.00, '2013-03-24' )

select
    t1.PurchasingId
    , t1.Order1
    , t1.Date
    , SUM( ISNULL( t2.Order1, 0 ) ) FourWeekTotal
from
    MysteryTable t1
    left outer join MysteryTable t2
     on DATEADD( ww, -4, t1.Date ) <= t2.Date and t1.Date > t2.Date
group by
    t1.PurchasingId
    , t1.Order1
    , t1.Date
order by
    t1.Date desc

解释:

自己加入表,t1 表示要返回的记录,t2 表示要聚合的记录。加入基于 t1 的日期减去四个星期小于或等于 t2 的日期和 t1 的日期大于 t2 的日期。然后按 t1 字段对记录进行分组,并对 t2.Order1 求和。左外连接是为了说明前面没有任何数据的一条记录。

【讨论】:

  • 谢谢,但我什至无法从您的查询中找到适用于这些结果的总和 - 它只返回我的 11 个采购行中的 7 个。我需要它们全部返回前 4 周的订单总数(不包括当前订单)。如果有帮助,我已经简化了上面的数据
  • 糟糕,我的 on 子句不正确。太困了 :P 现在更新。顺便说一句,根据您的样本数据,您的四个星期总数不包括当前记录的 Order1 值,对吗?
  • 程序员不睡觉!没错,当前的 Order1 不包括在内
  • 抱歉,刚刚注意到您更新了查询。我在等,但今晚我会再试一次。 ty
  • 很抱歉再次提出这个问题,但我有一个新要求,我真的很挣扎。我现在有一个“位置”列,所以我想让查询足够聪明,以便按位置对这 4 周的总和进行分组。现在,他们正在从两个地点累积价值(因为日期可能重叠)有什么想法/补充吗?非常感谢任何帮助
【解决方案2】:

试试这个...

Declare @LBDate date
SET @LBDate = DATEADD(d,-28,getdate())

现在编写你的选择查询...

Select * from Orders where Date between @LBDate and Getdate()

您也可以使用您需要的日期来代替当前日期..

【讨论】:

  • 返回第一行
猜你喜欢
  • 2017-07-17
  • 2016-01-01
  • 1970-01-01
  • 2023-04-05
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-02
相关资源
最近更新 更多