如何使用列变量作为列名

时间:2018-04-11 06:11:00

标签: sql postgresql pivot crosstab

我目前有以下查询:

SELECT a.instance_type, SUM(a.quantity) as quantity, b.name, b.id
FROM sales_iteminstance a
INNER JOIN inventory_item b ON b.id = a.fk_item_id
GROUP BY (a.instance_type, b.id)
ORDER BY (b.id)

返回:

+---------------+----------+----------+----+
| instance_type | quantity |   name   | id |
+---------------+----------+----------+----+
| Sell          |        5 | Gas 50Kg |  5 |
| Buy           |        8 | Gas 50Kg |  5 |
| Return        |        4 | Gas 50Kg |  5 |
+---------------+----------+----------+----+

是否可以更新查询而不是压缩上面的表并使用instance_type作为列名?即。

+----+----------+------+-----+--------+
| id |   name   | sell | buy | return |
+----+----------+------+-----+--------+
|  5 | Gas 50Kg |    5 |   8 |      4 |
+----+----------+------+-----+--------+

2 个答案:

答案 0 :(得分:2)

是的,一个简单的数据透视查询可以做到这一点:

SELECT
    id,
    name,
    MAX(CASE WHEN instance_type = 'Sell'   THEN quantity END) AS sell,
    MAX(CASE WHEN instance_type = 'Buy'    THEN quantity END) AS buy,
    MAX(CASE WHEN instance_type = 'Return' THEN quantity END) AS "return"
FROM yourTable
GROUP BY
    id, name;

答案 1 :(得分:1)

你也可以在Postgres中使用FILTER子句(9.4 +)

SELECT
    id,
    name,
    MAX(quantity) FILTER ( WHERE instance_type = 'Sell' ) AS sell,
    MAX(quantity) FILTER ( WHERE instance_type = 'Buy'  ) AS buy,
    MAX(quantity) FILTER ( WHERE instance_type = 'Return') AS "return"
FROM yourTable
GROUP BY
    id, name;

Demo