首页 > 解决方案 > 如何在 PostgreSQL 中将行转换为列?

问题描述

我有两个数据库表如下

site
id    |    name
1        Site One
2        Site Two
3        Site Three

asset_quantities
id   |   site_id   |  asset_type   | quantity
1           1             1              10
2           1             2              15
3           1             3              25
4           2             1              11
5           2             2              16
6           2             3              7
7           3             1              12
8           3             2              15
9           3             3              16

我想编写一个 SQL 查询,该查询将根据给定资产类型的“数量”列对结果进行排序 例如,我想根据所有站点中资产类型 1 的数量对结果进行降序排序。对于这样的场景,我将如何构建 SQL 查询?

如果我想要所有站点中资产类型 1 的数量的降序结果,下面是我想要的示例结果

site_id  |   asset_type_1_qty   |   asset_type_2_qty  |  asset_type_3_qty 
   3                12                     15                  16
   2                11                     16                  7
   1                10                     15                  25

标签: sqlpostgresqlsql-order-byjooq

解决方案


这是一个示例,它将在 sqlserver 中执行您想要的操作。您应该能够使其适应 postgres。

我有两个版本,一个对排序进行硬编码,第二个使用参数来决定排序依据。

首先在临时表变量中创建数据

declare @s table(id int, site_id int, asset_type int, quantity int)
insert @s values (1,1,1,10)
,(2,1,2,15)
,(3,1,3,25)
,(4,2,1,11)
,(5,2,2,16)
,(6,2,3,7)
,(7,3,1,12)
,(8,3,2,15)
,(9,3,3,16)

具有固定列排序的第一个版本

select site_id, 
    max(case when asset_type=1 then quantity else 0 end) as q1,
    max(case when asset_type=2 then quantity else 0 end) as q2,
    max(case when asset_type=3 then quantity else 0 end) as q3
from @s 
group by site_id
order by 2 desc

带参数列排序的第二个版本

declare @assetsort int;
set @assetsort=3

select * from (
    select site_id, 
        max(case when asset_type=1 then quantity else 0 end) as q1,
        max(case when asset_type=2 then quantity else 0 end) as q2,
        max(case when asset_type=3 then quantity else 0 end) as q3
    from @s 
    group by site_id
) q 
order by 
    case @assetsort when 1 then q1 when 2 then q2 when 3 then q3 end desc

推荐阅读