用于计数的嵌套计数查询的 SQL 语法问题?
Posted
技术标签:
【中文标题】用于计数的嵌套计数查询的 SQL 语法问题?【英文标题】:SQL syntax issue for a nested count query for count? 【发布时间】:2014-12-23 21:55:48 【问题描述】:对于以下查询,我在 Oracle SQL Developer 中遇到了缺少表达式的错误, 有人可以帮我解决这个问题。
SELECT COUNT(DISTINCT SEC.ERROR_GROUP_ID),
COUNT(DISTINCT SEC_DET.ERROR_GROUP_ID),
COUNT(DISTINCT MB.ERROR_GROUP_ID),
COUNT(DISTINCT OD.ERROR_GROUP_ID),
SELECT COUNT(DISTINCT SEC_SCH.ERROR_GROUP_ID)
FROM SCHEMA.SECURITY SEC
LEFT OUTER JOIN SCHEMA.SECURITY_SCHEDULE SEC_SCH
ON SEC.MSD_SECURITY_ID =SEC_SCH.MSD_SECURITY_ID
WHERE SEC.MSD_SECURITY_ID IN
( SELECT DISTINCT main.MSD_SECURITY_ID
FROM SCHEMA2.Positions main
WHERE main.QUANTITY != 0
AND systimestamp >= main.eff_from_dt
AND main.eff_to_dt > systimestamp
AND systimestamp >= main.asrt_from_dt
AND main.asrt_to_dt > systimestamp
)
FROM SCHEMA.SECURITY SEC
JOIN SCHEMA.SECURITY_DETAIL SEC_DET
ON SEC.MSD_SECURITY_ID = SEC_DET.MSD_SECURITY_ID
LEFT OUTER JOIN SCHEMA.MUNI_BOND MB
ON SEC.MSD_SECURITY_ID=MB.MSD_SECURITY_ID
LEFT OUTER JOIN SCHEMA.OPTION_DETAIL OD
ON SEC.MSD_SECURITY_ID =OD.MSD_SECURITY_ID
WHERE SEC.MSD_SECURITY_ID IN
( SELECT DISTINCT main.MSD_SECURITY_ID
FROM SCHEMA2.Positions main
WHERE main.QUANTITY != 0
AND systimestamp >= main.eff_from_dt
AND main.eff_to_dt > systimestamp
AND systimestamp >= main.asrt_from_dt
AND main.asrt_to_dt > systimestamp
) ;
错误
ORA-00936: 缺少表达式 00936. 00000 - “缺少表达式” *原因: *行动: 行错误:365 列:3
【问题讨论】:
我已更新上述查询以使用括号螺母现在我收到此错误 ORA-00937: not a single-group group function 00937. 00000 - "not a single-group group function" *原因:*操作:行错误:365 列:11 【参考方案1】:子查询必须用括号括起来。添加它们后,Oracle 应该停止抱怨。
【讨论】:
【参考方案2】:子查询确实需要放在括号中。子查询可能只使用COUNT(DISTINCT)
而不是嵌套子查询来编写:
SELECT COUNT(DISTINCT SEC.ERROR_GROUP_ID),
COUNT(DISTINCT SEC_DET.ERROR_GROUP_ID),
COUNT(DISTINCT MB.ERROR_GROUP_ID),
COUNT(DISTINCT OD.ERROR_GROUP_ID),
(SELECT COUNT(DISTINCT SEC_SCH.ERROR_GROUP_ID)
FROM SCHEMA.SECURITY SEC LEFT OUTER JOIN
SCHEMA.SECURITY_SCHEDULE SEC_SCH
ON SEC.MSD_SECURITY_ID = SEC_SCH.MSD_SECURITY_ID
WHERE SEC.MSD_SECURITY_ID IN ( <values>)
) . . .
请注意,这与您的查询有非常小的语义差异。这不计算 NULL
值,而您的版本计算在内。您可以通过以下方式获得相同的语义:
(SELECT COUNT(DISTINCT SEC_SCH.ERROR_GROUP_ID) + MAX(CASE WHEN SEC_SCH.ERROR_GROUP_ID IS NULL THEN 1 ELSE 0 END)
FROM SCHEMA.SECURITY SEC LEFT OUTER JOIN
SCHEMA.SECURITY_SCHEDULE SEC_SCH
ON SEC.MSD_SECURITY_ID = SEC_SCH.MSD_SECURITY_ID
WHERE SEC.MSD_SECURITY_ID IN ( <values>)
) . . .
为此目的使用子查询是不寻常的。我想知道您是否可以使用分析函数。
【讨论】:
我仍然收到错误,不幸的是我无法将查询粘贴到 cmets 中,因为它太大了所以我添加了一个答案,而不是让专家查看。以上是关于用于计数的嵌套计数查询的 SQL 语法问题?的主要内容,如果未能解决你的问题,请参考以下文章
如何优化执行嵌套在 group-by 子句中的计数的 SQL 查询?