简体   繁体   中英

Select Previous Record in SQL Server 2008

Here's the case: I have one table myTable which contains 3 columns:

  • ID int, identity
  • Group varchar(2), not null
  • value decimal(18,0), not null

Table looks like this:

ID  GROUP   VALUE   Prev_Value  Result
------------------------------------------
1   A       20      0           20
2   A       30      20          10
3   A       35      30          5
4   B       100     0           100
5   B       150     100         50
6   B       300     200         100
7   C       40      0           40
8   C       60      40          20
9   A       50      35          15
10  A       70      50          20

Prev_Value and Result columns should be custom columns. I need to make it on view. Anyone can help? please... Thank you so much.

The gist of what you need to do here is to join the table to itself, where part of the join condition is that the value column of the joined copy of the table is less than value column of the original. Then you can group by the columns from the original table and select the max value from the joined table to get your results:

SELECT t1.id, t1.[Group], t1.Value
     , coalesce(MAX(t2.Value),0) As Prev_Value
     , t1.Value - coalesce(MAX(t2.Value),0) As Result
FROM MyTable t1
LEFT JOIN MyTable t2 ON t2.[Group] = t1.[Group] and t2.Value < t1.Value
GROUP BY t1.id, t1.[Group], t1.Value

Once you can update to Sql Server 2012 you'll also be able to take advantage of the new LAG keyword .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM