gpt4 book ai didi

mysql - MySQL 或 Postgres 中的数据透视表

转载 作者:行者123 更新时间:2023-11-29 02:19:32 26 4
gpt4 key购买 nike

最佳答案

示例数据:

create table test (
custname text,
computer numeric,
monitor numeric,
software numeric);

insert into test values
('Alison', 345.89, 123.45, 78.78),
('Jason', 435.34, 158.23, 243.54);

查询:

select 
custname "Customer",
unnest(array['Computer', 'Monitor', 'Software']) "Item type",
unnest(array[computer, monitor, software]) "Amount"
from test;

Customer | Item type | Amount
----------+-----------+--------
Alison | Computer | 345.89
Alison | Monitor | 123.45
Alison | Software | 78.78
Jason | Computer | 435.34
Jason | Monitor | 158.23
Jason | Software | 243.54
(6 rows)

如果 unnest() 不可用,您可以使用 union:

select custname "Customer", 'Computer' "Item type", computer "Amount" from test
union select custname, 'Monitor', monitor from test
union select custname, 'Sofware', software from test
order by 1, 2;

关于mysql - MySQL 或 Postgres 中的数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34055779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com