2017-03-31 47 views
0

我已經編寫了一個查詢,該查詢使用多條件CASE語句根據聚合函數執行表數據分析,例如:具有多個條件的情況下即使在某些條件不符合時也會生成輸出

select country, 
(case when country in ('DE','FR','IT') then 'Europe' 
when country in ('CH','JP','SK') then 'Asia' 
when country in ('US','CN') then 'North America' 
else 'Other' end) as 'Continent', 
count(*) as NR 
from citizenship 
group by country, 
(case when country in ('DE','FR','IT') then 'Europe' 
when country in ('CH','JP','SK') then 'Asia' 
when country in ('US','CN') then 'North America' 
else 'Other' end) 

事情是非常直接的到現在爲止,但我需要的是,當有表中的0行滿足的情況下條件之一,把它顯示在輸出,就像一個空或其他一些預定義值,如:

| COUNTRY | Continent | NR | 
| IT | Europe | 5 | 
|   | Asia | 0 | 

等等on ...

是否有可能實現,考慮到真正的查詢類似於500行,由於when子句中應用了許多條件,並且該表有近60M行?同樣在這個環境中,我無法創建額外的數據庫對象。

+0

@Stephen這是工作,但它並沒有顯示的情況下,所有規定條件時,不能滿足他們。所以亞洲沒有出現,這就是我正在努力實現的 – gm08

+0

@Stephen是的,正確的,我希望它們全部出現,即使CASE有一個或多個匹配項時也有0個匹配 – gm08

回答

0

你可以嘗試這樣的事情:

CREATE TABLE continents (NAME VARCHAR(30)) 
INSERT INTO continents VALUES ('Europe'); 
INSERT INTO continents VALUES ('Asia'); 
INSERT INTO continents VALUES ('North America'); 
INSERT INTO continents VALUES ('Other'); 
SELECT * FROM continents 

CREATE TABLE citizenship (country VARCHAR(2)); 
INSERT INTO citizenship VALUES ('DE') 
    INSERT INTO citizenship VALUES ('IT') 
    INSERT INTO citizenship VALUES ('IT') 


SELECT A.NAME AS CONTINENT, B.COUNTRY, COALESCE(NR,0) AS NR 
FROM continents A 
LEFT JOIN (
select country 
    ,case when country in ('DE','FR','IT') then 'Europe' 
    when country in ('CH','JP','SK') then 'Asia' 
    when country in ('US','CN') then 'North America' 
    else 'Other' end as Continent 
    ,COALESCE(count(*),0) as NR 
from citizenship 
group by country, 
(case when country in ('DE','FR','IT') then 'Europe' 
when country in ('CH','JP','SK') then 'Asia' 
when country in ('US','CN') then 'North America' 
else 'Other' end) 
) B ON A.name = B.CONTINENT 

輸出:

CONTINENT      COUNTRY NR 
------------------------------ ------- ----------- 
Europe       DE  1 
Europe       IT  2 
Asia       NULL 0 
North America     NULL 0 
Other       NULL 0 
+0

是的,那是因爲我之前嘗試過,謝謝你的回答,但我必須在不允許添加數據庫對象的生產環境中運行此查詢:/ – gm08

+0

這就是實現它的方法! (但是,派生表會更好 - 避免兩次寫入大小寫表達式。) – jarlh

+0

@ gm08,做一個UNION ALL,每個大陸做一個UNION ALL。 – jarlh

相關問題