Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
harjeet_21
Starting Member
2 Posts |
Posted - 2010-10-13 : 13:23:29
|
Hi,I need some help to write a query. Consider a table "CardHistory" Create Table CardHistory(SerialNo INT IDENTITY(1,1),ModificationDatetime DATETIME,OldCardNo INT,NewCardNo INT)Some times "OldCardNo" and "NewCardNo" can be same.I need to find out very first CardNo, most recent (last) CardNo and ModificationsCount.Example: CardNo 100 changed to 101CardNo 101 changed to 102CardNo 102 changed to 103CardNo 103 changed to 104then query should return 100, 104, 4Please help as soon as possible.Thanks in advance ... |
|
Sachin.Nand
2937 Posts |
Posted - 2010-10-13 : 13:48:18
|
Will the changes be in order?What if CardNo 100 changed to 105CardNo 105 changed to 102What should be the o/p ?PBUH |
 |
|
harjeet_21
Starting Member
2 Posts |
Posted - 2010-10-13 : 13:58:38
|
100, 102, 2Thanks,Harjeet Singh Bhatia |
 |
|
Sachin.Nand
2937 Posts |
Posted - 2010-10-13 : 14:12:43
|
[code]Create Table CardHistory(SerialNo INT IDENTITY(1,1),ModificationDatetime DATETIME,OldCardNo INT,NewCardNo INT)insert into CardHistoryselect GETDATE()-3,100,107 union allselect GETDATE()-2,107,102 union allselect GETDATE()-1,102,105select * from CardHistoryselect min(case when min=1 then OldCardNo end)old,max(case when max=1 then NewCardNo end)new from ( select *,row_number()over(order by modificationdatetime )min, row_number()over(order by modificationdatetime desc)max from CardHistory c)t where min=1 or max=1[/code]PBUH |
 |
|
|
|
|
|
|