Author |
Topic |
peace
Constraint Violating Yak Guru
420 Posts |
Posted - 2013-04-11 : 23:42:20
|
SELECT col1,col2,ROW_NUMBER() OVER(PARTITION BY col1 ORDER BY col1,col2 desc) RNfrom tableA order by col2it show as below:col1 col2 RNaaa 123 1bbb 123 2ccc 456 1the result show be:col1 col2 RNaaa 123 1bbb 123 1ccc 456 1 |
|
bandi
Master Smack Fu Yak Hacker
2242 Posts |
Posted - 2013-04-12 : 00:15:20
|
SELECT col1,col2,ROW_NUMBER() OVER(PARTITION BY col2 ORDER BY col1 ) RNfrom TableA order by col2EDIT: If there is duplicates in col1 within each col2 group, then you can use the followingSELECT col1,col2,ROW_NUMBER() OVER(PARTITION BY col2 ORDER BY col1 , col2 desc ) RNfrom TableA order by col2 |
|
|
peace
Constraint Violating Yak Guru
420 Posts |
Posted - 2013-04-12 : 00:22:06
|
it still give me the same result:col1 col2 RNaaa 123 1bbb 123 2ccc 456 1 |
|
|
peace
Constraint Violating Yak Guru
420 Posts |
Posted - 2013-04-12 : 00:25:58
|
SELECT col1,col2,ROW_NUMBER() OVER(PARTITION BY col2 ORDER BY col1 , col2 desc ) RNfrom TableA where col1 in (aaa,bbb)col1 col2 RNaaa 1aaa 123 1bbb 123 2bbb 456 1bbb 2Result should be as below:col1 col2 RNaaa 2aaa 123 1bbb 123 1bbb 456 1bbb 2 |
|
|
bandi
Master Smack Fu Yak Hacker
2242 Posts |
Posted - 2013-04-12 : 00:26:40
|
Post your atcual data....--Illustration with your sample data working fineDECLARE @tab TABLE(col1 char(3), col2 int)insert into @tabSELECT 'aaa', 123 union allSELECT 'bbb', 123 union allSELECT 'ccc', 456SELECT * FROM @tab SELECT col1,col2,ROW_NUMBER() OVER(PARTITION BY col2 ORDER BY col1 , col2 desc ) RNfrom @tab order by col2col1 col2---- -----------aaa 123bbb 123ccc 456col1 col2 RN---- ----------- --------------------aaa 123 1bbb 123 2ccc 456 1 |
|
|
peace
Constraint Violating Yak Guru
420 Posts |
Posted - 2013-04-12 : 00:30:26
|
as above |
|
|
bandi
Master Smack Fu Yak Hacker
2242 Posts |
Posted - 2013-04-12 : 00:34:01
|
Oh.. for this result, your code is working fine...Result should be as below:col1 col2 RNaaa 2aaa 123 1bbb 123 1bbb 456 1bbb 2Tell me the logic behind the result which you want............EDIT: refere this link for ROW_NUMBER() OVER( PARTITION BY ORDER BY )http://www.codeproject.com/Articles/308281/How-to-Use-ROW_NUMBER-to-Enumerate-and-Partition-R |
|
|
peace
Constraint Violating Yak Guru
420 Posts |
Posted - 2013-04-12 : 00:38:29
|
my result didnt turn out as below:col1 col2 RNaaa 2aaa 123 1bbb 123 1bbb 456 1bbb 2i would like to take only rn=1 |
|
|
russell
Pyro-ma-ni-yak
5072 Posts |
Posted - 2013-04-12 : 01:09:17
|
this? if not, as bandi said, post actual DDL and sample data.WITH cteAS ( SELECT col1,col2, ROW_NUMBER() OVER(PARTITION BY col1 ORDER BY col1,col2 desc) RN from tableA)SELECT col1, col2, RNFROM cteWHERE RN = 1order by col2 And, if you don't mind my saying so Peace, you've been around here long enough to know how to post a question that makes it possible to get good help AND how to format your code... |
|
|
|