Sql 使用数据透视表显示已添加和已删除数据的数量;存货;
我有一组存储在外部数据库中的信息,类似于以下格式: 表1Sql 使用数据透视表显示已添加和已删除数据的数量;存货;,sql,excel,vba,Sql,Excel,Vba,我有一组存储在外部数据库中的信息,类似于以下格式: 表1 Date, InventoryID, InventoryValue 1-12-2011, 1111-111A, 60 2-12-2011, 1111-111B, 50 3-12-2011, 1111-111C, 30 1-1-2012, 1111-111B, 40 2-1-2012, 1111-111C, 40 3-1-2012, 1111-111D, 40 我需要在Pivot表中以以下格式表示上述结果: 表2 Month, Beg
Date, InventoryID, InventoryValue
1-12-2011, 1111-111A, 60
2-12-2011, 1111-111B, 50
3-12-2011, 1111-111C, 30
1-1-2012, 1111-111B, 40
2-1-2012, 1111-111C, 40
3-1-2012, 1111-111D, 40
我需要在Pivot表中以以下格式表示上述结果:
表2
Month, Beg Inventory, Added, Removed, Ending Inventory
Jan, 3, 1, 1, 3
从表1中,我们可以看到,12月11日的库存中增加了1项到1月12日的库存(1111-111D),删除了1项(1111-111A),结果如表2所示
当我双击“添加”或“删除”库存时,我应该能够查看它们属于哪个InventoryID。该表还应反映过去12个月的“增加”和“删除”
我愿意接受任何使用VBA或SQL获得结果的建议。解决方案(纯SQL):
繁殖: 示例数据脚本:
SELECT * INTO Table1 FROM (
SELECT GETDATE() [Date], '1111-111A' [InventoryID], 60 [InventoryValue] UNION
SELECT GETDATE() [Date], '1111-111B' [InventoryID], 50 [InventoryValue] UNION
SELECT GETDATE() [Date], '1111-111C' [InventoryID], 30 [InventoryValue] UNION
SELECT DATEADD(month, 1, GETDATE()) [Date], '1111-111B' [InventoryID], 40 [InventoryValue] UNION
SELECT DATEADD(month, 1, GETDATE()) [Date], '1111-111C' [InventoryID], 40 [InventoryValue] UNION
SELECT DATEADD(month, 1, GETDATE()) [Date], '1111-111D' [InventoryID], 40 [InventoryValue] UNION
SELECT DATEADD(month, 2, GETDATE()) [Date], '1111-111B' [InventoryID], 40 [InventoryValue] UNION
SELECT DATEADD(month, 2, GETDATE()) [Date], '1111-111C' [InventoryID], 40 [InventoryValue] UNION
SELECT DATEADD(month, 2, GETDATE()) [Date], '1111-111D' [InventoryID], 40 [InventoryValue] UNION
SELECT DATEADD(month, 2, GETDATE()) [Date], '1111-111F' [InventoryID], 40 [InventoryValue]) as tbl
输出:
Date Begin Added Removed End
---------------------------------------
Feb 2012 0 3 0 3
Mar 2012 3 1 1 3
Apr 2012 3 1 0 4
Date Begin Added Removed End
---------------------------------------
Feb 2012 0 3 0 3
Mar 2012 3 1 1 3
Apr 2012 3 1 0 4