我正在尝试从称为“行为”的表中获取摘要统计信息,该表存储了有关捐赠的数据。在此过程中,我想获得一个表格,其中包含与所有捐赠,非自动捐赠(DO)和自动捐赠(PA)有关的统计信息。为此,我使用了两个左连接(在同一表上,但具有不同的group by子句)。
我的查询返回以下错误:
错误代码:1054。未知列'a.yr。在“在子句中”
能否请您帮我找到解决这个问题的方法,或者提出实现我目标的另一种方法?非常感谢你!
SELECT
YEAR(a.act_date) AS yr,
SUM(a.amount) AS sum_all,
COUNT(a.amount) AS nb_all,
AVG(a.amount) AS avg_all,
COUNT(DISTINCT(a.contact_id)) AS unique_all,
sum_do,
nb_do,
avg_do,
unique_do,
sum_pa,
nb_pa,
avg_pa,
unique_pa
FROM
acts a
LEFT JOIN
(SELECT
YEAR(act_date) AS yr_do,
SUM(amount) AS sum_do,
COUNT(amount) AS nb_do,
AVG(amount) AS avg_do,
COUNT(DISTINCT(contact_id)) AS unique_do
FROM
acts
WHERE
YEAR(act_date) >= 1991 AND
act_type_id LIKE 'DO'
GROUP BY
1)
AS donation
ON a.yr = donation.yr_do
LEFT JOIN
(SELECT
YEAR(act_date) AS yr_pa,
SUM(amount) AS sum_pa,
COUNT(amount) AS nb_pa,
AVG(amount) AS avg_pa,
COUNT(DISTINCT(contact_id)) AS unique_pa
FROM
acts
WHERE
YEAR(act_date) >= 1991 AND
act_type_id LIKE 'PA'
GROUP BY
1)
AS pa
ON a.yr = pa.yr_pa
WHERE
YEAR(act_date) >= 1991
GROUP BY
1;
答案 0 :(得分:0)
您不能在同一查询中使用select中定义的别名。对于演示:
select YEAR(a.dt) myDt, myDt from T
也是无效的。 更改
ON a.yr = donation.yr_do
到
ON YEAR(a.act_date) = donation.yr_do