Can we define a GROUP_CONCAT function in PostgreSQL?

后端 未结 2 1692
滥情空心
滥情空心 2021-01-27 12:00

I have several lines of SQL code for my legacy database with GROUP_CONCAT statements, as in:

SELECT SUM(age), GROUP_CONCAT(sal) FROM Users;
<         


        
2条回答
  •  Happy的楠姐
    2021-01-27 12:45

    Yes this is possible. Have a look at https://github.com/2ndQuadrant/mysqlcompat/blob/master/sql_bits/aggregate.sql where it's already done, as such:

    -- GROUP_CONCAT()
    -- Note: only supports the comma separator
    -- Note: For DISTINCT and ORDER BY a subquery is required
    CREATE OR REPLACE FUNCTION _group_concat(text, text)
    RETURNS text AS $$
      SELECT CASE
        WHEN $2 IS NULL THEN $1
        WHEN $1 IS NULL THEN $2
        ELSE $1 operator(pg_catalog.||) ',' operator(pg_catalog.||) $2
      END
    $$ IMMUTABLE LANGUAGE SQL;
    
    CREATE AGGREGATE group_concat (
        BASETYPE = text,
        SFUNC = _group_concat,
        STYPE = text
    );
    

提交回复
热议问题