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 |
|
ben_53
Yak Posting Veteran
67 Posts |
Posted - 2011-09-19 : 16:50:16
|
| I have a tableA: (ID int, batch int, new_batch int)ID and batch are populated already:ID Batch New_Batch1 01 NULL2 01 NULL3 02 NULL4 02 NULL5 02 NULL6 03 NULL7 04 NULL8 05 NULLNow I want to populate New_batch according to the following select statement.(select batch from tableA where id in (3,8))now for this select statement, we get batch = 02 and batch =5. now I want to assign new_batch such that the result of select statement should be ordered first (batch02 then batch05) and the remaining data should be ordered in increasing order of batch NOT in select statement. (batch 1,3,4) result should be: ID Batch New_Batch 1 01 03 2 01 03 3 02 01 4 02 01 5 02 01 6 03 04 7 04 05 8 05 02Thanks. PS: DENSE_RANK() can be used, and please dont hard-code !! |
|
|
Aleph_0
Yak Posting Veteran
79 Posts |
Posted - 2011-09-19 : 17:09:31
|
quote: Originally posted by ben_53 I have a tableA: (ID int, batch int, new_batch int)ID and batch are populated already:ID Batch New_Batch1 01 NULL2 01 NULL3 02 NULL4 02 NULL5 02 NULL6 03 NULL7 04 NULL8 05 NULLNow I want to populate New_batch according to the following select statement.(select batch from tableA where id in (3,8))now for this select statement, we get batch = 02 and batch =5. now I want to assign new_batch such that the result of select statement should be ordered first (batch02 then batch05) and the remaining data should be ordered in increasing order of batch NOT in select statement. (batch 1,3,4) result should be: ID Batch New_Batch 1 01 03 2 01 03 3 02 01 4 02 01 5 02 01 6 03 04 7 04 05 8 05 02Thanks. PS: DENSE_RANK() can be used, and please dont hard-code !!
I'm still fairly new, but here's my suggestion:SELECT a.[id], a.Batch, [New_Batch] = dense_rank() OVER (ORDER BY CASE WHEN a.Batch IN (SELECT b.Batch FROM #tableA b WHERE b.[id] IN (3, 8)) THEN a.batch ELSE a.Batch + (SELECT max(b.Batch) FROM #tableA b WHERE b.[id] IN (3, 8)) END)FROM #tableA a I'm sure there's a better way to do this - that CASE statement looks really ugly to me. |
 |
|
|
|
|
|
|
|