CREATE TABLE Purchasing (
Event_Type VARCHAR(255),
Product VARCHAR(255),
Quantity VARCHAR(255)
);
INSERT INTO Purchasing
(Event_Type, Product, Quantity)
VALUES
("Offer", "Product_A", "300"),
("Offer", "Product_B", "200"),
("Offer", "Product_C", "500"),
("Offer", "Product_D", "400"),
("Offer", "Product_E", "600"),
("Order", "Product_B", "250"),
("Order", "Product_C", "450");
该表格使用products
Event_Type
或Offer
显示不同Order
的购买状态。
如您所见,某些产品具有Event_Type
Order
,而其他产品具有Event_Type Offer
。
现在,我想实现的是,一旦Product
具有Event_Type
Order
的{{1}}中的Quantity
取代了Order
Quantity
中的一个。
结果应如下所示:
Offer
到目前为止,如果满足条件,我只能查询数据而不替换值:
Product Event_Type Quantity
Product_A Offer 300
Product_B Order 250
Prodcut_C Order 450
Product_D Offer 400
Product_E Offer 600
要获得结果,我需要在SQL中进行哪些更改?
答案 0 :(得分:1)
您可以GROUP BY Product
并在子查询中选择max Event_Type
,然后再次与原始表进行联接
SELECT p2.Product,p2.Event_Type,p2.Quantity
FROM
(
SELECT Product, max(Event_Type) AS Event_Type
FROM Purchasing
GROUP BY Product
) p1
JOIN Purchasing p2
ON p2.Product=p1.Product
AND p2.Event_Type=p1.Event_Type
ORDER BY p2.Product
答案 1 :(得分:1)
从MySQL 8开始,排名通常是通过窗口函数完成的。我在这里使用MAX OVER
,因为'Order' > 'Offer'
。
select product, event_type, quantity
from
(
select p.*, max(event_type) over (partition by product) as best_event_type
from purchasing p
) ranked
where event_type = best_event_type;
演示:https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=b1337c181fd28c2ac3c1bfa18d60108f
更新:要获取更多值,请改用ROW_NUMBER
(或RANK
或DENSE_RANK
)。例如。类型排名'Accept' >> 'Order' >> 'Offer' >> 'Reject'
:
select product, event_type, quantity
from
(
select p.*,
row_number() over (partition by product
order by case event_type
when 'Accept' then 1
when 'Order' then 2
when 'Offer' then 3
when 'Reject' then 4
end) as rn
from purchasing p
) ranked
where rn = 1;
演示:https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=371817125aff1160f6865babd1f0f3bf
答案 2 :(得分:1)
在MySQL 8+中,使用窗口函数:
select p.*
from (select p.*,
row_number() over (partition by product order by field(Event_Type, 'Order', 'Offer')) as seqnum
from Purchasing p
) p
where seqnum = 1;
在早期版本中,我建议:
select p.*
from Purchasing p
where p.event_type = 'Order' or
(p.event_type = 'Offer' and
not exists (select 1 from Purchasing p2 where p2.product = p.product and p2.event_type = 'Order')
)
order by product;
Here是db <>小提琴。
请注意,这两种方法都适用于仅具有“订单”而没有“要约”的产品。
答案 3 :(得分:0)
SELECT x.product
, COALESCE(y.event_type,x.event_type) event_type
, COALESCE(y.quantity,x.quantity) quantity
FROM purchasing x
LEFT
JOIN purchasing y
ON y.product = x.product
AND y.event_type = 'order'
WHERE x.event_type = 'offer'