如何查找上一行和当前行的差异

时间:2013-02-25 06:58:45

标签: sql sql-server sql-server-2005

此表每个id有2行,id

不超过2行
id  date       amt
-------------------    
001 01/01/2012 100
001 01/12/2011 200
002 01/01/2013 100
002 01/12/2012 200
003 12/08/2012 500
003 31/12/2011 200
...

我想为每个ID显示行的max(date),其中包含当前和上一行的差异

预期产出

id  date       amt
------------------    
001 01/01/2012 100
002 01/01/2013 100
003 12/08/2012 300
...

怎么做?

2 个答案:

答案 0 :(得分:2)

你可以试试这个:

DECLARE @tbl TABLE (id VARCHAR(10), date DATE, amt INT)
INSERT @tbl VALUES
('001', CONVERT(DATE, '01/01/2012', 103), 100),
('001', CONVERT(DATE, '01/12/2011', 103), 200),
('002', CONVERT(DATE, '01/01/2013', 103), 100),
('002', CONVERT(DATE, '01/12/2012', 103), 200),
('003', CONVERT(DATE, '12/08/2012', 103), 500),
('003', CONVERT(DATE, '31/12/2011', 103), 200),
-- Added to display the one id - one row situation
('004', CONVERT(DATE, '14/02/2011', 103), 999),
('000', CONVERT(DATE, '02/02/2012', 103), 100),
('100', CONVERT(DATE, '09/09/2011', 103), 999)

;WITH a AS
(
    SELECT  id
            , amt
            , date      
            , ROW_NUMBER() OVER (PARTITION BY id ORDER BY date ASC) num
            , COUNT(*) OVER (PARTITION BY id) cnt
    FROM    @tbl
)

SELECT  t1.id
        , t1.date
        , ABS(t1.amt - t2.amt)
FROM    a t1
JOIN    a t2 ON (t1.id = t2.id AND t1.num = t2.num + 1)
OR      (t1.id = t2.id AND t2.cnt = 1)

ids 1和2的第一行和第二行的差值是-100所以我添加了返回绝对值的ABS函数。

我还添加了示例数据,以显示每个id只有一条记录时如何处理情况。

答案 1 :(得分:1)

试试这个:

WITH CTE
AS
(
   SELECT *,
     ROW_NUMBER() OVER(PARTITION BY Id ORDER BY Date DESC) AS Rownum
   FROM Table1
), CTE2
AS
(
  SELECT 
    id, 
    date, 
    amt, ROW_NUMBER() OVER(ORDER BY Id) AS rank
  FROM CTE c1
  WHERE rownum = 1
)
SELECT 
  id, 
  date, 
  amt - ISNULL((SELECT c2.amt
                FROM CTE2 c2
                WHERE c1.rank - c2.rank = 1), 0)
FROM CTE2 c1;

SQL Fiddle Demo