我对在Oracle SQL的嵌套查询中传递值的正确方法有疑问。我有以下代码:
SELECT b.business_id
FROM business b,
business_category c,
(SELECT COUNT(*) AS catcount
FROM business_category b1
GROUP BY b1.list_of_subcategories)
WHERE b.business_category = c.busn_catg_id
AND catcount = 1;
目标是查看名为BUSINESS_CATEGORY的表,并计算所有子类别的出现次数。该查询应该返回与业务子类别只有1的业务相关联的业务ID。本质上,我想返回具有唯一子类别的业务(意味着他们的子类别不会被多次使用)。
我可以在上面观察到我这样做的尝试。我决定使用嵌套查询,其中内部查询返回每个子类别的计数,并调用其返回值Catcount。然后,我确保Business_Catg_Id与Business_Category id匹配,以返回具有唯一类别的业务ID。
答案 0 :(得分:0)
我认为您正在寻找以下内容。它应该从BUSINESS_CATEGORY表中获取一个BUSINESS_ID以及该计数等于1的子类别的COUNT。
SELECT B.Business_Id
,COUNT(C.List_Of_Subcategories) AS CatCount
FROM BUSINESS B
INNER
JOIN BUSINESS_CATEGORY C
ON B.Business_Category = C.Busn_Catg_Id
GROUP
BY B.BusinessId
HAVING COUNT(C.List_Of_Subcategories) = 1
;
还将连接更改为符合ANSI标准
更新:添加以下查询以仅获取具有BUSINESS_CATEGORIES的那些BUSINESS_ID,并且这些类别在其中仅包含1个子类别。
SELECT B.Busines_ID
,B1.CatCount
FROM BUSINESS B
INNER
JOIN (
SELECT C.Busn_Catg_Id
,COUNT(C.List_Of_Subcategories) AS CatCount
FROM BUSINESS_CATEGORY C
GROUP
BY C.Busn_Catg_Id
HAVING COUNT(C.List_Of_Subcategories) = 1
) B1
ON B.Business_Category = B1.Busn_Catg_Id
希望这会有所帮助..
答案 1 :(得分:0)
如果我正确理解了问题,您可以使用分析函数计算CatCount
。然后你可以使用where
子句中的值:
SELECT B.Business_Id
FROM BUSINESS B JOIN
(SELECT C.*, COUNT(*) OVER (PARTITION BY List_Of_Subcategories) as CatCount
FROM BUSINESS_CATEGORY C
) C
ON B.Business_Category = C.Busn_Catg_Id
WHERE CatCount = 1;
我强烈建议您学习正确的JOIN
语法。