Author |
Topic |
bugulgad
Starting Member
21 Posts |
Posted - 2008-02-14 : 20:49:53
|
use northwindgocreate table table1(A char(10),B char(10),C char(10))insert table1values('Niners', 'Gold', 'WATCH')insert table1values('Niners', 'Silver', 'watch')insert table1values('Niners', 'Bronze', 'w@tch')insert table1values('Patriots', 'Silver', 'watch')insert table1values('Patriots', 'Bronze', 'w@tch')insert table1values('Giants', 'Bronze', 'w@tch')-- truncate table table1--drop table table1select *from table1-- I would like a query that picks up just 1 row per unique value in col A--The row it should pick should be based on a ranked criteria of possible values in col B-- Assuming the ranking is Gold, Silver then Bronze, result set should be 3 rows looking like this--Niners, Gold, WATCH--Patriots, Silver, watch--Giants, Bronze, w@tch |
|
pdreyer
Starting Member
6 Posts |
Posted - 2008-02-15 : 02:26:06
|
[code]select * into #table2 from (select 1,'Gold' union all select 2,'Silver' union all select 3,'Bronze' )r(D,B)select a.* from table1 ajoin #table2 b on a.B=b.Bjoin (select a.A,min(b.D)D from table1 ajoin #table2 b on a.B=b.Bgroup by a.A)con a.A=c.Aand b.D=c.Dorder by b.Ddrop table #table2[/code] |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2008-02-15 : 02:42:44
|
[code]-- Prepare sample dataDECLARE @Sample TABLE (ColA VARCHAR(10), ColB VARCHAR(10), ColC VARCHAR(10))INSERT @SampleSELECT 'Niners', 'Gold', 'WATCH' UNION ALLSELECT 'Niners', 'Silver', 'watch' UNION ALLSELECT 'Niners', 'Bronze', 'w@tch' UNION ALLSELECT 'Patriots', 'Silver', 'watch' UNION ALLSELECT 'Patriots', 'Bronze', 'w@tch' UNION ALLSELECT 'Giants', 'Bronze', 'w@tch'-- Show the expected outputSELECT s.ColA, s.ColB, s.ColCFROM @Sample AS sINNER JOIN ( SELECT ColA, MIN( CASE ColB WHEN 'Gold' THEN 1 WHEN 'Silver' THEN 2 WHEN 'Bronze' THEN 3 ELSE 9 END) AS Medal FROM @Sample GROUP BY ColA ) AS x ON x.ColA = s.ColAWHERE CASE x.Medal WHEN 1 THEN 'Gold' WHEN 2 THEN 'Silver' WHEN 3 THEN 'Bronze' ELSE NULL END = s.ColBORDER BY x.Medal[/code] E 12°55'05.25"N 56°04'39.16" |
 |
|
|
|
|