通过自定义列对Postgres进行分组

时间:2018-01-27 07:26:20

标签: sql postgresql

我对Postgres查询有一些复杂的要求。我想按自定义表达式进行分组:

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

在自定义字段中,如果column_1+column_2为空,则我需要column_3 column_3。这是因为某些数据已column_3分为column_1column_2。字段column_1column_2column_3VARCHAR.

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

如果查询中没有聚合函数或逐个阶段,则无法在查询中选择单个列。我的意思是您无法单独选择column_1column_2column_3。根据您的要求,我建议像这样查询。


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

希望我的回答能满足你。

答案 1 :(得分:0)

使用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

答案 2 :(得分:-1)

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