从SQL中的两列分组的结果中查找重复项

时间:2017-10-03 07:40:46

标签: sql

请告诉我以下查询的错误,说cnt是未知列。

SELECT SerialNumber, StoreCode, COUNT(*) as cnt
FROM serialnumberheader
GROUP BY serialnumber, StoreCode
having cnt > 1

3 个答案:

答案 0 :(得分:1)

HAVING列表之前评估SELECT子句,因此它不能引用该列别名。

SELECT SerialNumber, StoreCode, COUNT(*) as cnt
FROM serialnumberheader
GROUP BY serialnumber, StoreCode
having COUNT(*) > 1

或者,将查询包装在派生表中:

select SerialNumber, StoreCode, cnt
from
(
    SELECT SerialNumber, StoreCode, COUNT(*) as cnt
    FROM serialnumberheader
    GROUP BY serialnumber, StoreCode
) dt
where cnt > 1

答案 1 :(得分:0)

有些(全部?)here不允许您在wherehaving子句中使用列别名。您可以直接使用别名的表达式:

SELECT   SerialNumber, StoreCode, COUNT(*) AS cnt
FROM     serialnumberheader
GROUP BY SerialNumber, StoreCode
HAVING   COUNT(*) > 1

答案 2 :(得分:-1)

SELECT   SerialNumber, StoreCode, COUNT(1) AS cnt
FROM     serialnumberheader
GROUP BY SerialNumber, StoreCode
HAVING   COUNT(1) > 1