我编写了一个查询,该查询利用多条件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行以满足其中一个案例条件时,将其显示在输出中,例如使用NULL或其他预定义值,例如为:
| COUNTRY | Continent | NR |
| IT | Europe | 5 |
| | Asia | 0 |
依旧......
是否有可能实现,考虑到真正的查询类似于500行,由于条款中应用了很多条件,并且表有近60M行?此外,在此环境中,我无法创建其他数据库对象。
答案 0 :(得分: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