简体   繁体   中英

Grouping in Postgres by a custom column

I have a bit of complex requirement for a Postgres query. I want to group by a custom expression:

SELECT column_1, column_2, column_3 aggregate_function(column_4)
FROM tbl_name
GROUP BY custom_field 

In the custom field I want column_1+column_2 if column_3 is blank else column_3 . This is because some data has column_3 split into column_1 and column_2 . The fields column_1 , column_2 and column_3 are VARCHAR.

Any suggestions?

You can not select a single column in a query have group by if it not either in aggregate function or group by phase. I mean that you can not select column_1 , column_2 and column_3 separately. For your require, I suggest the query like this.


SELECT COALESCE(NULLIF(column_3,''), concat(column_1,column_2)) as custom_field, 
        aggregate_function(column_4)
FROM tbl_name
GROUP BY custom_field

OR


SELECT CASE
           WHEN NULLIF(column_3,'') IS NULL THEN concat(column_1,column_2)
           ELSE column_3
        END as custom_field, 
        aggregate_function(column_4)
FROM tbl_name
GROUP BY custom_field

Hopefully my answer will satisfy you.

New version with JSON

SELECT -- how to use json
   m.columns->>'column_1'
   , m.columns->>'column_2'
   , m.columns->>'column_3'
   , m.aggregate_function
FROM
(
   -- example of query
   SELECT CASE column_3 WHEN '' 
              THEN jsonb_build_object('column_1', column_1, 'column_2', column_2) 
              ELSE jsonb_build_object('column_3', column_3) 
          END AS columns
          , aggregate_function(column_4) AS aggregate_function 
   FROM tbl_name
   GROUP BY 1

) AS m
SELECT max(column_1) AS column_1
    , max(column_2) AS column_2
    , max(column_3) AS column_3
    , aggregate_function(column_4)
FROM tbl_name
GROUP BY CASE  
            WHEN column_3='' THEN (column_1, column_2, ''::varchar) 
            ELSE (''::varchar,''::varchar,column_3) 
          END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM