gpt4 book ai didi

sql - 如何使用列变量作为列名

转载 作者:行者123 更新时间:2023-11-29 12:41:07 26 4
gpt4 key购买 nike

我目前有以下查询:

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 |
+----+----------+------+-----+--------+

最佳答案

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

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;

关于sql - 如何使用列变量作为列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49767701/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com