以前的值和当前值

时间:2017-10-19 17:22:31

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

我想调整以下数据,以便我可以根据列rn中的值创建前一列和当前列。如果只有1个记录,则当前值和先前值将是相同的值。 (我正在使用ssms 2008)

CREATE TABLE #TEST1
(ACCT_ID INT, RN INT, LoadDate Date)

INSERT INtO #TEST1 VALUES (1, 1, '2016-12-21')
INSERT INtO #TEST1 VALUES (2, 1, NULL)
INSERT INtO #TEST1 VALUES (3, 1, '2017-10-06')
INSERT INtO #TEST1 VALUES (3, 2, NULL)
INSERT INtO #TEST1 VALUES (4, 1, '2016-12-21')

SELECT * FROM #TEST1
ACCT_ID RN  LoadDate
1   1   2016-12-21
2   1   NULL
3   1   2017-10-06
3   2   NULL
4   1   2016-12-21

根据上面的数据,我做了一个数据透视表

SELECT ACCT_ID, [1] as Prev, [2] as Curr FROM 
(
    SELECT * fROM #TEST1 S
    pivot(  MAX(LoadDate) for RN IN ([1],[2]) ) U 
)X

例如,acct_id 1和4如何与当前值具有相同的当前值。

3 个答案:

答案 0 :(得分:1)

我想你需要这样的东西。如果Curr为空,则会显示Prev值。

 select acct_id, curr, case when prev = ' ' then null else coalesce(prev, curr) end
 from
 (
    SELECT acct_id,
      max(CASE WHEN RN = 1 THEN loaddate END) as Curr,
      max(CASE WHEN RN = 2 THEN coalesce(loaddate, ' ') END) as Prev
    FROM #test1 t
    GROUP BY acct_id
 ) t

demo

答案 1 :(得分:0)

我会使用条件聚合:

select acct_id,
       max(case when rn = 1 then loaddate end) as load_date,
       max(case when rn = 2 then loaddate end) as load_date_prev
from #test1 t
group by acct_id;

答案 2 :(得分:0)

我不确定在这种情况下枢轴是否有效,如果您特别需要使用数据透视表答案我会道歉。

这里我通过子查询获取MAX(RN),然后为前一个和当前的LoadDate执行select语句。当前日期是MAX(RN)提供的日期。上一个日期是MAX(RN)的日期 - 如果MAX(RN)大于1则为1,否则它是RN等于1的前一个日期。

SELECT dT.ACCT_ID
      ,(SELECT T1.LoadDate FROM #TEST1 T1 WHERE T1.ACCT_ID = dT.ACCT_ID AND T1.RN = CASE WHEN dT.MaxRN = 1 THEN 1 ELSE dT.MaxRN - 1 END) [Prev]
      ,(SELECT T1.LoadDate FROM #TEST1 T1 WHERE T1.ACCT_ID = dT.ACCT_ID AND T1.RN = dT.MaxRN) [Curr]
  FROM (
         SELECT ACCT_ID
               ,MAX(RN) [MaxRN]
           FROM #TEST1
          GROUP BY ACCT_ID
 ) AS dT