如何在PostgreSQL中将多行转换为单行,但列名不同。

huangapple go评论66阅读模式
英文:

How to convert multiple rows into single row but with different column names in postgressql

问题

我想要的输出是:

id   name    amount1      amount2       amount3
1    abc     10           5             40
2    aaa     90           20            10
英文:

My resultant out is this using case when in postgres

id   name    amount1      amount2       amount3
1     abc    10           null          null
1     abc    null         5             null
1     abc    null         null          40

I want my output as:

id   name    amount1      amount2       amount3
1    abc     10           5             40
2    aaa     90           20            10

答案1

得分: 0

你可以使用 group by 和聚合函数 max()(如果你想按 id 列对数据进行求和,可以使用 sum()) 来实现:

select id, max(name) as name, max(amount1) as amount1, max(amount2) as amount2, max(amount3) as amount3
from mytable
group by id
英文:

You can do it using group by and the aggregate function max() ( use sum() if you want to sum your data by id ) :

select id, max(name) as name, max(amount1) as amount1, max(amount2) as amount2, max(amount3) as amount3
from mytable
group by id

答案2

得分: 0

你可以使用 group bycoalescenull 值聚合为0:

select id, name, sum(coalesce(amount1, 0)) as amount1, sum(coalesce(amount2, 0)) as amount2, sum(coalesce(amount3, 0)) as amount3
from yourtable
group by id, name

我理解你有一个 case when,你问题中的输入是那个查询的结果。在不了解更多关于你的表的情况下,我最好的建议是将上面的查询中的 yourtable 替换为 (<yourquery>) t,当然,你需要将 <yourquery> 替换为你实际的查询。

查看这个示例:SQL Fiddle链接

测试数据库:

create table yourtable(
    id int,
    name varchar(8),
    amount1 int,
    amount2 int,
    amount3 int
);

insert into yourtable(id, name, amount1, amount2, amount3)
values
(1, 'abc', 10, null, null),
(1, 'abc', null, 5, null),
(1, 'abc', null, null, 40),
(2, 'aaa', 90, 20, 10);

请注意,这里只提供了翻译的部分,没有其他内容。

英文:

You can aggregate using group by and coalesce null values to 0:

select id, name, sum(coalesce(amount1, 0)) as amount1, sum(coalesce(amount2, 0)) as amount2, sum(coalesce(amount3, 0)) as amount3
from yourtable
group by id, name

I understand you have a case when and your input in the question is the result of that. Without knowing more about your tables, the best I can suggest is to replace yourtable in the query above with (<yourquery>) t and of course, you need to replace <yourquery> with your actual query.

See this fiddle: http://sqlfiddle.com/#!15/e568d0/6

Test DB:

create table yourtable(
    id int,
    name varchar(8),
    amount1 int,
    amount2 int,
    amount3 int
);

insert into yourtable(id, name, amount1, amount2, amount3)
values
(1, 'abc', 10, null, null),
(1, 'abc', null, 5, null),
(1, 'abc', null, null, 40),
(2, 'aaa', 90, 20, 10);

huangapple
  • 本文由 发表于 2023年5月6日 21:01:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76189045.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定