[英]Getting the 2 rows with min and max value from a table
我有一個包含以下各列的產品表:
id | product_name | price
1 | Red Shirt | 10.0
2 | White Shirt | 15.0
3 | Black Shirt | 9.0
4 | Yellow Shirt | 12.0
如何進行查詢以返回具有max(price)和min(price)的行? 使用上面的示例,輸出應為:
id | product_name | price
3 | Black Shirt | 9.0
2 | White Shirt | 15.0
在重復值的情況下,選擇哪個值都無所謂,只要輸出只有2行即可。
其他兩個答案都不能滿足最后一個要求...“如果重復的值,選擇哪個值都無所謂,只要輸出僅2行即可。”
如果有兩個具有相同值的產品,它們將返回三行。
下面通過添加rownum = 1子句來解決此問題。
with testtab (id, product_name, price) as
(select 1, 'Red Shrit', 10.00 from dual
union
select 2, 'Whtie Shrit', 15.00 from dual
union
select 3, 'Black Shrit', 9.00 from dual
union
select 4, 'Yellow Shrit', 12.00 from dual
union
select 4, 'Pink Shrit', 15.00 from dual)
select id, product_name, price
from testtab
where price in (select max(price) from testtab)
and rownum = 1
union
select id, product_name, price
from testtab where price in (select min(price) from testtab)
and rownum = 1
您可以使用ROW_NUMBER()
分析函數來完成此操作,該函數僅使用單個表掃描(與使用UNION
或子查詢的解決方案不同)。
Oracle安裝程序 :
CREATE TABLE product ( id, product_name, price ) AS
SELECT 1, 'Red Shirt', 10.0 FROM DUAL UNION ALL
SELECT 2, 'White Shirt', 15.0 FROM DUAL UNION ALL
SELECT 3, 'Black Shirt', 9.0 FROM DUAL UNION ALL
SELECT 4, 'Yellow Shirt', 12.0 FROM DUAL UNION ALL
SELECT 5, 'Blue Shirt', 9.0 FROM DUAL
查詢 :
SELECT id, product_name, price
FROM (
SELECT p.*,
ROW_NUMBER() OVER ( ORDER BY price ASC ) As min_price_rn,
ROW_NUMBER() OVER ( ORDER BY price DESC ) As max_price_rn
FROM product p
)
WHERE min_price_rn = 1
OR max_price_rn = 1;
輸出 :
ID | PRODUCT_NAME | PRICE -: | :----------- | ----: 2 | White Shirt | 15 3 | Black Shirt | 9
db <> 在這里撥弄
您可以在where條件中使用Or條件。
with cte as (select 1 as ID, 'Red Shirt' as Product_name, 10.0 as price from dual
union all
select 2 as ID, 'White Shirt' as Product_name, 15.0 as price from dual
union all
select 3 as ID, 'Black Shirt' as Product_name, 9.0 as price from dual
union all
select 4 as ID, 'Yellow Shirt' as Product_name, 12.0 as price from dual )
select * from cte
where price = (select min(price) minprice from cte) or price = (select max(price)
maxprice from cte);
輸出:
ID PRODUCT_NAME PRICE
2 White Shirt 15
3 Black Shirt 9
您也可以這樣做:
select *
from product
where price in (
(select min(price) from product),
(select max(price) from product)
);
或者您可以像下面這樣進行聯合:
-UNION方法
Select *
from Product
where price = (select min(price) from Product)
union
select *
from Product
where price = (select max(price) from Product);
使用以下內容:
Create Table Product(id int, product_name varchar(20), price decimal);
Insert into Product values (1, 'Red Shirt', 10.0);
Insert into Product values (2, 'White Shirt', 15.0);
Insert into Product values (3, 'Black Shirt', 9.0);
Insert into Product values (4, 'Yellow Shirt', 12.0);
Select *
from Product
where Price in (
(select min(Price) from Product),
(select max(Price) from Product)
);
最終輸出:
Id Product_Name Price
2 White Shirt 15
3 Black Shirt 9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.