Instruction
Perfect! Now, let's say we want to create two columns which show different order sums based on the ShipCountry column. We can use the construction we've just learned, like so:
SELECT
SUM(CASE
WHEN ShipCountry IN ('USA', 'Canada', 'Mexico')
THEN Amount
ELSE 0.0
END) AS SumNorthAmerica,
SUM(CASE
WHEN ShipCountry NOT IN ('USA', 'Canada', 'Mexico')
THEN Amount
ELSE 0.0
END) AS SumElsewhere
FROM Orders;
Above, we twice used the CASE WHEN construction from the previous exercise along with the SUM() function. For each row, CASE WHEN checks the value in the ShipCountry column. The order's Amount is only added if the ShipCountry value matches the given condition. Otherwise, 0.0 is added. As a result, we'll get the total sum from orders shipped to the USA, Canada, and Mexico in the first column and the total sum from orders shipped to all other countries in the second column.
Exercise
Show two columns:
SumHighFreight– The total amount generated by all orders withFreightvalues above100.0.SumLowFreight– The total amount generated by all orders withFreightvalues equal to or less than100.0.
Stuck? Here's a hint!
Calculate the first column as:
SUM(CASE
WHEN Freight > 100
THEN Amount
ELSE 0.0
END) AS SumHighFreight




