![](/img/trans.png)
[英]Return all rows using Count statement and Left Join with a Where Clause
[英]How to join results of different with clause
我有以下數據結構:
table user
user_id | year_month | fruit
------------------------------
1 | 2021-01 | orange
1 | 2021-01 | apple
1 | 2021-01 | melon
1 | 2021-01 | orange
1 | 2021-02 | kiwi
1 | 2021-02 | orange
1 | 2021-02 | banana
1 | 2021-02 | melon
1 | 2021-02 | orange
1 | 2021-03 | melon
1 | 2021-03 | orange
1 | 2021-03 | melon
1 | 2021-03 | banana
1 | 2021-03 | apple
我想生成這個 output
user_id | year_month | fruits | most_frequent
---------------------------------------------------------------------
1 | 2021-01 | orange, apple, melon | orange
1 | 2021-02 | kiwi, orange, banana, melon | orange
1 | 2021-03 | melon, orange, banana, apple | orange
它基本上是year_month
消耗的一組水果。 請注意,最后一列是一直以來消耗最多的水果,而不僅僅是一個月。
到目前為止,這是我的代碼:
WITH user AS (
-- logic to retrieve the results from 2 other tables and aggregate into 1 temporary table
-- contains a function inside
), ranking AS (
SELECT
user_id,
fruit,
COUNT(*) AS most_frequent,
FROM
user
GROUP BY
1, 2
ORDER BY
3 desc
-- LIMIT 1
)
SELECT
user.user_id,
user.year_month,
STRING_AGG(distinct user.fruit, ', ') as fruits,
FROM user
LEFT JOIN ranking
ON user.user_id = ranking.user_id
WHERE user.user_id = 1
GROUP BY 1
, 2
ORDER BY 2
這是我的 output:
user_id | year_month | fruits
-----------------------------------------------------
1 | 2021-01 | orange, apple, melon
1 | 2021-02 | kiwi, orange, banana, melon
1 | 2021-03 | melon, orange, banana, apple
我在使用最常見的列時遇到問題。 我最初的解決方案是取消注釋WITH ranking AS
中的limit 1
行,並將ranking.fruit 包含到主ranking.fruit
中,但是這樣我沒有返回任何數據。
更讓我困惑的是,如果我在with
子句之外運行此ranking
代碼 - 包括使用limit
線,我會得到我在“初始解決方案”中提到的所需分組。 所以這個問題似乎與一些連接問題有關。
考慮以下方法
select * from (
select user_id, year_month,
string_agg(distinct fruit) as fruits
from user
group by user_id, year_month
) join (
select user_id, fruit
from user
group by user_id, fruit
qualify 1 = row_number() over(partition by user_id order by count(*) desc)
)
using (user_id)
如果應用於您問題中的示例數據 - output 是
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.