0

我有 2 张桌子,INWARDS并且OUTWARDS. 我必须显示每个不同库存的每个日期的总内向和总外向数以及该日期剩余的库存余额。我不需要按任何日期分组,我只想知道库存中的库存总数。

我的查询如下:

SELECT
    I.Date as'Date',
    P.ResourceName as 'Item Name',
    P.ResourceRate as'Rate',
    i.Qty as Inwards Quantity',
    (   select qty
        from Outwards_master
        where I.Date=S.Date and I.Nameofitem =S.Nameofitem
    ) as 'Outwards Quantity',
    (   select (sum(i.qty)-sum(S.Qty))
        from Inwards_Master
            inner join Outwards_Master
            on i.Nameofitem=S.Nameofitem
    ) as 'Balance'
From Resource_Master P, Inwards_Master I, Outwards_Master S
WHERE (I.Nameofitem= P.ResourceName) and P.TenderCode = 1

这个查询给了我一个错误。问题是什么?

错误是:

消息 8120,级别 16,状态 1,第 1 行列“Inwards_Master.Date”在选择列表中无效,因为它既不包含在聚合函数或 GROUP BY 子句中。

4

1 回答 1

0

我正在根据您的查询猜测您想要这样的东西:

SELECT I.Date as Date, 
  P.ResourceName as ItemName,
  P.ResourceRate as Rate,
  i.Qty as InwardsQuantity,
  s.qty as OutwardsQuantity,
  i.qty-S.Qty as Balance,
  O.UnitSymbol As ItemUnit
FROM UnitMaster O
INNER JOIN Resource_Master P
  ON O.UnitCode = P.Unitcode
INNER JOIN Inwards_Master I
  ON I.Nameofitem= P.ResourceName
INNER JOIN Outwards_Master S 
  ON I.Date=S.Date 
  AND I.Nameofitem =S.Nameofitem
WHERE P.TenderCode=1

如果要显示所有项目,则可能需要使用LEFT JOIN

SELECT I.Date as Date, 
  P.ResourceName as ItemName,
  P.ResourceRate as Rate,
  i.Qty as InwardsQuantity,
  s.qty as OutwardsQuantity,
  i.qty-S.Qty as Balance,
  O.UnitSymbol As ItemUnit
FROM UnitMaster O
INNER JOIN Resource_Master P
  ON O.UnitCode = P.Unitcode
LEFT JOIN Inwards_Master I
  ON I.Nameofitem= P.ResourceName
LEFT JOIN Outwards_Master S 
  ON I.Date=S.Date 
  AND I.Nameofitem =S.Nameofitem
WHERE P.TenderCode=1

编辑#1,根据您的评论,我无法完全确定问题所在,但您可以尝试在子查询中获取总量:

SELECT I.Date as Date, 
  P.ResourceName as ItemName,
  P.ResourceRate as Rate,
  i.TotalInQty as InwardsQuantity,
  s.TotalOutQty as OutwardsQuantity,
  i.TotalInQty-S.TotalOutQty as Balance,
  O.UnitSymbol As ItemUnit
FROM UnitMaster O
INNER JOIN Resource_Master P
  ON O.UnitCode = P.Unitcode
LEFT JOIN
(
  select sum(i.Qty) TotalInQty, Nameofitem
  from Inwards_Master I
  group by Nameofitem
) I
  ON I.Nameofitem= P.ResourceName
LEFT JOIN
(
  select sum(s.qty) TotalOutQty, Nameofitem
  from Outwards_Master S 
  group by s.Nameofitem
) S
  ON I.Date=S.Date 
  AND I.Nameofitem =S.Nameofitem
WHERE P.TenderCode=1
于 2013-01-08T12:03:40.540 回答