如何识别和显示表的两行中的值之间的差异

时间:2014-11-10 09:43:10

标签: sql sql-server sql-server-2008

我遇到了这个问题。

EID(primary key)  CID    Col1    Col2    Col3 ... 200 columns like this...
   1                3      5000   'ABC'  1200                  
   2                4      5000   'DEF'  1000                 
   3                3      5500   'ABC'  1300                    
   4                3      5000   'XYZ'  1100                  
   5                4      8000   'DEF'  1000                    
   6                3      4000   'ABC'   600

如何显示具有相同CID的两个最新行(在这种情况下,它将是带有Eid 6和Eid 4的行)之间的值与列名称之间的差异。提前感谢。我正在使用MS-Sql Server 2008。

2 个答案:

答案 0 :(得分:0)

您可以使用lag() window function。例如:

select  *
from    (
        select  EID
        ,       CID
        ,       col1
        ,       lag (col1) over (partition by CID order by EID) as prev_col1
        ,       max(EID) over (partition by CID) as max_eid_per_cid
        from    YourTable
        ) as SubQueryAlias
 where  col1 <> prev_col1 -- Col1 must have changed
        and EID = max_eid_per_cid -- Only latest EID per CID
 order by
        CID

答案 1 :(得分:0)

试试这个..使用Window function你可以得到最后两个值。并且通过使用left join,您可以将当前行与上一行进行比较。

;WITH cte
     AS (SELECT Row_number()OVER ( partition BY cid ORDER BY eid DESC) rn,
                *
         FROM   #tt)
SELECT a.eid,a.cid,a.col1,a.col2,a.col3,
       ( a.col1 - b.col1 ) col1_diff,
       ( a.col3 - b.col3 ) col3_diff
FROM   cte a
       LEFT JOIN cte b
              ON a.rn = b.rn + 1
                 AND a.CID = b.CID
WHERE  a.rn IN ( 1, 2 )