简体   繁体   中英

What is equivalent PostgreSQL syntax to Oracle's grouping_id?

This is Oracle Query Syntax I got. This is part of a much larger query written by Oracle that I need to convert to PostgreSQL. And I have no idea how this query can be done in PSQL. Please help!

I can't find any reference about how grouping_id can be converted in PSQL. Some posts said grouping_id is just an alias of grouping. So I converted grouping_id to grouping, decode to case when, but when I run the sql, It doesn't work.

SELECT
                  GROUPING_ID ( A.CO_ID
                              , A.CO_NM
                              , A.BIZ_ID
                              , A.BIZ_NM) AS CHK_NUM
                 , A.CO_ID
                 , DECODE( GROUPING_ID
                           ( A._CO_ID
                           , A._CO_NM
                           , A.BIZ_ID
                           , A.BIZ_NM )
                           , '7', 'count', '31', 'sum', A.CO_NM) AS CO_NM
                 , A.BIZ_ID
                 , DECODE( GROUPING_ID
                           ( A.CO_ID
                           , A.CO_NM
                           , A.BIZ_ID
                           , A.BIZ_NM )
                           , '3', 'count', A.BIZ_NM) AS BIZ_NM
         FROM
              (
                SELECT
                        *
                        FROM
                        (
                            SELECT  *
                              FROM
                                    TAB001 A
                         UNION ALL
                             SELECT
                                    *
                              FROM
                                    TAB002 A
                        ) A
                GROUP BY A.HDO_ID
                    , A.CO_ID
                    , A.BIZ_ID
               ) A
         GROUP BY ROLLUP ( A.CO_ID
                         , A.CO_NM
                         , A.BIZ_ID
                         , A.BIZ_NM)

Use GROUPING in PostgreSQL rather than GROUPING_ID in Oracle:

SELECT col1,
       col2,
       GROUPING(col1, col2),
       COUNT(col3)
FROM   table_name
GROUP BY ROLLUP(col1,  col2);

Which, for the sample data:

CREATE TABLE table_name (col1 VARCHAR(10), col2 VARCHAR(10), col3 VARCHAR(10));

INSERT INTO table_name (col1, col2, col3)
SELECT 'aaa', 'mmm', 'xxx' UNION ALL
SELECT 'aaa', 'mmm', 'yyy' UNION ALL
SELECT 'aaa', 'nnn', 'xxx' UNION ALL
SELECT 'aaa', 'nnn', 'yyy' UNION ALL
SELECT 'bbb', 'mmm', 'xxx' UNION ALL
SELECT 'bbb', 'mmm', 'yyy' UNION ALL
SELECT 'bbb', 'nnn', 'xxx';

Outputs:

col1 col2 grouping count
3 7
bbb mmm 0 2
bbb nnn 0 1
aaa mmm 0 2
aaa nnn 0 2
aaa 1 4
bbb 1 3

PostgreSQL db<>fiddle here

Oracle db<>fiddle here

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