GROUP BY contents of json type column in Postgresql2019 Community Moderator ElectionPostgreSQL “DESCRIBE TABLE”How do I format a Microsoft JSON date?Can comments be used in JSON?How can I pretty-print JSON in a shell script?What is the correct JSON content type?Show tables in PostgreSQLWhy does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?How to exit from PostgreSQL command line utility: psql

Should we avoid writing fiction about historical events without extensive research?

How can I be pwned if I'm not registered on the compromised site?

Practical reasons to have both a large police force and bounty hunting network?

Why doesn't "adolescent" take any articles in "listen to adolescent agonising"?

Misplaced tyre lever - alternatives?

How can neutral atoms have exactly zero electric field when there is a difference in the positions of the charges?

Is every open circuit a capacitor?

Levi-Civita symbol: 3D matrix

Book about a time-travel war fought by computers

How to kill a localhost:8080

How do we objectively assess if a dialogue sounds unnatural or cringy?

How do I deal with being envious of my own players?

Why did the Cray-1 have 8 parity bits per word?

Why is it "take a leak?"

Create chunks from an array

How does signal strength relate to bandwidth?

When was drinking water recognized as crucial in marathon running?

How can I highlight parts in a screenshot

I encountered my boss during an on-site interview at another company. Should I bring it up when seeing him next time?

Was it really inappropriate to write a pull request for the company I interviewed with?

Giving a talk in my old university, how prominently should I tell students my salary?

Find maximum of the output from reduce

Has Wakanda ever accepted refugees?

Can a Trickery Domain cleric cast a spell through the Invoke Duplicity clone while inside a Forcecage?



GROUP BY contents of json type column in Postgresql



2019 Community Moderator ElectionPostgreSQL “DESCRIBE TABLE”How do I format a Microsoft JSON date?Can comments be used in JSON?How can I pretty-print JSON in a shell script?What is the correct JSON content type?Show tables in PostgreSQLWhy does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?How to exit from PostgreSQL command line utility: psql










0















I have a Postgresql table with a json column named "food".



Here is an example of some rows:



food
["cheese", "salmon", "eggs"]
["salmon", "cheese", "eggs"]
["broccoli", "ham", "milk"]
["salmon", "cheese", "eggs", "pizza"]


Current result:



food count
["cheese", "salmon", "eggs"] | 1
["salmon", "cheese", "eggs"] | 1
["broccoli", "ham", "milk"] | 1
["salmon", "cheese", "eggs", "pizza"] | 1


Desired result:



food count
["cheese", "salmon", "eggs"] | 2
["broccoli", "ham", "milk"] | 1
["salmon", "cheese", "eggs", "pizza"] | 1


Is there a way to GROUP BY the contents of a json field without regard to the order of the elements? If two rows have the same exact contents, then I want them to be grouped together.



My plan was to GROUP BY json_array_elements(food), but for some reason this only returns the first element of each row.










share|improve this question









New contributor




Kurt Kline is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
























    0















    I have a Postgresql table with a json column named "food".



    Here is an example of some rows:



    food
    ["cheese", "salmon", "eggs"]
    ["salmon", "cheese", "eggs"]
    ["broccoli", "ham", "milk"]
    ["salmon", "cheese", "eggs", "pizza"]


    Current result:



    food count
    ["cheese", "salmon", "eggs"] | 1
    ["salmon", "cheese", "eggs"] | 1
    ["broccoli", "ham", "milk"] | 1
    ["salmon", "cheese", "eggs", "pizza"] | 1


    Desired result:



    food count
    ["cheese", "salmon", "eggs"] | 2
    ["broccoli", "ham", "milk"] | 1
    ["salmon", "cheese", "eggs", "pizza"] | 1


    Is there a way to GROUP BY the contents of a json field without regard to the order of the elements? If two rows have the same exact contents, then I want them to be grouped together.



    My plan was to GROUP BY json_array_elements(food), but for some reason this only returns the first element of each row.










    share|improve this question









    New contributor




    Kurt Kline is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      0












      0








      0








      I have a Postgresql table with a json column named "food".



      Here is an example of some rows:



      food
      ["cheese", "salmon", "eggs"]
      ["salmon", "cheese", "eggs"]
      ["broccoli", "ham", "milk"]
      ["salmon", "cheese", "eggs", "pizza"]


      Current result:



      food count
      ["cheese", "salmon", "eggs"] | 1
      ["salmon", "cheese", "eggs"] | 1
      ["broccoli", "ham", "milk"] | 1
      ["salmon", "cheese", "eggs", "pizza"] | 1


      Desired result:



      food count
      ["cheese", "salmon", "eggs"] | 2
      ["broccoli", "ham", "milk"] | 1
      ["salmon", "cheese", "eggs", "pizza"] | 1


      Is there a way to GROUP BY the contents of a json field without regard to the order of the elements? If two rows have the same exact contents, then I want them to be grouped together.



      My plan was to GROUP BY json_array_elements(food), but for some reason this only returns the first element of each row.










      share|improve this question









      New contributor




      Kurt Kline is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.












      I have a Postgresql table with a json column named "food".



      Here is an example of some rows:



      food
      ["cheese", "salmon", "eggs"]
      ["salmon", "cheese", "eggs"]
      ["broccoli", "ham", "milk"]
      ["salmon", "cheese", "eggs", "pizza"]


      Current result:



      food count
      ["cheese", "salmon", "eggs"] | 1
      ["salmon", "cheese", "eggs"] | 1
      ["broccoli", "ham", "milk"] | 1
      ["salmon", "cheese", "eggs", "pizza"] | 1


      Desired result:



      food count
      ["cheese", "salmon", "eggs"] | 2
      ["broccoli", "ham", "milk"] | 1
      ["salmon", "cheese", "eggs", "pizza"] | 1


      Is there a way to GROUP BY the contents of a json field without regard to the order of the elements? If two rows have the same exact contents, then I want them to be grouped together.



      My plan was to GROUP BY json_array_elements(food), but for some reason this only returns the first element of each row.







      json postgresql






      share|improve this question









      New contributor




      Kurt Kline is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      Kurt Kline is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 19 hours ago







      Kurt Kline













      New contributor




      Kurt Kline is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 19 hours ago









      Kurt KlineKurt Kline

      13




      13




      New contributor




      Kurt Kline is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Kurt Kline is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Kurt Kline is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          2 Answers
          2






          active

          oldest

          votes


















          1














          Actually similar to the answer of @Scoots, but no sorts, windows, aso:



          SELECT (
          SELECT jsonb_agg(items order by items)
          FROM jsonb_array_elements(food) AS items
          ) AS food,
          count(*)
          FROM test_json_grouping
          GROUP BY 1;


          ...explained:



           QUERY PLAN 
          ------------------------------------------------------------------------------------------------------
          HashAggregate (cost=1635.60..1890.60 rows=200 width=40)
          Group Key: (SubPlan 1)
          -> Seq Scan on test_json_grouping (cost=0.00..1629.25 rows=1270 width=32)
          SubPlan 1
          -> Aggregate (cost=1.25..1.26 rows=1 width=32)
          -> Function Scan on jsonb_array_elements items (cost=0.00..1.00 rows=100 width=32)
          (6 rows)


          Result:



           food | count 
          ---------------------------------------+-------
          ["cheese", "eggs", "salmon"] | 2
          ["broccoli", "ham", "milk"] | 1
          ["cheese", "eggs", "pizza", "salmon"] | 1
          (3 rows)





          share|improve this answer








          New contributor




          Ancoron is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.




















          • Gah, I forgot you can select from the output of a function. This is a good answer.

            – Scoots
            18 hours ago


















          0














          Not directly - to Postgres they're different strings.



          However what we can do is unpack these json strings through json_array_elements, then repack them with our own sorting applied with json_agg. They're then homogenized for your group by to work.



          Here's a query illustrating exactly what I mean:



          select
          __food.food::text,
          count(1)
          from (
          select
          json_agg(_unpack.food order by _unpack.food::text asc) as food
          from (
          select
          row_number() over(),
          json_array_elements(food) as food
          from
          YOUR_SCHEMA.YOUR_FOOD_TABLE
          ) as _unpack
          group by
          _unpack.row_number
          ) as __food
          group by
          __food.food::text





          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );






            Kurt Kline is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55021511%2fgroup-by-contents-of-json-type-column-in-postgresql%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Actually similar to the answer of @Scoots, but no sorts, windows, aso:



            SELECT (
            SELECT jsonb_agg(items order by items)
            FROM jsonb_array_elements(food) AS items
            ) AS food,
            count(*)
            FROM test_json_grouping
            GROUP BY 1;


            ...explained:



             QUERY PLAN 
            ------------------------------------------------------------------------------------------------------
            HashAggregate (cost=1635.60..1890.60 rows=200 width=40)
            Group Key: (SubPlan 1)
            -> Seq Scan on test_json_grouping (cost=0.00..1629.25 rows=1270 width=32)
            SubPlan 1
            -> Aggregate (cost=1.25..1.26 rows=1 width=32)
            -> Function Scan on jsonb_array_elements items (cost=0.00..1.00 rows=100 width=32)
            (6 rows)


            Result:



             food | count 
            ---------------------------------------+-------
            ["cheese", "eggs", "salmon"] | 2
            ["broccoli", "ham", "milk"] | 1
            ["cheese", "eggs", "pizza", "salmon"] | 1
            (3 rows)





            share|improve this answer








            New contributor




            Ancoron is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.




















            • Gah, I forgot you can select from the output of a function. This is a good answer.

              – Scoots
              18 hours ago















            1














            Actually similar to the answer of @Scoots, but no sorts, windows, aso:



            SELECT (
            SELECT jsonb_agg(items order by items)
            FROM jsonb_array_elements(food) AS items
            ) AS food,
            count(*)
            FROM test_json_grouping
            GROUP BY 1;


            ...explained:



             QUERY PLAN 
            ------------------------------------------------------------------------------------------------------
            HashAggregate (cost=1635.60..1890.60 rows=200 width=40)
            Group Key: (SubPlan 1)
            -> Seq Scan on test_json_grouping (cost=0.00..1629.25 rows=1270 width=32)
            SubPlan 1
            -> Aggregate (cost=1.25..1.26 rows=1 width=32)
            -> Function Scan on jsonb_array_elements items (cost=0.00..1.00 rows=100 width=32)
            (6 rows)


            Result:



             food | count 
            ---------------------------------------+-------
            ["cheese", "eggs", "salmon"] | 2
            ["broccoli", "ham", "milk"] | 1
            ["cheese", "eggs", "pizza", "salmon"] | 1
            (3 rows)





            share|improve this answer








            New contributor




            Ancoron is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.




















            • Gah, I forgot you can select from the output of a function. This is a good answer.

              – Scoots
              18 hours ago













            1












            1








            1







            Actually similar to the answer of @Scoots, but no sorts, windows, aso:



            SELECT (
            SELECT jsonb_agg(items order by items)
            FROM jsonb_array_elements(food) AS items
            ) AS food,
            count(*)
            FROM test_json_grouping
            GROUP BY 1;


            ...explained:



             QUERY PLAN 
            ------------------------------------------------------------------------------------------------------
            HashAggregate (cost=1635.60..1890.60 rows=200 width=40)
            Group Key: (SubPlan 1)
            -> Seq Scan on test_json_grouping (cost=0.00..1629.25 rows=1270 width=32)
            SubPlan 1
            -> Aggregate (cost=1.25..1.26 rows=1 width=32)
            -> Function Scan on jsonb_array_elements items (cost=0.00..1.00 rows=100 width=32)
            (6 rows)


            Result:



             food | count 
            ---------------------------------------+-------
            ["cheese", "eggs", "salmon"] | 2
            ["broccoli", "ham", "milk"] | 1
            ["cheese", "eggs", "pizza", "salmon"] | 1
            (3 rows)





            share|improve this answer








            New contributor




            Ancoron is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.










            Actually similar to the answer of @Scoots, but no sorts, windows, aso:



            SELECT (
            SELECT jsonb_agg(items order by items)
            FROM jsonb_array_elements(food) AS items
            ) AS food,
            count(*)
            FROM test_json_grouping
            GROUP BY 1;


            ...explained:



             QUERY PLAN 
            ------------------------------------------------------------------------------------------------------
            HashAggregate (cost=1635.60..1890.60 rows=200 width=40)
            Group Key: (SubPlan 1)
            -> Seq Scan on test_json_grouping (cost=0.00..1629.25 rows=1270 width=32)
            SubPlan 1
            -> Aggregate (cost=1.25..1.26 rows=1 width=32)
            -> Function Scan on jsonb_array_elements items (cost=0.00..1.00 rows=100 width=32)
            (6 rows)


            Result:



             food | count 
            ---------------------------------------+-------
            ["cheese", "eggs", "salmon"] | 2
            ["broccoli", "ham", "milk"] | 1
            ["cheese", "eggs", "pizza", "salmon"] | 1
            (3 rows)






            share|improve this answer








            New contributor




            Ancoron is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.









            share|improve this answer



            share|improve this answer






            New contributor




            Ancoron is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.









            answered 18 hours ago









            AncoronAncoron

            616




            616




            New contributor




            Ancoron is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.





            New contributor





            Ancoron is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.






            Ancoron is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.












            • Gah, I forgot you can select from the output of a function. This is a good answer.

              – Scoots
              18 hours ago

















            • Gah, I forgot you can select from the output of a function. This is a good answer.

              – Scoots
              18 hours ago
















            Gah, I forgot you can select from the output of a function. This is a good answer.

            – Scoots
            18 hours ago





            Gah, I forgot you can select from the output of a function. This is a good answer.

            – Scoots
            18 hours ago













            0














            Not directly - to Postgres they're different strings.



            However what we can do is unpack these json strings through json_array_elements, then repack them with our own sorting applied with json_agg. They're then homogenized for your group by to work.



            Here's a query illustrating exactly what I mean:



            select
            __food.food::text,
            count(1)
            from (
            select
            json_agg(_unpack.food order by _unpack.food::text asc) as food
            from (
            select
            row_number() over(),
            json_array_elements(food) as food
            from
            YOUR_SCHEMA.YOUR_FOOD_TABLE
            ) as _unpack
            group by
            _unpack.row_number
            ) as __food
            group by
            __food.food::text





            share|improve this answer



























              0














              Not directly - to Postgres they're different strings.



              However what we can do is unpack these json strings through json_array_elements, then repack them with our own sorting applied with json_agg. They're then homogenized for your group by to work.



              Here's a query illustrating exactly what I mean:



              select
              __food.food::text,
              count(1)
              from (
              select
              json_agg(_unpack.food order by _unpack.food::text asc) as food
              from (
              select
              row_number() over(),
              json_array_elements(food) as food
              from
              YOUR_SCHEMA.YOUR_FOOD_TABLE
              ) as _unpack
              group by
              _unpack.row_number
              ) as __food
              group by
              __food.food::text





              share|improve this answer

























                0












                0








                0







                Not directly - to Postgres they're different strings.



                However what we can do is unpack these json strings through json_array_elements, then repack them with our own sorting applied with json_agg. They're then homogenized for your group by to work.



                Here's a query illustrating exactly what I mean:



                select
                __food.food::text,
                count(1)
                from (
                select
                json_agg(_unpack.food order by _unpack.food::text asc) as food
                from (
                select
                row_number() over(),
                json_array_elements(food) as food
                from
                YOUR_SCHEMA.YOUR_FOOD_TABLE
                ) as _unpack
                group by
                _unpack.row_number
                ) as __food
                group by
                __food.food::text





                share|improve this answer













                Not directly - to Postgres they're different strings.



                However what we can do is unpack these json strings through json_array_elements, then repack them with our own sorting applied with json_agg. They're then homogenized for your group by to work.



                Here's a query illustrating exactly what I mean:



                select
                __food.food::text,
                count(1)
                from (
                select
                json_agg(_unpack.food order by _unpack.food::text asc) as food
                from (
                select
                row_number() over(),
                json_array_elements(food) as food
                from
                YOUR_SCHEMA.YOUR_FOOD_TABLE
                ) as _unpack
                group by
                _unpack.row_number
                ) as __food
                group by
                __food.food::text






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 18 hours ago









                ScootsScoots

                2,1161227




                2,1161227




















                    Kurt Kline is a new contributor. Be nice, and check out our Code of Conduct.









                    draft saved

                    draft discarded


















                    Kurt Kline is a new contributor. Be nice, and check out our Code of Conduct.












                    Kurt Kline is a new contributor. Be nice, and check out our Code of Conduct.











                    Kurt Kline is a new contributor. Be nice, and check out our Code of Conduct.














                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55021511%2fgroup-by-contents-of-json-type-column-in-postgresql%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                    2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                    Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme