代码之家  ›  专栏  ›  技术社区  ›  Alex Nikitin

PostgreSQL如何按主键按行分组?

  •  0
  • Alex Nikitin  · 技术社区  · 3 年前

    我有以下问题

     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 ('Кухня', 'Вегетарианское', 'Постное', 'Для ресторанов')
    

    在结果中,我有3列具有相同的主键。
    enter image description here

    如何根据结果进行分组

    ° °
    8677 ° 是的
    1 回复  |  直到 3 年前
        1
  •  3
  •   Gordon Linoff    3 年前

    我猜你想要:

    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";