SELECT * FROM (SELECT x.PARENT_CLIENT ,sum(x.PS_L_AMOUNT)/100000000 as total FROM glsc_data.ti_trpt_temp_bill_his x WHERE x.beg_date::date =to_date('2023-05-24','yyyy-MM-dd') GROUP BY x.PARENT_CLIENT) s order by s.total desc limit 3 ,把这段代码做行转列操作用postgresql,但不要用tablefunc扩展
时间: 2024-02-03 12:13:56 浏览: 310
CAD常用命(练习用).pdf
可以使用CASE语句实现行转列操作,以下是一个示例代码:
```
SELECT
s.client AS client,
SUM(CASE WHEN s.rnk = 1 THEN s.total ELSE 0 END) AS total_1,
SUM(CASE WHEN s.rnk = 2 THEN s.total ELSE 0 END) AS total_2,
SUM(CASE WHEN s.rnk = 3 THEN s.total ELSE 0 END) AS total_3
FROM (
SELECT
x.PARENT_CLIENT AS client,
SUM(x.PS_L_AMOUNT) / 100000000 AS total,
ROW_NUMBER() OVER (PARTITION BY x.beg_date::date ORDER BY SUM(x.PS_L_AMOUNT) DESC) AS rnk
FROM glsc_data.ti_trpt_temp_bill_his x
WHERE x.beg_date::date = to_date('2023-05-24','yyyy-MM-dd')
GROUP BY x.PARENT_CLIENT
) s
GROUP BY s.client
ORDER BY s.client;
```
这段代码首先使用了子查询计算每个客户在指定日期的总金额,并按照金额进行降序排列并分配排名。然后在外部查询中使用CASE语句将每个客户的前三名金额转换为列。最后按照客户名称排序输出。
阅读全文