我有以下查询,并且正在尝试加入
SELECT COUNTRY_NAME, COUNTRY_ID
FROM OEHR_COUNTRIES;
这些结果
COUNTRY_NAME CO
---------------------------------------- --
Argentina AR
Australia AU
Belgium BE
Brazil BR
Canada CA
Switzerland CH
China CN
Germany DE
Denmark DK
Egypt EG
France FR
HongKong HK
Israel IL
India IN
Italy IT
Japan JP
Kuwait KW
Mexico MX
Nigeria NG
Netherlands NL
Singapore SG
United Kingdom UK
United States of America US
Zambia ZM
Zimbabwe ZW
我的第二个问题
SELECT COUNTRY_ID, COUNT(COUNTRY_ID) AS "LCOUNT"
FROM OEHR_LOCATIONS
GROUP BY COUNTRY_ID;
结果
CO LCOUNT
-- -------
US 4
SG 1
CA 2
CH 2
IT 2
MX 1
CN 1
DE 1
JP 2
IN 1
AU 1
UK 3
BR 1
NL 1
当我尝试加入这两个结果时,每个国家/地区都有计数
SELECT OEHR_COUNTRIES.COUNTRY_NAME, OEHR_COUNTRIES.COUNTRY_ID, COUNT(OEHR_LOCATIONS.COUNTRY_ID) AS LCOUNT
FROM OEHR_COUNTRIES
OUTER JOIN OEHR_LOCATIONS
ON OEHR_COUNTRIES.COUNTRY_ID = OEHR_LOCATIONS.COUNTRY_ID
ORDER BY LCOUNT;
我收到此错误
ON OEHR_COUNTRIES.COUNTRY_ID = OEHR_LOCATIONS.COUNTRY_ID
*
ERROR at line 4:
ORA-00904: "OEHR_COUNTRIES"."COUNTRY_ID": invalid identifier
ON OEHR_COUNTRIES.COUNTRY_ID = OEHR_LOCATIONS.COUNTRY_ID
*
ERROR at line 4:
ORA-00904: "OEHR_COUNTRIES"."COUNTRY_ID": invalid identifier
导致此错误的原因是什么?
有没有更简单的方法来实现我想要实现的目标?
答案 0 :(得分:1)
我认为这是你需要的。对于没有统计的国家/地区,它会列出0
。如果您不想列出没有计数的国家/地区,请使用INNER JOIN
SELECT C.COUNTRY_NAME,
case
when L.LCOUNT is null
then 0
else L.LCOUNT
END as LCOUNT
FROM OEHR_COUNTRIES C
LEFT JOIN
(SELECT COUNTRY_ID, COUNT(COUNTRY_ID) AS LCOUNT
FROM OEHR_LOCATIONS
GROUP BY COUNTRY_ID) L
on C.COUNTRY_ID=L.COUNTRY_ID
order by LCOUNT DESC
答案 1 :(得分:0)
您在加入语法中的可选RIGHT
之前错过了the mandatory LEFT
(或在其他情况下,OUTER
)。
目前,OUTER
这个词被误解为一个表别名,这就是导致你得到的错误的原因 - 解析器现在有一个OUTER.COUNTRY_ID
但是不是OEHR_COUNTRIES.COUNTRY_ID
。
添加缺少的单词以阻止它被视为别名,并阻止它默认为内部联接:
SELECT OEHR_COUNTRIES.COUNTRY_NAME, OEHR_COUNTRIES.COUNTRY_ID,
COUNT(OEHR_LOCATIONS.COUNTRY_ID) AS LCOUNT
FROM OEHR_COUNTRIES
LEFT OUTER JOIN OEHR_LOCATIONS
ON OEHR_COUNTRIES.COUNTRY_ID = OEHR_LOCATIONS.COUNTRY_ID
GROUP BY OEHR_COUNTRIES.COUNTRY_NAME, OEHR_COUNTRIES.COUNTRY_ID
ORDER BY LCOUNT;
我也添加了缺少的分组条款。使用您的样本数据:
COUNTRY_NAME CO LCOUNT
------------------------ -- ----------
Belgium BE 0
Argentina AR 0
Zimbabwe ZW 0
...
Zambia ZM 0
Mexico MX 1
China CN 1
...
Germany DE 1
Switzerland CH 2
Canada CA 2
Japan JP 2
Italy IT 2
United Kingdom UK 3
United States of America US 4
25 rows selected.
如果不添加该缺失的单词,更改对表的其他引用以使用(错误的)OUTER
别名将意味着它将执行,同样添加了group-by子句:
SELECT OUTER.COUNTRY_NAME, OUTER.COUNTRY_ID, COUNT(OEHR_LOCATIONS.COUNTRY_ID) AS LCOUNT
FROM OEHR_COUNTRIES
OUTER JOIN OEHR_LOCATIONS
ON OUTER.COUNTRY_ID = OEHR_LOCATIONS.COUNTRY_ID
GROUP BY OUTER.COUNTRY_NAME, OUTER.COUNTRY_ID
ORDER BY LCOUNT;
但它不会做你想要的 - 假设你想看到没有位置的国家的零数 - 因为它现在是一个内部联接:
COUNTRY_NAME CO LCOUNT
------------------------ -- ----------
Netherlands NL 1
India IN 1
...
Australia AU 1
Switzerland CH 2
Japan JP 2
Canada CA 2
Italy IT 2
United Kingdom UK 3
United States of America US 4
14 rows selected.
没有地点的11个国家根本没有显示内部联接。