我有一个名为Location_ID |Item_ID |Stock
1 |A |100
1 |B |500
1 |C |300
2 |A |10
2 |B |20
的表,结构如下:
location_ID
字段item_ID
和Item_ID |Stock_1 |Stock_2
A |100 |10
B |500 |20
C |300 |0
是复合键。我想从该单个表中生成以下数据:
Item_ID
我尝试编写了几个自联接查询,但它不起作用。还有另一个问题:location_ID
上{{1}} C不存在.2。我们如何设置值' 0' 0在结果表上,如果它不存在?有聪明才智的人可以放弃任何光明吗?
答案 0 :(得分:3)
select DIS_ITME_ID,
IFNULL ((select stock
from inventory
where location_id = 1
and item_id = DIS_ITEM_ID), 0) as stock_1,
IFNULL ((select stock
from inventory
where location_id = 2
and item_id = DIS_ITEM_ID), 0) as stock_2
from (select distinct item_ID as DIS_ITEM_ID from inventory)
答案 1 :(得分:1)
我知道这可能为时已晚,但有一种更简单的方法:
SELECT Item_Id,
SUM(
CASE WHEN Location_ID = 1 THEN
Stock
ELSE
0
END) As Stock1,
SUM(
CASE WHEN Location_ID = 2 THEN
Stock
ELSE
0
END) As Stock2
FROM Inventory
GROUP BY Item_Id
答案 2 :(得分:0)
您可以使用dinamic pivot查询:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(IF(i.location_ID = ''',
CAST(location_ID as CHAR(50)),
''', i.stock, 0)) AS stock_',
CAST(location_ID as CHAR(50))
)
) INTO @sql
FROM inventory;
SET @sql = CONCAT('SELECT i.item_ID, ', @sql, '
FROM inventory i
GROUP BY i.item_ID');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
您可以在此处找到更多信息:http://buysql.com/mysql/14-how-to-automate-pivot-tables.html