自我加入并获得日期之间的唯一记录

时间:2017-11-13 10:01:59

标签: sql-server

我的表和数据如下所示,我试图根据句点进行过滤并获得结果

CREATE TABLE testData
(
    Id int,
    period date,
    value decimal(18,2)
)

INSERT INTO testData 
VALUES (1, '2001-08-01', 400), (2, '2001-09-01', 400), (2, '2001-09-01', 300)

我有一个小提琴,它会给出结果,但不是预期的,你可以在这里查看小提琴http://sqlfiddle.com/#!6/beb4c/5

这是我的SQL查询

SELECT
    a.id,
    [value] - (SELECT TOP 1 b.[value]
               FROM testData b
               WHERE b.period = a.period
               ORDER BY b.id DESC) x
FROM
    testData a

我期待的输出是

1  2001-08-01 400 
2  2001-09-01 100

1 个答案:

答案 0 :(得分:1)

试试这个

WITH CTE
AS
(
    SELECT
      SeqNo = ROW_NUMBER() OVER(PARTITION BY Id ORDER BY Period),
      *
    FROM TestData

)
SELECT
  A.Id,
  A.Period,
  Value = ISNULL(A.Value,0) - ISNULL(Q.Value,0)
  FROM CTE A
    LEFT JOIN(
      SELECT
        B.Id,
        B.period,
        Value = SUM(B.Value)
        FROM CTE B
          WHERE B.SeqNo <> 1
          GROUP BY B.Period,B.Id
     )Q
     ON A.Id = Q.Id
     WHERE A.SeqNo = 1

Fiddle Link Here