动态将MAX CASE和LEFT JOIN应用于所有表列

时间:2019-06-29 20:39:48

标签: postgresql

如何将此查询应用于users_flex表中的所有列?当前,它仅应用firstNamelastName。有没有办法将其动态地应用于表中的所有列?

 SELECT t1.users_core_id,
    t1."firstName",
    t2."lastName"
   FROM ( SELECT users_flex.users_core_id,
            max(
                CASE
                    WHEN users_flex."firstName" IS NOT NULL THEN users_flex.id
                    ELSE NULL::integer
                END) AS firstnameid,
            max(
                CASE
                    WHEN users_flex."lastName" IS NOT NULL THEN users_flex.id
                    ELSE NULL::integer
                END) AS lastnameid
           FROM users_flex
          GROUP BY users_flex.users_core_id) t
     LEFT JOIN users_flex t1 ON t1.id = t.firstnameid
     LEFT JOIN users_flex t2 ON t2.id = t.lastnameid
  ORDER BY t1.users_core_id;

0 个答案:

没有答案