[英]How to extract data in PostgresSQL?
我有一個基本數據庫,我正在嘗試為每個用戶提取最大的 3 個投資買單的基金名稱和金額。 我基本上等着有一個 output 行,其中包括:user_id、fund_name_1、amount_1、fund_name_2、amount_2、fund_name_3、amount_3 等。
我附上了數據庫的圖像。
制作的示例數據庫:
我嘗試了以下但它不工作
SELECT
user_id,
top_fund(1)
FROM (SELECT ROW_NUMBER() OVER(PARTITION BY fund_name
ORDER BY amount) AS top_funds
FROM investment_buy_order)
WHERE top_funds IN (1,3)
任何幫助都會很棒! (我是 SQL 的新手)
這與中位數無關。 只需使用條件聚合:
SELECT user_id,
max(case when seqnum = 1 then fund_name end),
max(case when seqnum = 1 then amount end),
max(case when seqnum = 2 then fund_name end),
max(case when seqnum = 2 then amount end),
max(case when seqnum = 3 then fund_name end),
max(case when seqnum = 3 then amount end)
FROM (SELECT ibo.*
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY amount) AS seqnum
FROM investment_buy_order ibo
) ibo
GROUP BY user_id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.