由另一列分组的array_agg()值

发布于 2025-01-25 18:30:52 字数 918 浏览 4 评论 0 原文

这是我的表,如下所示

p_no  type  name  value
------------------------
1     A     Tomy  1
1     A     Nick  2
1     B     Tomy  3
1     B     Nick  4
1     C     Tomy  5
1     C     Nick  4
2     A     Tomy  8
2     A     Nick  7
2     B     Tomy  5
2     B     Nick  4

,表示每个 p_no 表示一个块,该块在两个 a,b,c type中都记录了poeple的值(可能是更多类型)。

我想选择一个具有其所有类型的人

给定的人的价值 p_no = 1,name = tomy

A    B    C    D
------------------
1    3    5    ..

我尝试过的,

SELECT p_no, t[1] A, t[2] B/*, t[3] C.....*/
FROM (
    SELECT p_no, ARRAY_AGG(type) FILTER (WHERE name='Tomy') t
    FROM type
    GROUP BY 1
    ORDER BY 1) _unused

但它插入了array_agg()includ yavence

我想我需要类似的东西到 array_agg('type''组'组'组)

是可能的查询吗?还是有更好的替代方案?

Here's my table like below

p_no  type  name  value
------------------------
1     A     Tomy  1
1     A     Nick  2
1     B     Tomy  3
1     B     Nick  4
1     C     Tomy  5
1     C     Nick  4
2     A     Tomy  8
2     A     Nick  7
2     B     Tomy  5
2     B     Nick  4

It means each p_no represents a block that records poeple's value in both A, B, C type (might be more types).

I want to select a person with his value of all types

Given p_no=1, name=Tomy

A    B    C    D
------------------
1    3    5    ..

I have tried

SELECT p_no, t[1] A, t[2] B/*, t[3] C.....*/
FROM (
    SELECT p_no, ARRAY_AGG(type) FILTER (WHERE name='Tomy') t
    FROM type
    GROUP BY 1
    ORDER BY 1) _unused

but it cannnot make the ARRAY_AGG() include the value

I think I need something similar to ARRAY_AGG('value' GROUP BY 'type')

Is this kind of query possible or is there any better alternatives?

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

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

发布评论

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

评论(1

夜吻♂芭芘 2025-02-01 18:30:52

您的直觉是对的。您想汇总 value type 订购,因此:

select p_no, t[1] as "A", t[2] as "B", t[3] as "C"
from (
    select p_no, array_agg(value order by type) as t
    from my_table
    where name = 'Tomy' 
    group by p_no
    ) s

db<> tiddle。

Your intuition is right. You want to aggregate value ordered by type, so:

select p_no, t[1] as "A", t[2] as "B", t[3] as "C"
from (
    select p_no, array_agg(value order by type) as t
    from my_table
    where name = 'Tomy' 
    group by p_no
    ) s

db<>fiddle.

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