Skip to content
Advertisement

PostgreSQL how to group by rows by primary key?

i have following query

 SELECT "Nomenclature",
            CASE
                WHEN ad."Title" = 'Кухня'
                    THEN au."Value"
                ELSE NULL END AS "Кухня",
            CASE
                WHEN ad."Title" = 'Вегетарианское'
                    THEN au."Value"
                ELSE NULL END AS "Вегетарианское",
            CASE
                WHEN ad."Title" = 'Постное' THEN au."Value"
                ELSE NULL END AS "Постное",
            CASE
                WHEN ad."Title" = 'Постное'
                    THEN au."Value"
                ELSE NULL END AS "Для ресторанов"
     FROM "AttributeUnit" au
              JOIN "AttributeDictionary" ad ON au."AttributeDictionary" = ad."@AttributeDictionary"
     WHERE "Nomenclature" = ANY (ARRAY(SELECT "@Nomenclature" FROM base_info))
       AND ad."Title" IN ('Кухня', 'Вегетарианское', 'Постное', 'Для ресторанов')

In the result i have 3 columns with same primary key.
enter image description here

How to group by the result that it will looks like

Nomenclature. Кухня Вегетерианское Постное Для ресторанов
8677 Италия True

Advertisement

Answer

I’m guessing you want aggregation:

SELECT "Nomenclature",
       MAX(CASE WHEN ad."Title" = 'Кухня' THEN au."Value" END) AS "Кухня",
       MAX(CASE WHEN ad."Title" = 'Вегетарианское' THEN au."Value" END) AS "Вегетарианское",
       MAX(CASE WHEN ad."Title" = 'Постное' THEN au."Value" END) AS "Постное",
       MAX(CASE WHEN ad."Title" = 'Постное' THEN au."Value" END) AS "Для ресторанов"
FROM "AttributeUnit" au JOIN
     "AttributeDictionary" ad
     ON au."AttributeDictionary" = ad."@AttributeDictionary"
WHERE "Nomenclature" = ANY (ARRAY(SELECT "@Nomenclature" FROM base_info)) AND
       ad."Title" IN ('Кухня', 'Вегетарианское', 'Постное', 'Для ресторанов')
GROUP BY "Nomenclature";
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement