SQL 在子查询中引用别名

SQL Refer to alias in subquery

我想查询一个 table,它看起来像这样:

customer_id(整数),transaction_date(日期),收入(整数)

我正在尝试创建一个 table 来显示每个不同 customer_id 的收入总和,但仅在 2014 年进行交易的客户除外。

我的查询:

SELECT DISTINCT(customer_id) AS a_customer_id, sum( case when (SELECT YEAR(transaction_date) FROM table__ WHERE customer_id = a_customer_id) != ('2014') then income else 0 end) AS sum_income FROM table__ GROUP BY a_customer_id ORDER BY sum_income DESC;

我收到的错误是“未知列 a_customer_id”。 如何将子查询引用到第一个查询中创建的别名?

您的查询无效 SQL。根据您对问题的描述,您似乎想要聚合和一个 having 子句:

select customer_id, sum(income) sum_income
from mytable
group by customer_id
having max(year(transaction_date ) <> 2014) = 1

这会为您提供每个客户的总数 income,同时过滤掉仅在 2014 年有过交易的客户。