db2 sql,如何在一个 table 的同一查询中仅获取最小值和最大值?
db2 sql, how to get min and max value only in the same query with one table?
使用此查询
SELECT distinct name,MIN(price) minprice, MAX(price) maxprice FROM cars where group='CNO' GROUP BY name HAVING MIN(price) > 1 order by minprice;
我得到这个结果
NAME MINPRICE MAXPRICE
---------------------------------------- ----------- -----------
Super CNO 20000 20000
CNO 340 40000 40000
CNO 110 60000 60000
CNO 790 100000 100000
如何只获取MIN和MAX价格来查看什么车最贵?
像这样
NAME MINPRICE MAXPRICE
---------------------------------------- ----------- -----------
Super CNO 20000 20000
CNO 790 100000 100000
当然我们不知道查询前的最低价和最高价,所以 20000 到 100000 之间是无效的。
您可以使用 window 函数。您的结果显示 min 和 max 具有相同的值,这让我怀疑每个名称只有一行。如果是:
select *
from (
select name, price,
rank() over(order by price desc) rn_desc,
rank() over(order by price) rn_asc
from cars
where price > 1
) c
where 1 in (rn_asc, rn_desc)
如果你真的需要聚合:
select *
from (
select name, min(price) min_price, max(price) max_price
rank() over(order by max(price) desc) rn_desc,
rank() over(order by min(price)) rn_asc
from cars
group by name
having min(price) > 1
) c
where 1 in (rn_asc, rn_desc)
使用此查询
SELECT distinct name,MIN(price) minprice, MAX(price) maxprice FROM cars where group='CNO' GROUP BY name HAVING MIN(price) > 1 order by minprice;
我得到这个结果
NAME MINPRICE MAXPRICE
---------------------------------------- ----------- -----------
Super CNO 20000 20000
CNO 340 40000 40000
CNO 110 60000 60000
CNO 790 100000 100000
如何只获取MIN和MAX价格来查看什么车最贵? 像这样
NAME MINPRICE MAXPRICE
---------------------------------------- ----------- -----------
Super CNO 20000 20000
CNO 790 100000 100000
当然我们不知道查询前的最低价和最高价,所以 20000 到 100000 之间是无效的。
您可以使用 window 函数。您的结果显示 min 和 max 具有相同的值,这让我怀疑每个名称只有一行。如果是:
select *
from (
select name, price,
rank() over(order by price desc) rn_desc,
rank() over(order by price) rn_asc
from cars
where price > 1
) c
where 1 in (rn_asc, rn_desc)
如果你真的需要聚合:
select *
from (
select name, min(price) min_price, max(price) max_price
rank() over(order by max(price) desc) rn_desc,
rank() over(order by min(price)) rn_asc
from cars
group by name
having min(price) > 1
) c
where 1 in (rn_asc, rn_desc)