Author |
Topic |
kamii47
Constraint Violating Yak Guru
353 Posts |
Posted - 2007-03-08 : 02:43:19
|
Suppose I have a table with three fieldjcode jnumber jstatus1 123 11 323 11 434 51 213 52 324 1 2 343 53 344 53 343 54 23 2 4 232 3 4 001 3I want's each code with maximum jnumberjcode jnumber jstatus1 434 52 343 53 344 54 232 3Please help me in the select sql |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-03-08 : 02:48:46
|
[code]select t.*from table1 t inner join ( select jcode, max_jnumber = max(jnumber) from table1 group by jcode ) mon t.jcode = m.jcodeand t.jnumber = m.max_jnumber[/code] KH |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-03-08 : 03:54:30
|
Oops!'23' > '1001'TRUE...It seems JNumber is stored as VARCHAR!Peter LarssonHelsingborg, Sweden |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-03-08 : 03:59:13
|
[code]-- prepare sample datadeclare @t table (jcode int, jnumber varchar(4), jstatus int)insert @tselect 1, '123', 1 union allselect 1, '323', 1 union allselect 1, '434', 5 union allselect 1, '213', 5 union allselect 2, '324', 1 union allselect 2, '343', 5 union allselect 3, '344', 5 union allselect 3, '343', 5 union allselect 4, '23', 2 union allselect 4, '232', 3 union all select 4, '001', 3-- Show the outputSELECT t1.jCode, t1.jNumber, t1.jStatusFROM @t AS t1WHERE t1.jNumber = (SELECT TOP 1 t2.jNumber FROM @t AS t2 WHERE t1.jCode = t2.jCode ORDER BY LEN(t2.jNumber) DESC, t2.jNumber DESC)[/code]Peter LarssonHelsingborg, Sweden |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-03-08 : 04:56:21
|
And with SQL Server 2005 (if you consider the move)-- prepare sample datadeclare @t table (jcode int, jnumber varchar(4), jstatus int)insert @tselect 1, '123', 1 union allselect 1, '323', 1 union allselect 1, '434', 5 union allselect 1, '213', 5 union allselect 2, '324', 1 union allselect 2, '343', 5 union allselect 3, '344', 5 union allselect 3, '343', 5 union allselect 4, '23', 2 union allselect 4, '232', 3 union all select 4, '001', 3-- Show the outputSELECT jCode, jNumber, jStatusFROM ( SELECT jCode, jNumber, jStatus, ROW_NUMBER() OVER (PARTITION BY jCode ORDER BY LEN(jNumber) DESC, jNumber DESC) AS RecID FROM @t ) AS xWHERE RecID = 1 Peter LarssonHelsingborg, Sweden |
 |
|
|
|
|