我try 使用max(大小写),但无法将非透视数据转换为透视格式.

我们可以按以下格式透视此数据吗?

我的桌子:

Create table mytable (id integer,indicator text,value text);

Insert into mytable (id, indicator, value) values (1,'indicator 1', '10');
Insert into mytable (id, indicator, value) values (1,'indicator 2', 'yes');
Insert into mytable (id, indicator, value) values (1,'indicator 3', '123');
Insert into mytable (id, indicator, value) values (1,'state', 'ns');
Insert into mytable (id, indicator, value) values (1,'district', 'yr');
Insert into mytable (id, indicator, value) values (1,'block', 'ty');
id indicator value
1 indicator 1 10
1 indicator 2 yes
1 indicator 3 123
1 state ns
1 district yr
1 block ty

输出应如下所示:

id state district block indicator value
1 ns yr ty indicator 1 10
1 ns yr ty indicator 2 yes
1 ns yr ty indicator 3 123

推荐答案

您似乎想要将州/区/区块行旋转到列,同时保留"指示器"行.

一个选项是使用窗口函数进行透视,然后进行筛选:

select id, state, district, block, indicator, value
from (
    select t.*,
        max(value) filter(where indicator = 'state')    over(partition by id) as state,
        max(value) filter(where indicator = 'district') over(partition by id) as district,
        max(value) filter(where indicator = 'block')    over(partition by id) as block
    from mytable t
) t
where indicator like 'indicator%'
id state district block indicator value
1 ns yr ty indicator 1 10
1 ns yr ty indicator 2 yes
1 ns yr ty indicator 3 123

fiddle

Sql相关问答推荐

SQL Google Sheets:UNIQUE/DISTINCT和编码查询函数

Stack Exchange站点上的最短帖子(按正文长度计算,用户名为原始发帖(SEDE))

在甲骨文中查找前一个星期一的S日期

PostgreSQL中的合并命令是原子的,还是需要一些类似于SQL Server版本的内容?

UPDATE查询中的乐观锁

更新其组的日期字段值小于最大日期减go 天数的记录

你能过滤一个列表只返回多个结果吗?

返回找到的最小和最大row_number()spark SQL

从列中提取子字符串的ORDER BY CASE语句

HAVING子句内部过滤的正确方法

嵌套Json对象的SQL UPDATE WHERE

SQL仅返回第一个字母在A-Z之间的值

使用同一个表,为什么IN、NOT IN、NOT EXISTS和EXISTS有不同的输出?

试图找到两个身份列表的交集(列表的长度不同),但获取列 id 不明确?

PostgreSQL:从多个字段收集特定指标的最后一个条目

JSON对象查询SQL服务器

如何在插入时将字符串'03-January-2023'转换为日期时间

在给定列中具有特定值的行与 SQL 中的总行数的比率

条件前置值

SQL中所有先前日期的累计总和