SQL / Redshift错误-仅过滤值的首次出现

时间:2018-09-18 15:01:34

标签: sql amazon-redshift

我正在尝试使用以下SQL脚本返回值的首次出现:

SELECT a.store_id, b.store_name, c.prod_id FROM
  (
select a.store_id as sh, b.store_name, c.prod_id
count(1) ct,row_number() over  (partition by store_id order by store_id 
desc) row_num
from stores a, store_details b , product c
where a.id=b.store_id  and a.prod_id = c.id and  b.id = 101
group by a.store_id as sh, b.store_name, c.prod_id,
)t
WHERE row_num = 1;

我收到错误

无效的操作:关系“ a”不存在

我正在使用Redshift数据库。任何人都可以在这方面提供协助。谢谢。

1 个答案:

答案 0 :(得分:2)

您正在从子查询中进行选择,并且其别名为“ T”,因此无法从子查询外部引用子查询别名。

SELECT t.store_id, T.store_name, T.prod_id 
FROM
  (
   select a.store_id as sh, b.store_name, c.prod_id
   count(1) ct,row_number() over  (partition by store_id order by store_id 
   desc) row_num
   from stores a, store_details b , product c
   where a.id=b.store_id  and a.prod_id = c.id and  b.id = 101
   group by a.store_id as sh, b.store_name, c.prod_id,
)T
WHERE t.row_num = 1;