我收到以下错误
Msg 102, Level 15, State 1, Line 11
Incorrect syntax near ')'.
当我尝试运行以下查询时
SELECT COUNT(*)
FROM tbl_usgGroupXref
WHERE GroupID = 478
AND accountNo IN (
SELECT TOP 5000 accountNo
FROM (
SELECT DISTINCT accountNo
FROM tbl_usgGroupXref
WHERE GroupID = 478
)
)
目前,我的查询包含来自单个表tbl_usgGroupXref
的一系列嵌套查询。该表包含每个帐户的多个月记录。最里面的查询是获取不同的帐户。下一个外部查询是获取任何5000个帐户(我似乎无法将TOP
与DISTINCT
结合起来)。最外层的查询是获取5000个帐户所代表的实际记录的计数。
任何人都可以对错误有所了解或修改这个sql以便它可以工作吗?
答案 0 :(得分:3)
您必须为此子查询添加别名:
FROM (
SELECT DISTINCT accountNo
FROM tbl_usgGroupXref
WHERE GroupID = 478
) AS MySubQuery
另外请注意,只是说TOP 5000
并不能保证您将获得第一个记录。
答案 1 :(得分:3)
您不需要子查询如此复杂,因为IN将忽略重复项。
。不需要DISTINCTSELECT COUNT(*)
FROM tbl_usgGroupXref
WHERE GroupID = 478
AND accountNo IN (
SELECT TOP 5000 accountNo
FROM tbl_usgGroupXref
WHERE GroupID = 478
)
然而,TOP 5000
没有意义,因为你没有ORDER BY,所以你有5000个任意行。
答案 2 :(得分:2)
您必须为大多数内部选择指定别名:
SELECT COUNT(*)
FROM tbl_usgGroupXref
WHERE GroupID = 478
AND accountNo IN (
SELECT TOP 5000 accountNo
FROM (
SELECT DISTINCT accountNo
FROM tbl_usgGroupXref
WHERE GroupID = 478
) ALIAS
)
或
结合TOP和DISTINCT
SELECT COUNT(*)
FROM tbl_usgGroupXref
WHERE GroupID = 478
AND accountNo IN (
SELECT DISTINCT TOP 5000 accountNo
FROM tbl_usgGroupXref
WHERE GroupID = 478
)
答案 3 :(得分:1)
你也可以写:
SELECT TOP 5000 accountNo
FROM (
SELECT DISTINCT accountNo
FROM tbl_usgGroupXref
WHERE GroupID = 478
)
为:
SELECT TOP 5000 accountNo
FROM tbl_usgGroupXref
WHERE GroupID = 478
GROUP BY accountNo
以及您的整个查询:
SELECT SUM(cnt)
FROM
( SELECT TOP 5000
COUNT(*) AS cnt
FROM tbl_usgGroupXref
WHERE GroupID = 478
GROUP BY accountNo
) grp