SQL 显示库存更新
SQL Display Inventory Updates
我有一个 table 显示库存的所有更新:
╔══════════════╦════════╦══════════╦═══════╗
║ ItemName ║ Type ║ Quantity ║ Date ║
╠══════════════╬════════╬══════════╬═══════╣
║ BottledWater ║ Add ║ 50 ║ 07/03 ║
║ BottledWater ║ Deduct ║ 20 ║ 07/03 ║
║ Chips ║ Add ║ 30 ║ 07/02 ║
║ BottledWater ║ Deduct ║ 10 ║ 07/02 ║
║ Chips ║ Deduct ║ 20 ║ 07/01 ║
╚══════════════╩════════╩══════════╩═══════╝
我想编写一个查询 return 一个 table 来显示添加和扣除库存的项目总数,table 看起来像:
╔══════════════╦═══════╦══════════╗
║ ItemName ║ Added ║ Deducted ║
╠══════════════╬═══════╬══════════╣
║ BottledWater ║ 50 ║ 30 ║
║ Chips ║ 30 ║ 20 ║
╚══════════════╩═══════╩══════════╝
有什么想法吗?
只使用条件聚合:
select item,
sum(case when type = 'Add' then quantity else 0 end) as added,
sum(case when type = 'Deduct' then quantity else 0 end) as deducted
from inventory
group by item;
语法略有偏差,但这是伪代码:
select ItemName, sum(Type==add) as added, sum(Type==deduct) as deducted,
from inventory
group by ItemName
我有一个 table 显示库存的所有更新:
╔══════════════╦════════╦══════════╦═══════╗ ║ ItemName ║ Type ║ Quantity ║ Date ║ ╠══════════════╬════════╬══════════╬═══════╣ ║ BottledWater ║ Add ║ 50 ║ 07/03 ║ ║ BottledWater ║ Deduct ║ 20 ║ 07/03 ║ ║ Chips ║ Add ║ 30 ║ 07/02 ║ ║ BottledWater ║ Deduct ║ 10 ║ 07/02 ║ ║ Chips ║ Deduct ║ 20 ║ 07/01 ║ ╚══════════════╩════════╩══════════╩═══════╝
我想编写一个查询 return 一个 table 来显示添加和扣除库存的项目总数,table 看起来像:
╔══════════════╦═══════╦══════════╗ ║ ItemName ║ Added ║ Deducted ║ ╠══════════════╬═══════╬══════════╣ ║ BottledWater ║ 50 ║ 30 ║ ║ Chips ║ 30 ║ 20 ║ ╚══════════════╩═══════╩══════════╝
有什么想法吗?
只使用条件聚合:
select item,
sum(case when type = 'Add' then quantity else 0 end) as added,
sum(case when type = 'Deduct' then quantity else 0 end) as deducted
from inventory
group by item;
语法略有偏差,但这是伪代码:
select ItemName, sum(Type==add) as added, sum(Type==deduct) as deducted,
from inventory
group by ItemName