[英]SQL Refer to alias in subquery
I want to query a table which looks like this:我想查询一个看起来像这样的表:
customer_id (INT), transaction_date (DATE), income(INT) customer_id (INT)、transaction_date (DATE)、收入(INT)
I'm trying to create a table which shows the sum of income per distinct customer_id, except for customers which made transactions ONLY in 2014.我正在尝试创建一个表格,显示每个不同 customer_id 的收入总和,但仅在 2014 年进行交易的客户除外。
My query:我的查询:
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;
The error I receive is "Unknown column a_customer_id
".我收到的错误是“未知列
a_customer_id
”。 How do I refer a subquery to an alias created in the first query?如何将子查询引用到在第一个查询中创建的别名?
Your query is not valid SQL.您的查询不是有效的 SQL。 Based on the description of your question, you seem to want aggregation and a
having
clause:根据您的问题的描述,您似乎想要聚合和
having
子句:
select customer_id, sum(income) sum_income
from mytable
group by customer_id
having max(year(transaction_date ) <> 2014) = 1
This gives you the total income
per customers, while filtering out customers that had transactions in 2014 only.这为您提供每位客户的总
income
,同时过滤掉仅在 2014 年进行过交易的客户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.