只是另一个SQL案例(分组方式)
我陷入了一个SQL问题,我不知道如何解决 假设我有这样一张表(关于房价估算): estimationDate是进行估算的日期,userID是进行估算的用户的ID,cityID是进行估算的城市的ID 我需要获得每个城市一个用户所做的最大估计数(我不在乎是哪一个,我不需要ID) 差不多只是另一个SQL案例(分组方式),sql,google-bigquery,Sql,Google Bigquery,我陷入了一个SQL问题,我不知道如何解决 假设我有这样一张表(关于房价估算): estimationDate是进行估算的日期,userID是进行估算的用户的ID,cityID是进行估算的城市的ID 我需要获得每个城市一个用户所做的最大估计数(我不在乎是哪一个,我不需要ID) 差不多 SELECT cityID,*maximum number of estimations made by one user from this city* FROM estimationsTable GROUP BY
SELECT cityID,*maximum number of estimations made by one user from this city* FROM estimationsTable GROUP BY cityID
有什么想法吗?一步一步:
select cityid, max(cnt)
from
(
select cityid, userid, count(*) as cnt
from estimationstable
group by cityid, userid
) counted
group by cityid
order by cityid;
试试下面这样
with cte as (
select userid,cityid,count(*) as cnt
from table_name group by userid,cityid
)
, cte2 as (
select *,
row_number() over(partition by cityid order by cnt desc) rn
from cte
) select * from cte2 where rn=1
解决方案1:
sol2:
像这样的东西应该有用
这样做的目的是在id和另一个查询中使用group by对内部查询中的所有事件进行计数,以获得最大值,或者使用ORDER by[Field]DESC
在BigQuery中,
groupby
会自动将最高的值放在最上面,我想您可以不用子查询就可以做到这一点:
select distinct cityid,
(array_agg(userid order by count(*) desc, userid))[ordinal(1)] as userid,
max(count(*)) over (order by count(*) desc) as cnt
from estimationstable
group by cityid, userid
嘿,这个问题安排得很好,但是标题可以改进,以总结你的问题。好吧,对不起,标题没有什么灵感(x)没问题,只是想下次帮你:)哦,谢谢,伙计,不知道你可以在两个专栏上分组!完美:)
SELECT id, MAX(maximum_number_of_estimations)
FROM (SELECT id,COUNT(*) AS maximum_number_of_estimations
FROM TABLE x)group by id as final_query
use order by Count DESC with group by`
select distinct cityid,
(array_agg(userid order by count(*) desc, userid))[ordinal(1)] as userid,
max(count(*)) over (order by count(*) desc) as cnt
from estimationstable
group by cityid, userid