I have a table called country that has 2 columns: orderid, country_code.
I need to do the following CASE WHEN:
SELECT
CASE
WHEN country_code IN ('PT','IT','ES','PL','AD') THEN 'SWE'
WHEN country_code IN ('MD','BG','BA','SI','HR','ME','RO','RS') THEN 'SEE'
WHEN country_code IN ('CI','GH','MA','NG','UG','KE','TN') THEN 'AFRICA'
WHEN country_code IN ('CI','GH','NG','UG','KE','TN') THEN 'SSA'
WHEN country_code IN ('UA','BY','GE','KZ','KG','AM') THEN 'ECA'
END AS region,
COUNT(DISTINCT orderid) AS amount_of_orders
FROM country
GROUP BY 1
However, when I run the code, Region SSA doesn’t appear because the tcondition before (AFRICA) is using the countries of SSA (SSA is the same as AFRICA but without MA).
How can I achieve to have the complete amount of orders for AFRICA and SSA?
rdbms: Amazon Redshift
EDIT:
This is my table right now:
SWE 200
SEE 500
AFRICA 350
SSA 0 <--- (it doesn't appear because the conditions were met by AFRICA region)
ECA 200
And I need the following:
SWE 200
SEE 500
AFRICA 350 --> (MA represent 150 orders)
SSA 200 --> (sames as AFRICA, but without MA)
ECA 200
2
Answers
You want to concatenate strings. For the lack of some CONCAT_WS function skipping nulls, just have a comma with every region and trim the string accordingly in the end.
UPDATE
You have complete changed your request. You answered that you want a column with a region list (e.g. ‘AFRICA,SSA’), but now you show that you want one row per single region. Please don’t make such fundamental changes to your requests. However, you want a union of single region queries now:
You could define a common table expression (CTE) that contains all country codes and theirs corresponding region, then join it with your data.
Demo: http://sqlfiddle.com/#!17/9eecb/101807