我们有两个表格:
Products
ID | Item | Supplier
1 | Harry Potter | Warner
2 | Harry Potter | Warner
3 | Game of Thrones | HBO
4 | The Simpsons | Warner
5 | The Simpsons | Warner
和
Prices
ID | Price
1 | 10.99
2 | 20.00
3 | 20.00
4 | 10.00
5 | 12.00
我正在尝试获得价格最低的商品的ID,其中有两个商品名称和供应商相同。
我可以获得重复的行:
SELECT
Products.ID,Products.Item,Products.Supplier,Prices.price
FROM
Products
LEFT JOIN Prices ON Prices.ID = Products.ID
WHERE Products.ID IN (
SELECT ID FROM Products WHERE Supplier="Warner" GROUP BY Item HAVING count(*) > 1
)
如何修改此项以仅显示价格最低的重复项目名称的Products.ID?
我尝试了ORDER BY,但这对我来说是一个错误。
结果应为:
ID | Item | Supplier | Price
1 | Harry Potter | Warner | 10.99
4 | The Simpsons | Warner | 10.00
谢谢,
瑞克
答案 0 :(得分:0)
首先,如果您在Products表中将ID作为主键,则您的表的实现必须改进,您的数据将如下所示(您需要主键)。
Products
ID | Item | Supplier
1 | Harry Potter | Warner
2 | Game of Thrones | HBO
Prices
ID | Price
1 | 10.99
1 | 20.00
2 | 20
现在,为了选择价格最低的物品,请使用最小功能
SELECT
Products.ID,Products.Item,Products.Supplier, MIN(Prices.price)
FROM
Products
LEFT JOIN Prices ON Prices.ID = Products.ID;
答案 1 :(得分:0)
/* Oracle syntax
with Products as
(
select 1 id, 'Harry Potter' item, 'Warner' supplier from dual union all
select 2 id, 'Harry Potter' item, 'Warner' supplier from dual union all
select 3, 'Game of Thrones', 'HBO' from dual union all
select 4, 'the simpsons', 'Warner' from dual union all
select 5, 'the simpsons', 'Warner' from dual
),
Prices as
(
select 1 id, 10.99 price from dual union all
select 2, 20.00 from dual union all
select 3, 20.00 from dual union all
select 4, 10.00 from dual union all
select 5, 12.00 from dual)
*/
select distinct p.id from Products p join Prices c
on (p.id = c.id)
where (p.item, p.supplier, c.price) in
(select item, supplier, min(price) from Products p join Prices c on (p.id = c.id) group by item, supplier having count(item) > 1);
(如果多个产品具有相同的商品价值和价格,此查询将同时显示两种产品)