在 SQL 中,WHERE
子句在子句之前SELECT
处理。因此,当 SQL 开始过滤表中与查询相关的行时,它还不知道该列TOTAL_SPENT
。
有几种方法可以解决这个问题。
1)重复WHERE
子句中的表达式,而不是引用子句中的列名SELECT
:
SELECT Account_Id,
SUM(CASE WHEN Transaction_Code = 'Purchase' THEN Transaction_Amount ELSE 0 END) AS TOTAL_PURCHASED,
SUM(CASE WHEN Transaction_Code = 'Return' THEN Transaction_Amount ELSE 0 END) AS TOTAL_RETURNED,
(TOTAL_PURCHASED - TOTAL_RETURNED) AS TOTAL_SPENT
FROM Transactions_Table
WHERE Store = 'Store XYZ'
GROUP BY Account_Id
ORDER BY
(SUM(CASE WHEN Transaction_Code = 'Purchase' THEN Transaction_Amount ELSE 0 END) - SUM(CASE WHEN Transaction_Code = 'Return' THEN Transaction_Amount ELSE 0 END)) DESC
注意:如果您要查找500 以上的组,请使用该子句而不是.TOTAL_SPENT
HAVING
WHERE
2)使用视图。删除您的WHERE
子句并VIEW
使用您的查询创建一个。然后,从该视图中选择并添加您的WHERE
子句。
CREATE VIEW Whatever AS
SELECT Account_Id,
SUM(CASE WHEN Transaction_Code = 'Purchase' THEN Transaction_Amount ELSE 0 END) AS TOTAL_PURCHASED,
SUM(CASE WHEN Transaction_Code = 'Return' THEN Transaction_Amount ELSE 0 END) AS TOTAL_RETURNED,
(TOTAL_PURCHASED - TOTAL_RETURNED) AS TOTAL_SPENT
FROM Transactions_Table
GROUP BY Account_Id;
SELECT * From Whatever WHERE TOTAL_SPENT >= 500
3)使用嵌套选择:
select * from (
SELECT
Account_Id,
SUM(CASE WHEN Transaction_Code = 'Purchase' THEN Transaction_Amount ELSE 0 END) AS TOTAL_PURCHASED,
SUM(CASE WHEN Transaction_Code = 'Return' THEN Transaction_Amount ELSE 0 END) AS TOTAL_RETURNED,
(TOTAL_PURCHASED - TOTAL_RETURNED) AS TOTAL_SPENT
FROM Transactions_Table
WHERE Store = 'Store XYZ'
GROUP BY Account_Id
) where TOTAL_SPENT > 500 ORDER BY TOTAL_SPENT DESC;
4)如果您的数据库支持它,请使用 CTE:
WITH MyQuery AS (
SELECT
Account_Id,
SUM(CASE WHEN Transaction_Code = 'Purchase' THEN Transaction_Amount ELSE 0 END) AS TOTAL_PURCHASED,
SUM(CASE WHEN Transaction_Code = 'Return' THEN Transaction_Amount ELSE 0 END) AS TOTAL_RETURNED,
(TOTAL_PURCHASED - TOTAL_RETURNED) AS TOTAL_SPENT
FROM Transactions_Table
WHERE Store = 'Store XYZ'
GROUP BY Account_Id
)
SELECT * FROM MyQuery WHERE TOTAL_SPENT > 500 ORDER BY TOTAL_SPENT DESC;