我有一个Personal
表,其中包含LastName
列和MaybeUniqueID
。
我想输出一个带有LastName
列的表格,其中设置在列MaybeUniqueID
上的计数器提供的行数超过1行。
我尝试了不同的SQL语句,例如HAVING
或GROUP BY
,但我没有得到我想要的结果。
请查看以下无法工作的摘要测试:
SELECT LastName
FROM Personal
JOIN
(SELECT MaybeUniqueID AS ID2,
COUNT(*) AS CNT
FROM Personal
--WHERE CNT > 1
GROUP BY MaybeUniqueID
HAVING cnt > 1
) AS MultiMaybeUniqueID
ON Personal.MaybeUniqueID = MultiMaybeUniqueID.ID2
答案 0 :(得分:4)
HAVING cnt > 1
应为HAVING COUNT(*) > 1
。
列别名只能在ORDER BY
子句中引用,而不能在HAVING
子句中引用。
虽然你也可以使用
;WITH T AS
(
SELECT LastName,
COUNT(*) OVER (PARTITION BY MaybeUniqueID) AS Cnt
FROM Personal
)
SELECT LastName
FROM T
WHERE Cnt > 1