请告诉我以下查询的错误,说cnt是未知列。
SELECT SerialNumber, StoreCode, COUNT(*) as cnt
FROM serialnumberheader
GROUP BY serialnumber, StoreCode
having cnt > 1
答案 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不允许您在where
和having
子句中使用列别名。您可以直接使用别名的表达式:
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