我有一張像下面這樣的桌子。每個 ID 都是唯一的。
| ID | 出門次數 |
|---|---|
| fef666 | 2個 |
| S335gg | 1個 |
| 9a2c50 | 1個 |
還有另一張像這樣的桌子↓。在第二個表中,“id”不是唯一的,單個 id 有不同的“category_name”。
| ID | 分類名稱 | 城市 |
|---|---|---|
| S335gg | 游戲和游戲用品 | tk |
| 9a2c50 | 電話公司 | 作業系統 |
| 9a2c50 | 娛樂中心 | 凱 |
| fef666 | 娛樂中心 | 凱 |
我想找出經常外出的人(times_of_going_out<5)和不經常外出的人(times_of_going_out<=5)的目的地(category_name)之間的區別。
** 兩個表都是大表的小樣本。
?出門兩次的人經常去哪里??外出6次的人經常去哪里?謝謝
預期的結果可能是這樣的
| 小于 5 | 超過5 |
|---|---|
| “times_of_going_out”少于 5 次的 uid 的前十名“category_name” | uid 的“times_of_going_out”超過 5 次的前十名“category_name” |
uj5u.com熱心網友回復:
腳步:
- 合并資料并匯總總 time_going_out
- 創建您需要的類別:小于等于 5 和大于 5。如果您不需要等于 5,您可以調整代碼
- 使用 dense_rank() 將兩個類別都排在前 10 名。這將根據總 time_going out 產生 1 - 10 的排名
- 過濾案例,因此它采用兩個類別的前 10 個值
with main as (
select
category_name,
sum(coalesce(times_of_going_out,0)) as total_time_per_category
from table1 as t1
left join table2 as t2
on t1.id = t2.id
group by 1
),
category as (
select
*,
if(total_time_per_category >= 5, 'more than 5', 'less than equal to 5') as is_more_than_5_times
from main
),
ranking_ as (
select *,
case when
is_more_than_5_times = 'more than 5' then
dense_rank() over (partition by is_more_than_5_times order by total_time_per_category desc)
else NULL
end AS rank_more_than_5,
case when
is_more_than_5_times = 'less than equal to 5' then
dense_rank() over (partition by is_more_than_5_times order by total_time_per_category)
else NULL
end AS rank_less_than_equal_5
from category
)
select
is_more_than_5_times,
string_agg(category_name,',') as list
from ranking_
where rank_less_than_equal_5 <=10 or rank_more_than_5 <= 10
group by 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/537814.html
標籤:Google Cloud Collective 数据库加入谷歌大查询
下一篇:以下遞回函式的時間復雜度是多少
