0

我有 2 个表格,我应该在其中显示数量,库存物品的数量和余额数量我写了如下查询:

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

上面的查询给了我一个如下错误:

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

任何人都可以帮我吗

4

2 回答 2

1

那是因为您没有Date从表引用中选择列inot s,您应该使用聚合函数MINor将其包含在选择列表中MAX,或者将其包含在GROUP BY子句中,如下所示:

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, 
    "Date",
    Nameofitem
  from Inwards_Master I
  group by Nameofitem, "Date"
) I
ON I.Nameofitem = P.ResourceName
LEFT JOIN
(
  select 
    sum(s.qty) TotalOutQty, 
    "Date",
    Nameofitem
  from Outwards_Master S 
  group by s.Nameofitem, "Date"
) S  ON I.Date       = S.Date 
    AND I.Nameofitem = S.Nameofitem
WHERE P.TenderCode = 1;

或者:如果您不需要GROUP BY约会,那么您希望为每个分组获得什么日期Nameofitem

在这种情况下,您必须使用聚合函数。例如MAX(Date),要像这样获取最新日期:

...
LEFT JOIN
(
  select 
    sum(i.Qty) TotalInQty, 
    MAX("Date") LatestDate,
    Nameofitem
  from Inwards_Master I
  group by Nameofitem
) I

对于s.

于 2013-01-10T08:56:16.157 回答
1

就像它说的那样 - 所以尝试在一个聚合中包含I.Date和:S.Date

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 COALESCE(sum(i.Qty), 0) AS TotalInQty, Nameofitem, Min(I.Date) AS Date
  from Inwards_Master I
  group by Nameofitem
) I
ON I.Nameofitem= P.ResourceName
LEFT JOIN
(
  select COALESCE(sum(s.qty), 0) AS TotalOutQty, Nameofitem, Min(S.Date) AS Date
  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-10T08:58:10.053 回答