当我运行第一个查询时,所有运行正常:
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;
答案 0 :(得分:1)
该错误表明您的子查询不起作用,这是显而易见的,因为您不能在ORDER子句中使用SQL函数。您只能在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)
答案 1 :(得分:0)
我会在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中尝试此操作。