如何合并这张桌子?

发布于 2025-02-06 18:17:45 字数 1228 浏览 1 评论 0原文

我有一个问题,我会尝试这样描述。我在Postgresql中有一张桌子,如下 (这是我所拥有的)。

现在,我正在将自己的头缠绕着如何“合并”或“合并”此表,使其看起来像是这样的 - > 这是我想要有。

多行是一般而言,在任何列中具有不同的ID或不同值(但我不再需要这些信息,因此我可能会摆脱它而不会产生任何后果)。

是否有任何功能或任何技巧可能会给我带来理想的结果吗?

我尝试的是:

select "name"
       , "array_agg" [1][1] as math_grade 
       , "array_agg" [2][2] as history_grade 
       , "array_agg" [3][3] as geography_grade 
from (select "name"
             , array_agg(array[math_grade,history_grade,geography_grade]) 
      from temp1234 
      group by "name") as abc

这是一个示例表:

create table temp1234 (id int
                       , name varchar(50)
                       , math_grade int
                       , history_grade int
                       , geography_grade int)

示例数据:

insert into temp1234 values (1, 'John Smith', 3, null, null)
insert into temp1234 values (2, 'John Smith', null, 4, null)
insert into temp1234 values (3, 'John Smith', null, null, 3)

最好的问候

I have a problem that I will try to describe like this. I have a table in PostgreSQL like below
(here's what I have).

Now I'm wrapping my head around how to "merge" or "consolidate" this table to make it look like this one on -> Here's what I want to have.

Multiple rows are the result of having different ID or different value in any column after in general (but I don't need that information anymore, so I may get rid of it without any consequences).

Is there any function or any trick that might bring me desired result?

What I have tried:

select "name"
       , "array_agg" [1][1] as math_grade 
       , "array_agg" [2][2] as history_grade 
       , "array_agg" [3][3] as geography_grade 
from (select "name"
             , array_agg(array[math_grade,history_grade,geography_grade]) 
      from temp1234 
      group by "name") as abc

Here is a example table:

create table temp1234 (id int
                       , name varchar(50)
                       , math_grade int
                       , history_grade int
                       , geography_grade int)

And example data:

insert into temp1234 values (1, 'John Smith', 3, null, null)
insert into temp1234 values (2, 'John Smith', null, 4, null)
insert into temp1234 values (3, 'John Smith', null, null, 3)

Best Regards

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暮倦 2025-02-13 18:17:45

这将为您提供您想要的东西,但我确信,有了更多数据,您会发现此查询并没有涵盖您需要的一切吗?请提供更多数据以提供更多详细的帮助。

select min(id), name, max(math_grade), max(history_grade), max(geography_grade)
from temp1234
group by name

This will give you what you want but I am sure that with more data you will find this query is not covering all you need ? Please do provide more data for more detailed help.

select min(id), name, max(math_grade), max(history_grade), max(geography_grade)
from temp1234
group by name

Here is a demo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文