Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

sql - How to group by duplicate value and nested the array Postgresql

I want to make a query that will give result, if there is duplicate id it will grouped, and the data below will intact to the same groupped data and it's all in array JSON data.

I make a query like this:

SELECT json_build_object(
    'nama_perusahaan',"a"."nama_perusahaan",
    'proyek', json_build_object(
        'no_izin',"b"."no_izin",
        'kode',c.kode,
        'judul_kode',d.judul
    )
)
FROM "t_pencabutan" "a"
LEFT JOIN "t_pencabutan_non" "b" ON "a"."id_pencabutan" = "b"."id_pencabutan"
LEFT JOIN "t_pencabutan_non_b" "c" ON "b"."no_izin" = "c"."no_izin"
LEFT JOIN "t_pencabutan_non_c" "d" ON "c"."id_proyek" = "d"."id_proyek"

the result is like below.

{
    "nama_perusahaan" : "JASA FERRIE", 
    "proyek" : 
    {
        "no_izin" : "26A/E/IUA/ABC/D8FD", 
        "kode" : "14302", 
        "judul_kode" : "IND"
    }
}
{
    "nama_perusahaan" : "JASA FERRIE", 
    "proyek" : 
    {
        "no_izin" : "26A/E/IUA/ABC/D8FD", 
        "kode" : "13121", 
        "judul_kode" : "IND B"
    }
}

what i expect was like this.

{
    "nama_perusahaan" : "JASA FERRIE", 
    "proyek" : 
    {
        "no_izin" : "26A/E/IUA/ABC/D8FD", 
        "kode" : "14302", 
        "judul_kode" : "IND"
    }
    {
        "no_izin" : "26A/E/IUA/ABC/D8FD", 
        "kode" : "13121", 
        "judul_kode" : "IND B"
    }
}

How could i make a query like my expect ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You would need to turn on aggregation, and use json_agg() to generate the proper data structure.

This should be close to what you want:

SELECT json_build_object(
    'nama_perusahaan',"a"."nama_perusahaan",
    'proyek', json_agg(
            json_build_object(
            'no_izin',"b"."no_izin",
            'kode',c.kode,
            'judul_kode',d.judul
        )
    )
)
FROM "t_pencabutan" "a"
LEFT JOIN "t_pencabutan_non" "b" ON "a"."id_pencabutan" = "b"."id_pencabutan"
LEFT JOIN "t_pencabutan_non_b" "c" ON "b"."no_izin" = "c"."no_izin"
LEFT JOIN "t_pencabutan_non_c" "d" ON "c"."id_proyek" = "d"."id_proyek"
GROUP BY "a"."nama_perusahaan"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...