汇总不同仓库位置的库存值

时间:2019-01-23 21:19:04

标签: sql sql-server

我希望在各个位置(SITEID)上汇总零件编号(ITEMID)的总值。

我设法构建了一个视图,显示我们的零件号(ITEMID)及其配置(CONFIGID)以及它们在不同仓库位置的库存数量。

SELECT TOP (100) PERCENT dbo.INVENTSUM.ITEMID,
dbo.INVENTDIM.CONFIGID, SUM(dbo.INVENTSUM.AVAILPHYSICAL) AS TOH,
dbo.INVENTDIM.INVENTSITEID

FROM dbo.INVENTSUM INNER JOIN
dbo.INVENTDIM ON dbo.INVENTSUM.INVENTDIMID =
dbo.INVENTDIM.INVENTDIMID

GROUP BY dbo.INVENTSUM.ITEMID, dbo.INVENTDIM.INVENTSITEID,
dbo.INVENTDIM.CONFIGID

HAVING (dbo.INVENTSUM.ITEMID LIKE N'36-2%') AND
(dbo.INVENTDIM.CONFIGID
= N'776')

ORDER BY dbo.INVENTSUM.ITEMID

这是我得到的输出:

ITEM ID CONFIGID  AVAILPHYSICAL         SITEID
36-2001   776   104.0000000000000000    PKR
36-2001   776   3.0000000000000000      USS002
36-2001   776   0.0000000000000000      CANS001

我正在寻找如何输出以下内容:

ITEM ID   CONFIGID  AVAILPHYSICAL
36-2001     776          107

我知道我不应该创建另一个视图来引用该视图吗?因为我尝试过这样做,并且设法获得了期望的输出。

SELECT TOP (100) PERCENT PARTNO, CONFIG, SUM(QTY) AS Expr1
FROM dbo._vw_Advance_FDO_Data
GROUP BY PARTNO, CONFIG
ORDER BY PARTNO

我得到了

PARTNO   CONFIG   QTY
36-2001    776    358.0000000000000000
36-200106  776    12.0000000000000000
36-2006    776    81.0000000000000000
36-2006B   776    40.0000000000000000

根据对嵌套视图的了解,我通过建议的更改更改了第一个视图:

SELECT TOP (100) PERCENT dbo.INVENTSUM.ITEMID AS PARTNO,
dbo.INVENTDIM.CONFIGID AS CONFIG, SUM(dbo.INVENTSUM.AVAILPHYSICAL) AS QTY

FROM dbo.INVENTSUM INNER JOIN
dbo.INVENTDIM ON dbo.INVENTSUM.INVENTDIMID = dbo.INVENTDIM.INVENTDIMID

GROUP BY dbo.INVENTSUM.ITEMID, dbo.INVENTDIM.CONFIGID

HAVING (dbo.INVENTSUM.ITEMID LIKE N'36-2%') AND (dbo.INVENTDIM.CONFIGID =
N'776')
ORDER BY PARTNO

看来这给了我想要的输出!

PARTNO     CONFIG     QTY
36-2001      776     358.0000000000000000
36-200106    776     12.0000000000000000

1 个答案:

答案 0 :(得分:0)

这是您使用别名查询的样子。它很容易阅读,输入方式少。我还将您的HAVING移至WHERE子句。在哪里用于过滤行,在哪里用于过滤组。

SELECT i.ITEMID
    , id.CONFIGID
    , SUM(i.AVAILPHYSICAL) AS TOH
FROM dbo.INVENTSUM i
INNER JOIN dbo.INVENTDIM id ON i.INVENTDIMID = id.INVENTDIMID
WHERE i.ITEMID LIKE N'36-2%'
    AND id.CONFIGID = N'776'
GROUP BY i.ITEMID
    , id.CONFIGID
ORDER BY i.ITEMID