我希望b的每个唯一值得到前1行,b的特定值的最小值为c。即使可以有超过1行具有相同的最小值(只选择第一行)
我试过这个查询
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
但是,在此表中,对于给定的b值,可能存在多于1个最小值c的实例。上述查询会在这些条件下生成重复项。
我有一种感觉,我需要在某处使用rownum,但我不太确定在哪里。
答案 0 :(得分:9)
您可以使用ROW_NUMBER:
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY b ORDER BY c) AS rn
FROM myTable
) AS T1
WHERE rn = 1
答案 1 :(得分:0)
要在相等的c之间打破平局,您需要进一步子查询一个级别,以获得每个等于每个b的c组的min-a。 (一口!)
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