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 |
|
mavershang
Posting Yak Master
111 Posts |
Posted - 2009-03-19 : 13:36:45
|
| Hi all. Here is my question:the table is like:pos1 pos2 score9 20 1.29 25 210 18 1.310 20 1.3211 23 1.2220 41 3.120 102 1.4...Now I want to group those rows share the same positions. For example, group 9:20(row 1), 10:20(row 4) and 20:41(row x) together because they contain the same position "20", and get the max(score) in that group.Anyone could help me figure it out? |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-03-19 : 13:42:18
|
| [code]SELECT posval,MAX(score)FROM(SELECT posval,postype,scoreFROM table mUNPIVOT (posval FOR postype IN ([pos1],[pos2]))u)tGROUP BY posval[/code] |
 |
|
|
mavershang
Posting Yak Master
111 Posts |
Posted - 2009-03-19 : 13:46:17
|
Thanks. So helpful and fast response.quote: Originally posted by visakh16
SELECT posval,MAX(score)FROM(SELECT posval,postype,scoreFROM table mUNPIVOT (posval FOR postype IN ([pos1],[pos2]))u)tGROUP BY posval
|
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-03-19 : 13:47:21
|
welcome |
 |
|
|
mavershang
Posting Yak Master
111 Posts |
Posted - 2009-03-19 : 14:16:28
|
| I do not know much about pivot. Here is a little bit more further.how should I do if I want to show the pairing position associated with the shared element in the result likeif "20" is the sharing element, then show:20 41 3.1 instead of just20 3.1Thanks a lot |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-03-19 : 14:54:47
|
| [code]SELECT posval,COALESCE(NULLIF(pos1,posval),pos2),scoreFROM(SELECT posval,postype,score,DENSE_RANK() OVER (PARTITION BY posval ORDER BY score DESC) AS Seq,MAX(CASE WHEN postype='pos1' THEN posval ELSE NULL END) OVER (PARTITION BY score) AS pos1,MAX(CASE WHEN postype='pos2' THEN posval ELSE NULL END) OVER (PARTITION BY score) AS pos2FROM table mUNPIVOT (posval FOR postype IN ([pos1],[pos2]))u)tWHERE posval=20AND Seq=1[/code] |
 |
|
|
mavershang
Posting Yak Master
111 Posts |
Posted - 2009-03-19 : 17:55:03
|
Thank you so much.quote: Originally posted by visakh16
SELECT posval,COALESCE(NULLIF(pos1,posval),pos2),scoreFROM(SELECT posval,postype,score,DENSE_RANK() OVER (PARTITION BY posval ORDER BY score DESC) AS Seq,MAX(CASE WHEN postype='pos1' THEN posval ELSE NULL END) OVER (PARTITION BY score) AS pos1,MAX(CASE WHEN postype='pos2' THEN posval ELSE NULL END) OVER (PARTITION BY score) AS pos2FROM table mUNPIVOT (posval FOR postype IN ([pos1],[pos2]))u)tWHERE posval=20AND Seq=1
|
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-03-20 : 09:32:43
|
welcome |
 |
|
|
|
|
|
|
|