SELECT
( Select
COUNT(t2.ID) as Total_HH_Memebers_Primary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI = t1.URI
WHERE EXISTS (SELECT 1
FROM PScData t1
WHERE t1.SETTLEMENT_ID = SETTLEMENT_ID
AND t2.EDUCATION_LEVEL = 5
HAVING Count(*) > 1)
Group By t1.SETTLEMENT_ID
) col1
, (Select
COUNT(t2.ID) as Total_HH_Memebers_Secondary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI = t1.URI
WHERE EXISTS (SELECT 1
FROM PScData t1
WHERE t1.SETTLEMENT_ID = SETTLEMENT_ID
AND t2.EDUCATION_LEVEL = 10
HAVING Count(*) > 1)
Group By t1.SETTLEMENT_ID
) col2
这是我的查询,我想根据" WHERE"得到两个不同的结果。条件来自同一个表格的列,当我这样做它给出这个错误。有人如何正确吗?
答案 0 :(得分:2)
使用条件聚合:
SELECT
SUM(CASE WHEN t2.EDUCATION_LEVEL = 5
THEN 1 ELSE 0 END) AS Total_HH_Members_Primary,
SUM(CASE WHEN t2.EDUCATION_LEVEL = 10
THEN 1 ELSE 0 END) AS Total_HH_Members_Secondary,
t1.SETTLEMENT_ID
FROM PScData t1
INNER JOIN PscMemberData t2
ON t2._PARENT_AURI = t1.URI
GROUP BY
t1.SETTLEMENT_ID
HAVING COUNT(*) > 1;
select子句中的两个子查询对我来说完全没用。而且我认为我们可以删除EXISTS
子句,并将HAVING
子句移动到外部查询。
答案 1 :(得分:0)
尝试使用cte
;with col1 as
( Select
COUNT(t2.ID) as Total_HH_Memebers_Primary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI = t1.URI
WHERE EXISTS (SELECT 1
FROM PScData t1
WHERE t1.SETTLEMENT_ID = SETTLEMENT_ID
AND t2.EDUCATION_LEVEL = 5
HAVING Count(*) > 1)
Group By t1.SETTLEMENT_ID
),col2 as
(Select
COUNT(t2.ID) as Total_HH_Memebers_Secondary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI = t1.URI
WHERE EXISTS (SELECT 1
FROM PScData t1
WHERE t1.SETTLEMENT_ID = SETTLEMENT_ID
AND t2.EDUCATION_LEVEL = 10
HAVING Count(*) > 1)
Group By t1.SETTLEMENT_ID
)
select col1.SETTLEMENT_ID,col2.Total_HH_Memebers_Secondary, col1.Total_HH_Memebers_Primary from col1
join col2 on col1.SETTLEMENT_ID=col2.SETTLEMENT_ID
答案 2 :(得分:0)
错误消息告诉您:选择列表中的子查询不允许返回多于一个值,对于每个子查询都是如此。
您有2列和此查询返回的多行:
Select COUNT(t2.ID) as Total_HH_Memebers_Primary, t1.SETTLEMENT_ID from PScData t1 INNER JOIN PscMemberData t2 ON t2._PARENT_AURI = t1.URI WHERE EXISTS (SELECT 1 FROM PScData t1 WHERE t1.SETTLEMENT_ID = SETTLEMENT_ID AND t2.EDUCATION_LEVEL = 5 HAVING Count(*) > 1) Group By t1.SETTLEMENT_ID
所以不允许作为"子查询"在一个选择条款中。
您需要使用"条件聚合"相反,在别处解释。
答案 3 :(得分:0)
我已接受上述答案,我也找到了另一种方法:
这两种方法都是可行的,我发现的方法如下:
WITH EDU_LEVEL AS
(SELECT t1.SETTLEMENT_ID,t2.EDUCATION_LEVEL from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI = t1.URI
)
SELECT SETTLEMENT_ID,
(Select COUNT(*) FROM EDU_LEVEL WHERE SETTLEMENT_ID = T.SETTLEMENT_ID AND EDUCATION_LEVEL = 5 ) Total_HH_Memebers_Primary,
(Select COUNT(*) FROM EDU_LEVEL WHERE SETTLEMENT_ID = T.SETTLEMENT_ID AND EDUCATION_LEVEL = 10 ) Total_HH_Memebers_Secondary
FROM EDU_LEVEL AS T
Group By SETTLEMENT_ID