请教各位大佬一个SQL编写问题,在数据表中,列转行

开源之夏第三届火热来袭,高校学生参与赢万元奖金!>>>

请教各位大佬一个SQL编写问题,在数据表中,列转行

假设数据格如下

名:db_value


ts code value 2022-08-18 00:00:00 123456 20 2022-08-18 00:00:00 654321 15 2022-08-17 00:00:00 123456 30 2022-08-17 00:00:00 654321 10 2022-08-13 00:00:00 123456 80 2022-08-13 00:00:00 654321 80

怎么编写sql,查出如下结果。(目前我使用的数据库是postgreSQL


ts 123456 654321 2022-08-18 00:00:00 20 15 2022-08-17 00:00:00 30 10 2022-08-13 00:00:00 80 80

回答

Select 123456,654321 from (Select ts,code,value from table where ts=‘2022-08-18 00:00:00’ )a PIVOT (Max (a.values) FOR a.code in (123456,654321))bSelect 123456,654321 from (Select ts,code,value from table where ts=‘2022-08-18 00:00:00’ )a PIVOT (Max (a.values) FOR a.code in (123456,654321))b 手机盲打的,你试试