2

这个表每个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
...

我想max(date)用当前行和上一行显示每个 id 的行 amt 差异

预期产出

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

这该怎么做?

4

2 回答 2

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)

id 1 和 2 的第一行和第二行之差为 -100,因此我添加了ABS返回绝对值的函数。

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

于 2013-02-25T07:28:52.403 回答
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 小提琴演示

于 2013-02-25T07:01:18.007 回答