简体   繁体   中英

How can I select only the first row from each subset of partially distinct values?

I have sql database having four columns as given below:

  A   B    C   D
1038 496 4789 10 
1303 496 6678 10 
1852 496 1645  8 
 982 496 5203  8
 427 496 5574  8 
  81 496 6908  7 
1264 496 2740  5 
1491 496 6408  4     
1198 496 9766  3

As you can see first and second rows have B and D columns with same values.

I want to select only one row from these two rows having lesser C value.

same I want to do with 3rd 4th and 5th row. How to do it?

You can try using row_number()

select * from
(
select a,b,c,d, row_number() over(partition by b,d order by c) as rn
from tablename
)A where rn=1

If your MySQL version doesn't support Windowed Aggregates you can get the minimum C per B/D and then join back:

select *
from tab as t
join 
 (
   select b, d, min(c) as minc
   from tab
   group by b, d
 ) as dt
 on t.b = dt.b
and t.c = dt.minc
and t.d = dt.d

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM