使用数据透视表显示添加和删除的“库存”数量

时间:2012-02-07 02:20:39

标签: 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

我需要在数据透视表中用以下格式表示上述结果:

表2

Month, Beg Inventory, Added, Removed, Ending Inventory
Jan, 3, 1, 1, 3

从表1中我们可以看到1个项目已从Dec'11库存添加到1月12日库存(1111-111D),并删除了一个项目(1111-111A),结果在表中2。

当我双击“已添加”或“已移除”广告资源时,我应该能够查看他们所属的库存ID。该表还应反映过去12个月的“已添加”和“已移除”。

我愿意接受任何使用VBA或SQL来获取结果的建议。

1 个答案:

答案 0 :(得分:2)

解决方案(纯SQL):

SELECT right(convert(varchar, tbl.[Date], 106), 8) [Date],
(SELECT COUNT(*) FROM [Table1] t1 WHERE month(t1.[Date]) = (tbl.m - 1) AND year(t1.[Date])=tbl.y) [Begin],
(SELECT COUNT(*)
    FROM Table1 t1
    WHERE month(t1.[Date]) = tbl.m
    AND year(t1.[Date])=tbl.y
    AND t1.InventoryID NOT IN (
        SELECT InventoryID
        FROM Table1
        WHERE month(t1.[Date]) = month(DATEADD(month, 1, [Date])) AND year(t1.[Date]) = year([Date]))) [Added],
(SELECT COUNT(*)
    FROM Table1 t1
    WHERE month(t1.[Date]) = (tbl.m - 1)
    AND year(t1.[Date])=tbl.y
    AND t1.InventoryID NOT IN (
        SELECT InventoryID
        FROM Table1
        WHERE month([Date]) = month(DATEADD(month, 1, t1.[Date])) AND year(t1.[Date]) = year([Date]))) [Removed],
(SELECT COUNT(*) FROM [Table1] t1 WHERE month(t1.[Date]) = (tbl.m) AND year(t1.[Date])=tbl.y) [End]
FROM (SELECT DISTINCT [Date], month([Date]) [m], year([Date]) [y] from Table1) as tbl

繁殖:

示例数据脚本:

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