开发者

Oracle subquery top 1 result

开发者 https://www.devze.com 2023-02-05 07:19 出处:网络
I want to get the top 1 row for each unique value of b with the minimum value of c for that particular value of b. Even though there can be more than 1 row with the same min value (just chose the firs

I want to get the top 1 row for each unique value of b with the minimum value of c for that particular value of b. Even though there can be more than 1 row with the same min value (just chose the first one)

myTable

  • a integer (unique)
  • b integer
  • c integer

I've tried this query

SELECT t1.* 
  FROM myTable t1, 
       (SELECT b, 
               MIN(c) as c 
          FROM myTable 
      GROUP BY b) t2 
 WHERE t1.b = t2.b 
   AND t1.c = t2.c

However, in this table it's possible for there to be more than 1 instance of the minimum value of c for a gi开发者_开发问答ven value of b. The above query generates duplicates under these conditions.

I've got a feeling that I need to use rownum somewhere, but I'm not quite sure where.


You can use ROW_NUMBER:

SELECT *
FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY b ORDER BY c) AS rn
    FROM myTable
) AS T1
WHERE rn = 1


To tie-break between the equal c's, you will need to subquery one level further to get the min-a for each group of equal c's per b. (A mouthful!)

select t0.*
FROM myTable t0
inner join (
    select t1.b, t1.c, MIN(a) as a
    from myTable t1
    inner join (
        select b, min(c) as c 
        from myTable 
        group by b
    ) t2 on t1.b = t2.b and t1.c = t2.c
    group by t1.b, t1.c
) t3 on t3.a = t0.a and t3.b = t0.b and t3.c = t0.c
0

精彩评论

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