的最大值我有这已经工作的SQL语句,但我认为必须有比我更好的解决方案。SQL查询:选择再选择
我试图得到的文章与已从未出售的最高价。
有了这个选择我收到尚未售出的所有文章(数+价格):
select anr, price
from article a
where not exists(
select 1 from OrderItems o
where o.artnr = a.anr
)
的文章编号+价格结果如下
| Anr | Price |
| 1 | 300.0 |
| 4 | 340.0 |
| 5 | 340.0 |
| 3 | 200.0 |
我临时解决方案获得价格最高的商品是:
select anr, price
from article
where anr in(
select anr
from article a
where not exists(
select 1 from OrderItems o
where o.artnr = a.anr
)
)
and price = (
select max(price)
from article a
where not exists(
select 1 from OrderItems o
where o.artnr = a.anr
)
)
正确的解决方案是:
| Anr | Price |
| 4 | 340.0 |
| 5 | 340.0 |
有没有办法避免两次使用相同的子查询?
为了测试这里是缩短了与我的插入值创建表的脚本:
CREATE TABLE Article
(
Anr Int Primary Key,
Price Numeric(9,2) Not Null
);
CREATE TABLE Orders
(
OrderNr Int Primary Key
)
CREATE TABLE OrderItems
(
OrderNr Int References Orders On Delete Cascade,
ItemNr Int,
Artnr Int References Article Not Null,
Amount Int Not Null Check(Amount >= 0),
Primary Key(OrderNr, ItemNr)
)
-- articles without an order
Insert into Article (Anr, Price) values(1,300.0);
Insert into Article (Anr, Price) values(4,340.0);
Insert into Article (Anr, Price) values(5,340.0);
Insert into Article (Anr, Price) values(3,200.0);
-- articles for order with orderNr '1'
Insert into Article (Anr, Price) values(2,340.0);
Insert into Article (Anr, Price) values(6,620.0);
-- insert test order that contains the two articles
Insert into Orders (OrderNr) values (1);
Insert into OrderItems(OrderNr, ItemNr, Artnr, Amount) values(1,1,2,4);
Insert into OrderItems(OrderNr, ItemNr, Artnr, Amount) values(1,2,6,2);
我也阅读主题Select max value in subquery SQL 但我觉得在我的情况下,必须有做选择较短的方式。
的SQL Server/MySQL的/甲骨文/ PostgreSQL的/火鸟/ SQLite的? – lad2025
它应该适用于每个数据库,这就是为什么我不需要特定的数据库。我想通过使用标准的SQL来解决这个问题。 但我正在测试Oracle 12c :) – Johnny90
如果您添加脚本以创建表和记录..我可以帮你 – rdn87