基金产品交易流水表t_trade,描述如下:
init_date INTEGER COMMENT '日期',
client_id VARCHAR(20) COMMENT '客户号',
fund_code VARCHAR(6) COMMENT '基金产品代码',
business_flag INTEGER COMMENT '1卖出2买入',
business_balance NUMERIC(38, 10)
- 思路
- 按
日期
、基金代码
、买入卖出
分组,聚合出交易金额
,然后结果使用窗口函数进行排序,最后选出前十
- 按
-- 建表插入数据
CREATE OR REPLACE VIEW
t_trade(init_date, client_id, fund_code, business_flag, business_balance) AS
VALUES (1, 1, 1, 1, 1000),
(1, 88, 1, 1, 2000),
(1, 2, 2, 1, 900),
(1, 3, 3, 1, 800),
(1, 4, 4, 1, 700),
(1, 8, 9, 2, 10000),
(1, 7, 8, 2, 9000),
(1, 6, 7, 2, 8000);
SELECT *
FROM t_trade;
WITH t1 AS (
SELECT init_date,
fund_code,
business_flag,
SUM(business_balance) money
FROM t_trade
GROUP BY init_date, fund_code, business_flag
),
t2 AS (
SELECT *,
RANK() OVER (PARTITION BY init_date,business_flag ORDER BY money DESC ) rk
FROM t1
)
SELECT *
FROM t2
WHERE rk <= 10;