我有两张桌子,我应该在数量,数量和平衡数量的库存物品中显示我写下我的查询如下:
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
以上查询给出了如下错误:
Msg 8120,Level 16,State 1,Line 14 Column'Inwards_Master.Date'是 在选择列表中无效,因为它不包含在任何一个中 聚合函数或GROUP BY子句。
任何1请帮帮我
答案 0 :(得分:1)
这是因为您没有从表格引用Date
而不是i
中选择s
列,您应该将其包含在具有汇总功能MIN
的选择列表中,或者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
也一样。
答案 1 :(得分: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