我有以下查询,其中的每个部分详细说明了库存进出。我想要的是有一个表格,如下所示,每个查询详细说明进出日期。
SELECT
inventory.DSTAMP,
inventory.NAME,
inventory.WEIGHT AS KG_Weight,
inventory.CODE
FROM inventory
WHERE inventory.code = 'In'
UNION
SELECT
inventory.DSTAMP,
inventory.NAME,
inventory.WEIGHT AS KG_Weight,
inventory.CODE
FROM inventory
WHERE inventory.code = 'Out'
输出为:
╔═════════╦════════════╦═════════════╗
║ Date ║ In ║ Out ║
╠═════════╬════════════╬═════════════╣
║01/01/14 ║ 4500 ║ 7800 ║
║02/01/14 ║ 0 ║ 8500 ║
║03/01/14 ║ 8000 ║ 0 ║
╚═════════╩════════════╩═════════════╝
有一种简单的方法吗?
答案 0 :(得分:1)
select DSTAMP,
sum(case when code = 'In' then WEIGHT else 0 end) as "In",
sum(case when code = 'Out' then WEIGHT else 0 end) as "Out"
from inventory
group by DSTAMP
答案 1 :(得分:1)
您可以使用条件聚合:
SELECT i.DSTAMP, i.NAME,
SUM(CASE WHENn i.CODE = 'IN' THEN i.WEIGHT END) as IN_KG_Weight,
SUM(CASE WHENn i.CODE = 'OUT' THEN i.WEIGHT END) as OUT_KG_Weight
FROM inventory i
WHERE i.code = 'In'
GROUP BY i.DSTAMP, i.NAME;
编辑:
仅按日期对此进行分组:
SELECT to_char(i.DSTAMP, 'YYYY-MM-DD') as yyyymmdd, i.NAME,
SUM(CASE WHENn i.CODE = 'IN' THEN i.WEIGHT END) as IN_KG_Weight,
SUM(CASE WHENn i.CODE = 'OUT' THEN i.WEIGHT END) as OUT_KG_Weight
FROM inventory i
WHERE i.code = 'In'
GROUP BY to_char(i.DSTAMP, 'YYYY-MM-DD'), i.NAME;
这会将值转换为日期字符串,可以进行排序。