从sql表中选择不同的当前列和上一列

时间:2016-07-26 14:48:29

标签: sql sql-server pivot

我有一张像这样的桌子

[processInfo operatingSystemVersion]

我想只选择更改,并希望显示之前的值以及当前更改后的内容。最终结果如下。我正在使用SQL Server 2014。

   Id  |Name    |Status |   Rate |  Method  |ModifiedTime             |ModifiedBy
-----------------------------------------------------------------------------
    1  |Recipe1 |  0    |    30  |   xyz    | 2016-07-26 14:55:57.977 |     A
-------------------------------------------------------------------------------
    2  |Recipe1 |  0    |    30  |   abc    | 2016-07-26 14:56:18.123 |     A
--------------------------------------------------------------------------------
    3  |Recipe1 |  1    |    30  |   xyz    | 2016-07-26 14:57:50.180 |     b

1 个答案:

答案 0 :(得分:1)

没有动态SQL,这是我能做的最好的事情。 我假设您按floor(8.0/0.4) != 8.0//0.4对更改进行分组。如果Name可以更改,则应删除分区,并将其添加到项子查询和Name。你可以尝试here

case

<强>输出

select item, 
       case item
         when 'Status' then cast(prevStatus as varchar)
         when 'Rate' then cast(prevRate as varchar)
         when 'Method' then prevMethod
         end as Before, 
       case item
         when 'Status' then cast(Status as varchar)
         when 'Rate' then cast(Rate as varchar)
         when 'Method' then Method
         end as After,
         ModifiedTime,
         ModifiedBy
  from (
    select Status,
           lag(Status) over (partition by Name order by id) prevStatus,
           Rate,
           lag(Rate) over (partition by Name order by id) prevRate,
           Method,
           lag(Method) over (partition by Name order by id) prevMethod,
           ModifiedBy,
           ModifiedTime
      from t ) as t1 cross join  (select 'Status' as item union all 
                                  select 'Rate' as item union all 
                                  select 'Method' as item) items
where (item = 'Status' and Status <> prevStatus)
   or (item = 'Rate' and Rate <> prevRate)
   or (item = 'Method' and Method <> prevMethod)
order by ModifiedTime

在第二行,当您拥有item Before After ModifiedTime ModifiedBy ------ ------ ----- ----------------------- ---------- Method xyz abc 2016-07-26 14:56:18.123 A Status 0 1 2016-07-26 14:57:50.180 b Method abc xyz 2016-07-26 14:57:50.180 b 时,您会看到ModifiedBy为b。我认为这是一个错字。

相关问题