请帮我执行此查询。我已经做了所有事情,但我认为我的查询不起作用。请帮忙。
表
ITEM
id Name
1 Computer 1
2 Computer 2
STATUS
id Stat_Name
1 Stock In
2 Stock Out
INVENTORY
id Item_id Status_id Quantity
1 1 1 100
2 1 2 200
3 1 1 30
4 2 1 35
5 2 2 36
我想要这个输出 输出:
Item overall_stock_in overall_stock_out
Computer1 130 200
Computer2 35 36
谢谢大家
答案 0 :(得分:1)
试试这个:
SELECT
B.Id,
B.Name,
SUM(CASE WHEN A.Status_id=1 THEN A.Quantity ELSE 0 END) AS overall_stock_in,
SUM(CASE WHEN A.Status_id=2 THEN A.Quantity ELSE 0 END) AS overall_stock_out
FROM INVENTORY A JOIN ITEM B ON A.Item_id=B.id
GROUP BY B.Id, B.Name
ORDER BY B.Name;
答案 1 :(得分:0)
也使用状态表 (更新了@ cdaiga的查询):
SELECT
C.Name,
SUM(CASE WHEN B.Status_Name='Stock In' THEN A.Quantity ELSE 0 END) AS
overall_stock_in,
SUM(CASE WHEN B.Status_Name='Stock Out' THEN A.Quantity ELSE 0 END) AS
overall_stock_out
FROM INVENTORY A JOIN ITEM C ON A.Item_id=C.id
JOIN "status" B ON A.Status_id=B.id
GROUP BY C.Name
ORDER BY C.Name;