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 |
kowalsky
Starting Member
29 Posts |
Posted - 2010-07-08 : 13:16:46
|
hi all,i have a simple problem:ID TBL COL VAL1 AAA COL1 1002 AAA COL2 XYZ3 AAA COL3 2004 AAA COL1 505 AAA COL2 XYZ6 AAA COL3 100 What would be the query that displays the following:ID TBL COL VAL1 VAL21 AAA COL1 100 502 AAA COL2 XYZ XYZ3 AAA COL3 200 100 I tried:select t1.id, t1.tbl, t1.col, t1.val as VAL1 , t2.val as VAL2from myTable t1, myTable t2where t1.TBL=t2.TBL andt1.COL=t2.COLbut I am getting nowhere.Thanks,kowalsky |
|
kowalsky
Starting Member
29 Posts |
Posted - 2010-07-08 : 13:25:50
|
hi all,false alarm!i guess I would have to add t1.id < t2.id and everything would be just fine,thanks,kowalskykowalsky |
 |
|
SD_Monkey
Starting Member
38 Posts |
|
sodeep
Master Smack Fu Yak Hacker
7174 Posts |
Posted - 2010-07-09 : 11:09:56
|
How can the Val2 Value come for 1,2,3 when there ID is 4,5,6? |
 |
|
ms65g
Constraint Violating Yak Guru
497 Posts |
Posted - 2010-07-10 : 02:25:34
|
[code]SELECT ID = ROW_NUMBER() OVER(ORDER BY COL ASC), TBL, COL, VAL1 = MAX(CASE WHEN rec_id = 1 THEN VAL END), VAL2 = MAX(CASE WHEN rec_id = 2 THEN VAL ELSE '' END)FROM ( SELECT *, ROW_NUMBER() OVER(PARTITION BY COL ORDER BY ID) AS Rec_id FROM MyTable) AS DGROUP BY COL, TBL ORDER BY ID ; [/code]______________________ |
 |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2010-07-11 : 21:54:58
|
[code]; with dataas( select col_no = row_number() over (partition by TBL, COL order by VAL), TBL, COL, VAL from yourtable)select TBL, COL, VAL1 = [1], VAL2 = [2]from data d pivot ( max(VAL) for col_no in ([1], [2]) ) p[/code] KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
|
|
|
|