在SQL中计算最近7天或更少天的平均费用

时间:2019-05-02 23:13:12

标签: sql-server variables dateadd

我有一个SQL Server 2012表,如下所示:

Date       Product   Cost   AvgCost
----------------------------------
4/7/2019    ProdA   3   NULL
4/9/2019    ProdA   2   NULL
4/10/2019   ProdA   4   NULL
4/24/2019   ProdA   4   NULL
4/30/2019   ProdA   1   NULL

我正在尝试根据以下条件计算AvgCost的值:

  1. 如果最近7天或更短时间内有行,则对那几天取“费用”的简单平均值
  2. 如果最近7天或更短时间内没有任何行,则只需为AvgCost输入1

代码:

SELECT [Date], Product, Cost, oa.AvgCost
FROM [Table1] A
OUTER APPLY
    (SELECT AVG(A1.Cost) as AvgCost
     FROM [Table1] A1
     WHERE A1.Product = A.Product
       AND A1.date BETWEEN DATEADD (Day, -6, DATEADD(DAY, -1, A.date)) 
                       AND DATEADD(DAY, -1, A.date)) oa 
WHERE 
    a.date BETWEEN '04/1/2019' AND '04/30/2019'

该代码似乎仅在恰好有7天之前存在行时才起作用

(例如:如果我有从2019年4月1日至2019年7月4日的行,则能够获得2019年4月8日的正确值)

预期结果:

 Date    Product Cost   AvgCost
 4/7/2019   ProdA   3   1   -- no rows exist for last 7 days or 
                            --    less then 1
 4/9/2019   ProdA   2   3   -- Only 1 rows exists for last 7 days or 
                            --     less then average for that day
 4/10/2019  ProdA   4   2.5 -- Average cost for 4/7 and 4/9
 4/24/2019  ProdA   4   1   -- no rows exist for last 7 days or 
                            --    less then 1
 4/30/2019  ProdA   1   4 --Only 1 rows exists for last 7 days or 
                          --       less then average for that day

实际结果

  Date  Product  Cost   AvgCost
  4/7/2019  ProdA   3   NULL
  4/9/2019  ProdA   2   NULL
  4/10/2019 ProdA   4   NULL
  4/24/2019 ProdA   4   NULL
  4/30/2019 ProdA   1   NULL

1 个答案:

答案 0 :(得分:0)

因此,我整理了一堆对我来说有意义的查询语句,并添加了实际代码以获取示例。我还添加了代码以获取1,其中平均值缺失或小于0。在那儿的某个地方,我做了一些事情,使其完全按照您指定的方式工作,但是我不知道对不起。

drop table if exists #table1
create table #table1 (d date, Product nvarchar(max), Cost float, AvgCost FLOAT)
insert into #table1 values ('20190407', 'ProdA', 3, null)
insert into #table1 values ('20190409', 'ProdA', 2, null)
insert into #table1 values ('20190410', 'ProdA', 4, null)
insert into #table1 values ('20190424', 'ProdA', 4, null)
insert into #table1 values ('20190430', 'ProdA', 1, null)


SELECT [d], Product, Cost, iif(isnull(oa.AvgCost, 0) < 1, 1, oa.AvgCost) as AvgCost
FROM [#table1] A
OUTER APPLY
    (
        SELECT AVG(A1.Cost) as AvgCost
        FROM [#table1] as A1
        WHERE A1.Product = A.Product
            AND A1.d BETWEEN DATEADD(Day, -7, A.d) 
                            AND DATEADD(DAY, -1, A.d)
    ) as oa 
WHERE a.d BETWEEN '20190104' AND '20190430'

结果:

d           Product Cost    AvgCost
2019-04-07  ProdA   3       1
2019-04-09  ProdA   2       3
2019-04-10  ProdA   4       2.5
2019-04-24  ProdA   4       1
2019-04-30  ProdA   1       4