使用多列确定SUM结果

时间:2018-04-25 09:36:05

标签: sql sql-server sql-server-2008

我无法理解下面的总和。我有一个项目表,显示位置,项目代码和大小代码。此表的独特功能是有一个标志,用于确定该位置是否存储特定项目。 我有另一张表格,显示物品的库存变动情况。此表还显示位置,项目,大小以及正或负条目。正/负条目的总和给出了当前的股票持有量。

我似乎无法做的是说明商品移动数量,其中商品和尺码标有'位置可以库存此商品'

第一个选择语句会带回可以按位置存储的项目

select
S.[Location Code],S.[Item No_],S.[size],
from [Stockkeeping Units] S
where [Range in Location] = 1

结果返回一个列表:

location Code| Item no | Size
     1       | SHIRT1  |  s
     1       | SHIRT1  |  m
     1       | SHIRT2  |  s
     1       | SHIRT2  |  m
     2       | SHIRT1  |  s
     2       | SHIRT2  |  m

第二个选择语句按地点带回物品的当前库存

select 
L.[Location Code],L.[Item No_],L.[size],
sum(L.[Quantity]) as Quantity 
from [Item Ledger Entry] L

location Code| Item no | Size | Quantity
     1       | SHIRT1  |  s   |   5
     1       | SHIRT1  |  m   |   3
     1       | SHIRT2  |  s   |   5
     1       | SHIRT2  |  m   |   7
     2       | SHIRT1  |  s   |   3
     2       | SHIRT2  |  m   |   0

当我尝试加入这些表以恢复前两个选择语句的组合时,它会误入歧途

select  L.[Location Code],L.[Item No_], L.[Variant Code],
sum(L.[Quantity]) as Quantity 
from [$Item Ledger Entry] L
join [Stockkeeping Unit] on [Item Ledger Entry].[Item No] = [Stockkeeping 
Unit].[Item No_]
where  [Stockkeeping Unit].[Range in Location] = 1
group by L.[Location Code],L.[Item No_],L.[Variant Code]

我希望看到的是:

location|item no|size|quantity where range in location is yes

联接的查询带回的结果是忽略了     [库存单位]。[位置范围] = 1个请求

联接查询也不会返回与第二个SELECT查询相同的SUM结果

1 个答案:

答案 0 :(得分:0)

看起来你的意思是:

SELECT [Location Code], [Item No_], [size], SUM([Quantity]) AS Quantity
FROM [Item Ledger Entry] L
WHERE EXISTS (
             SELECT *
             FROM [Stockkeeping Units] S
             WHERE S.[Range in Location]=1
               AND S.[Location code]=L.[Location code]
               AND S.[Item No]=L.[Item no]
               AND S.[Size]=L.[Size]
             )
GROUP BY L.[Location Code], L.[Item No_], L.[size];