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

                    Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                    Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                    How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page