当我运行第一个查询时,一切都运行良好:
select uid,
(select top 1 city from UserData where UserData.uid = #uids.uid
group by city)
from #uids;
问题是当我添加
order by count(city)
时,我收到错误:由于内部错误,不支持这种类型的相关子查询模式
select uid,
(select top 1 city from UserData where UserData.uid = #uids.uid
group by city
order by count(city))
from #uids;
我会在 RedShift 中使用
row_number()
来完成此操作:
select u.uid, ud.city
from uids u left join
(select uid, city, count(*) as cnt,
row_number() over (partition by uid order by count(*) desc) as seqnum
from UserData ud
group by uid, city
) ud
on ud.uid = u.uid and seqnum = 1;
您也可以在 SQL Server 中尝试此操作。
该错误表明您的子查询不起作用,这很明显,因为您不能在 SQL 的 ORDER 子句中使用函数。您只能在 SELECT 和 HAVING 子句中使用它们。
如果您想按
count(city)
排序,则应将其添加到带有别名的 SELECT 子句中,并按别名排序。所以你的子查询可以是这样的:
(SELECT city, COUNT(*) AS city_count
FROM UserData
WHERE UserData.uid = #uids.uid
GROUP BY city
ORDER BY city_count
LIMIT 1)
Redshift 中不允许在 GROUP BY 列中引用相关子查询的结果。请在此处查看 AWS 文档:https://docs.aws.amazon.com/redshift/latest/dg/r_corlated_subqueries.html