SQL。有没有找到第二个最低值的有效方法?
我有下表:SQL。有没有找到第二个最低值的有效方法?,sql,db2,subquery,Sql,Db2,Subquery,我有下表: ItemID Price 1 10 2 20 3 12 4 10 5 11 我需要找到第二低的价格。到目前为止,我有一个有效的查询,但我不确定它是否是最有效的查询: select min(price) from table where itemid not in (select itemid from table where price= (select min(price) from table)); 如果我必须找到
ItemID Price
1 10
2 20
3 12
4 10
5 11
我需要找到第二低的价格。到目前为止,我有一个有效的查询,但我不确定它是否是最有效的查询:
select min(price)
from table
where itemid not in
(select itemid
from table
where price=
(select min(price)
from table));
如果我必须找到第三或第四个最低价格怎么办?我甚至没有提到其他属性和条件。。。有没有更有效的方法
注意,最小值不是唯一的值。例如,第1项和第4项都是最小值。简单的订购是不行的。不确定这是否是最快的,但这样可以更容易地选择第二个、第三个等等。。。只需更改最高值
select price from table where price in (
select
distinct price
from
(select t.price,rownumber() over () as rownum from table t) as x
where x.rownum = 2 --or 3, 4, 5, etc
)
已更新
SELECT MIN(price)
FROM table
WHERE price NOT IN (SELECT DISTINCT TOP 1 price FROM table ORDER BY price)
我想最简单的方法是使用标准sql中的偏移量获取过滤器,如果列中没有重复值,则不需要使用distinct
从表中选择不同的(价格)
按价格订购
偏移量1行仅取第一行代码>
无需编写复杂的子查询
在amazon红移中,使用limit fetch代替ex
Select distinct(price) from table
order by price
limit 1
offset 1;
您可以使用以下选项之一:-
select min(your_field) from your_table where your_field NOT IN (select distinct TOP 1 your_field from your_table ORDER BY your_field DESC)
或
我认为您可以使用限制和顺序找到第二个最小值
select max(price) as minimum from (select distinct(price) from tableName order by price asc limit 2 ) --or 3, 4, 5, etc
如果你想找到第三个或第四个最小值等等。。。您可以通过更改“限制”中的最小数量来找到答案。您可以使用此语句查找
这是一个很好的答案:
SELECT MIN( price )
FROM table
WHERE price > ( SELECT MIN( price )
FROM table )
确保执行此操作时,子查询中只有一行!(末端括号中的部分)
例如,如果要使用分组依据
,则必须使用以下方法进一步定义:
SELECT MIN( price )
FROM table te1
WHERE price > ( SELECT MIN( price )
FROM table te2 WHERE te1.brand = te2.brand)
GROUP BY brand
因为groupby
将为您提供多行,否则您将得到错误:
SQL错误[21000]:错误:子查询作为表达式返回多行这是一个很好的解决方案,但可能有两个最小值,并且不会在db2i中使用workTOP。它可能会工作,但不一定是第2行。可以有两个最小值,如上所述,ItemID=1和4都有10@Buras上面的怎么样?如果它不起作用,我很抱歉,我没有一个db2实例来测试它。@TomStudee我相信这个函数的拼写是row_number()。@Buras在不同值的中间结果集上使用row_number(),在最里面的SELECT上不能有重复的值。最外层的SELECT看起来是多余的,因为它显示了重复的价格,但没有任何内容。但是,在其他示例中,您可能会考虑使用DeSEYRANK(),因为如果它们并列第二位,它将识别多行。rank()函数稍有不同,在这里可能没有用处,因为如果存在绑定值,则将跳过秩数。在第一名的平局中,排名第二的将被rank()跳过,但不会被dense_rank()跳过。
SELECT MIN( price )
FROM table
WHERE price > ( SELECT MIN( price )
FROM table )
SELECT MIN( price )
FROM table te1
WHERE price > ( SELECT MIN( price )
FROM table te2 WHERE te1.brand = te2.brand)
GROUP BY brand