连续显示栏位

时间:2019-05-08 06:21:31

标签: sql postgresql pivot crosstab

我有一个多选查询

SELECT C.CATEGORIES_NAME 
FROM CATEGORIES AS C 
WHERE CATEGORIES_ID = 1

UNION

SELECT L.LOCATION_TYPE_NAME 
FROM LOCATIONS_TYPE AS L 
WHERE LOCATION_TYPE_ID = 2 

UNION

SELECT S.SUBSCRIPTION_TYPE 
FROM SUBSCRIPTIONS AS S 
WHERE SUBSCRIPTION_ID = 3

他给了我结果:

 CATEGORIES_NAME |
------------------
       free      |
       Plaza     |
      Mobiles    |

我需要得到这个结果:

 CATEGORIES_NAME | LOCATION_TYPE_NAME | SUBSCRIPTION_TYPE |
-----------------------------------------------------------
       free      |       Plaza        |      Mobiles      |

这怎么办?

2 个答案:

答案 0 :(得分:1)

使用crosstab()-作为参考,您可以查看详细信息 here

CREATE EXTENSION tablefunc;
    SELECT *
    FROM crosstab(
        'SELECT C.CATEGORIES_NAME 
    FROM CATEGORIES AS C 
    WHERE CATEGORIES_ID = 1

    UNION

    SELECT L.LOCATION_TYPE_NAME 
    FROM LOCATIONS_TYPE AS L 
    WHERE LOCATION_TYPE_ID = 2 

    UNION

    SELECT S.SUBSCRIPTION_TYPE 
    FROM SUBSCRIPTIONS AS S 
    WHERE SUBSCRIPTION_ID = 3'
    ) AS ct(CATEGORIES_NAME text, LOCATION_TYPE_NAME text, SUBSCRIPTION_TYPE text)

答案 1 :(得分:1)

我认为最简单的解决方案是将SELECT放在查询之前:

SELECT (SELECT C.CATEGORIES_NAME 
        FROM CATEGORIES AS C 
        WHERE CATEGORIES_ID = 1
       ) as CATEGORIES_NAME,
       (SELECT L.LOCATION_TYPE_NAME 
        FROM LOCATIONS_TYPE AS L 
        WHERE LOCATION_TYPE_ID = 2
       ) as LOCATION_TYPE_NAME,
       (SELECT S.LOCATION_TYPE_NAME 
        FROM SUBSCRIPTIONS AS S 
        WHERE SUBSCRIPTION_ID = 3
       ) as LOCATION_TYPE_NAME;