Replacing values with other values if a criteria is met

Michi :

SQL Fiddle:

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");

The table displays the purchasing status of different products using the Event_Type Offer or Order.


As you can see some of the products have an Event_Type Order whereas other once have the Event_Type Offer.
Now, I want to achieve that once a Product has an Event_Type Order the Quantity of the Order replaces the Quantity of the Offer. The result should look like this:

Product          Event_Type        Quantity
Product_A          Offer             300
Product_B          Order             250
Prodcut_C          Order             450
Product_D          Offer             400
Product_E          Offer             600

So far I am only able to query the data without replacing the values if a criteria is met:

SELECT
Product,
Event_Type,
Quantity
FROM Purchasing
GROUP BY 1,2;

What do I need to change in the SQL to get the result?

Strawberry :
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'

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=16468&siteId=1