Use OR conditions in WHERE clause as column names in result

Michi :

SQL Fiddle:

CREATE TABLE Sales (
    Product_ID VARCHAR(255),
    Country VARCHAR(255),
    Sales_Volume VARCHAR(255)
);

INSERT INTO Sales
(Product_ID, Country, Sales_Volume)
VALUES 
("P001", "US", "500"),
("P001", "US", "100"),
("P003", "US", "800"),
("P002", "DE", "300"),
("P001", "DE", "700"),
("P002", "NL", "200"),
("P002", "NL", "400");

In the table I have the the Sales in different Countries.
Now, I want to sum up the Sales per Country.
The expected result should look like this:

                US             DE 
P001           600            700
P002           NULL           300
P003           800            NULL

So far I have the following query:

SELECT
Product_ID,
Country,
SUM(Sales_Volume)
FROM Sales
WHERE 
Country = "US" 
OR Country ="DE"
GROUP BY 1,2;

This query basically works but instead of displaying the Country as column name it displays the country as value.

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

Gordon Linoff :

You could use conditional aggregation:

SELECT Product_ID,
       SUM(CASE WHEN Country = 'US' THEN Sales_Volume ELSE 0 END) as US,
       SUM(CASE WHEN Country = 'DE' THEN Sales_Volume ELSE 0 END) as DE
FROM Sales
GROUP BY Product_ID;

Guess you like

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