我有如下SQL查询:
SELECT a.ID as AID, a.Amt as AAmt
FROM
(SELECT
ID,
CASE
WHEN Col1 = 0
THEN SUM (Col2 + Col3)
ELSE 0
END AS Amt
FROM table1
GROUP BY ID, Amt) AS a
我收到错误:
无效的列名称'Amt'。
(注意:这适用于GROUP BY子句)。
答案 0 :(得分:2)
你不能GROUP BY
别名,
尝试
SELECT a.ID as AID, a.Amt as AAmt
FROM
(SELECT
ID,
CASE
WHEN Col1 = 0
THEN SUM (Col2 + Col3)
ELSE 0
END AS Amt
FROM table1
GROUP BY ID, Col1) AS a
如果你看一下SQL Query Order of Operations,你会注意到操作的顺序是
1.FROM clause
2.WHERE clause
3.GROUP BY clause
4.HAVING clause
5.SELECT clause
6.ORDER BY clause
这意味着GROUP BY
在SELECT
之前处理,这是您定义别名的位置。
这也解释了为什么你可以通过别名订购。
答案 1 :(得分:1)
您的查询似乎有点过于复杂,而且意图并不完全有意义。我怀疑你想要条件聚合:
SELECT ID, SUM(CASE WHEN col1 = 0 THEN col2 + col3 ELSE 0 END)
FROM table1
GROUP BY ID;