这个问题是由于 Amazon Redshift(基于 Paraccel 的柱状分析数据库)的限制而产生的。不支持的功能之一是 references in a GROUP BY column to the results of a correlated subquery .
例如,以下语句将产生 Redshift 错误,因为 GROUP BY 使用由子查询生成的 list
。
select listing.listid,
(select count (sales.listid) from sales where sales.listid=listing.listid) as list
from listing
group by list, listing.listid;
以下例子来自Gordon Linoff是另一个不受支持的用例(对生成此一般性问题的 specific question 的回答)。
select type, (case when cnt > XXX then url end) as url, sum(cnt) as visit_cnt
from (select type, url, count(*) as cnt
from t
group by type, url
) t
group by type, url
order by type, sum(cnt) desc;
这个问题的目的是找到一个通用模式来克服这个特定的 Amazon Redshift 相关子查询限制。有哪些替代 SQL 模式可以实现与使用相关子查询中的值相同的结果?
最佳答案
左连接应该可以解决问题,除非我遗漏了什么。
SELECT listing.listid
,COUNT(sales.listid)
FROM listing
LEFT JOIN sales
ON sales.listid = listing.listid
GROUP BY listing.listid
ORDER BY COUNT(sales.listid) DESC
;
关于sql - 在 GROUP BY 列中替代对相关子查询结果的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20821214/