选择包含先前值的公式

时间:2014-10-20 16:18:12

标签: sql sql-server

DECLARE @sales TABLE
(
    code VARCHAR(10) NOT NULL,
    date1 DATE NOT NULL,
    sales NUMERIC(10, 2) NOT NULL,
    profits NUMERIC(10, 2) NOT NULL
);

INSERT INTO @sales(Code, Date1, sales, profits)
VALUES  ('q', '20140708', 0.51,21),
        ('q', '20140712', 0.3,33),
        ('q', '20140710', 0.5,12),
        ('q', '20140711', 0.6,43),
        ('q', '20140712', 0.2,66),
        ('q', '20140713', 0.7,21),
        ('q', '20140714', 0.24,76),
        ('q', '20140714', 0.24,12),
        ('x', '20140709', 0.25,0),
        ('x', '20140710', 0.16,0),
        ('x', '20140711', 0.66,31),
        ('x', '20140712', 0.23,12),
        ('x', '20140712', 0.35,11),
        ('x', '20140714', 0.57,1),
        ('c', '20140712', 0.97,2),
        ('c', '20140714', 0.71,3);



SELECT code,
       CONVERT(VARCHAR, date1, 104)                 AS SPH_DATE_FORMATO,
       Cast(Sum(sales)
              OVER (
                ORDER BY date1) AS NUMERIC (18, 2)) AS SPH_CLOSE
FROM   @sales
WHERE  date1 > Dateadd(month, -21, Getdate())
       AND code = 'q' 

此选项为我提供按日期排序的'g'代码的累计销售额,这很好。 但现在我需要一个额外的列来计算: (1 +前一天销售)*(1+今日销售)-1 也按日期排序'g'代码

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

你可以使用CTE这样做,只需像这样改变你的选择查询

;with Sales as ( SELECT code, convert(varchar, date1, 104) AS SPH_DATE_FORMATO, cast(SUM(sales) OVER (ORDER BY date1) as numeric (18,2)) AS SPH_CLOSE,ROW_NUMBER() OVER(ORDER BY Date1 ASC) as rowid FROM @sales where date1 >DATEADD(month, -21, GETDATE()) and code='q') select S1.code,S1.SPH_DATE_FORMATO,S1.SPH_CLOSE ,S2.SPH_close as Sales_Last_Day from Sales S1 left outer join Sales S2 on S1.rowid -1 = S2.rowid