[英]How to extract data in PostgresSQL?
I have a basic database, I am trying to extract the fund_name and amount for the largest 3 investment buy orders for each user.我有一个基本数据库,我正在尝试为每个用户提取最大的 3 个投资买单的基金名称和金额。 I basically wait to have one output row which consists of: user_id, fund_name_1, amount_1, fund_name_2, amount_2, fund_name_3, amount_3 etc.
我基本上等着有一个 output 行,其中包括:user_id、fund_name_1、amount_1、fund_name_2、amount_2、fund_name_3、amount_3 等。
I have attached an image of the database.我附上了数据库的图像。
example database made:制作的示例数据库:
I tried the following but it is not working我尝试了以下但它不工作
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)
Any help would be great!任何帮助都会很棒! (I am a newbie at SQL)
(我是 SQL 的新手)
This has nothing to do with medians.这与中位数无关。 Just use conditional aggregation:
只需使用条件聚合:
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.