如何使用列变量作为列名
How to use column variables as column names
我目前有以下查询:
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)
哪个returns:
+---------------+----------+----------+----+
| instance_type | quantity | name | id |
+---------------+----------+----------+----+
| Sell | 5 | Gas 50Kg | 5 |
| Buy | 8 | Gas 50Kg | 5 |
| Return | 4 | Gas 50Kg | 5 |
+---------------+----------+----------+----+
是否可以更新查询以压缩上面的 table 并使用 instance_type
作为列名?即
+----+----------+------+-----+--------+
| id | name | sell | buy | return |
+----+----------+------+-----+--------+
| 5 | Gas 50Kg | 5 | 8 | 4 |
+----+----------+------+-----+--------+
是的,一个简单的数据透视查询可以做到这一点:
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;
您也可以在 Postgres (9.4+) 中使用 FILTER
子句
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;
我目前有以下查询:
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)
哪个returns:
+---------------+----------+----------+----+
| instance_type | quantity | name | id |
+---------------+----------+----------+----+
| Sell | 5 | Gas 50Kg | 5 |
| Buy | 8 | Gas 50Kg | 5 |
| Return | 4 | Gas 50Kg | 5 |
+---------------+----------+----------+----+
是否可以更新查询以压缩上面的 table 并使用 instance_type
作为列名?即
+----+----------+------+-----+--------+
| id | name | sell | buy | return |
+----+----------+------+-----+--------+
| 5 | Gas 50Kg | 5 | 8 | 4 |
+----+----------+------+-----+--------+
是的,一个简单的数据透视查询可以做到这一点:
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;
您也可以在 Postgres (9.4+) 中使用 FILTER
子句
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;