开发者

sql server getting first value when grouping

开发者 https://www.devze.com 2023-02-22 04:22 出处:网络
I have a table with column a having not necessarily distinct values and column b having for each value of a a number of distinct values. I want to get a result having each value of a appearing only on

I have a table with column a having not necessarily distinct values and column b having for each value of a a number of distinct values. I want to get a result having each value of a appearing only once and getting the first found value of b for that value of a. How do I do this in sql server 2000?

example table:

a  b
1  aa
1  bb
2  zz
3  aa
3  zz
3  bb
4  bb
4  aa

Wanted result:

a  b
1  aa
2  zz
3  aa
4  bb

In addition, I must add that the values in column b are all text value开发者_运维知识库s. I updated the example to reflect this. Thanks


;with cte as
    (
  select *,
    row_number() over(partition by a order by a) as rn
  from yourtablename
    )    
    select  
a,b
from cte 
where rn = 1 


SQL does not know about ordering by table rows. You need to introduce order in the table structure (usually using an id column). That said, once you have an id column, it's rather easy:

SELECT a, b FROM test WHERE id in (SELECT MIN(id) FROM test GROUP BY a)

There might be a way to do this, using internal SQL Server functions. But this solution is portable and more easily understood by anyone who knows SQL.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号