sql sum join group by

时间:2016-08-11 09:53:56

标签: sql sql-server group-by

我的SQLcode

select  ITM.Item_Code,
        ITM.Item_Description,
        --INV.QTY,
        SUM(INV.QTY) as 'Balance QTY',
        UN.Unit_Code
from    Inventory INV
join Items ITM on INV.Item_ID=ITM.Item_ID
join Units UN on ITM.Unit_ID=UN.Unit_ID
where INV.Type1 in ('GRN','DTN','DGRN','SR','RN','SVN') AND INV.Stors_ID_1='6'
group by INV.Item_ID

然后执行,错误

    Msg 8120, Level 16, State 1, Line 1
Column 'Items.Item_Code' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

解释我解决这个问题。

由于

3 个答案:

答案 0 :(得分:0)

尝试使用相关的子查询:

select  ITM.Item_Code,
        ITM.Item_Description,
        --INV.QTY,
        (select SUM(INV2.QTY) from Inventory INV2 where INV2.Item_ID = INV.Item_ID) as 'Balance QTY',
        UN.Unit_Code
from    Inventory INV
join Items ITM on INV.Item_ID=ITM.Item_ID
join Units UN on ITM.Unit_ID=UN.Unit_ID
where INV.Type1 in ('GRN','DTN','DGRN','SR','RN','SVN') AND INV.Stors_ID_1='6'

(一般GROUP BY规则说: 如果指定了GROUP BY子句,则SELECT列表中的每个列引用必须标识分组列或者是set函数的参数。

答案 1 :(得分:0)

select  ITM.Item_Code,
    ITM.Item_Description,
    --INV.QTY,
    SUM(INV.QTY) as 'Balance QTY',
    UN.Unit_Code
   from    Inventory INV
     join Items ITM on INV.Item_ID=ITM.Item_ID
      join Units UN on ITM.Unit_ID=UN.Unit_ID
     where INV.Type1 in ('GRN','DTN','DGRN','SR','RN','SVN') AND INV.Stors_ID_1='6'
        group by INV.Item_ID,ITM.Item_Description,

尝试以上查询。

答案 2 :(得分:-1)

您收到此错误是因为列ITM.Item_CodeITM.Item_DescriptionUN.Unit_Code位于SELECT中,但既不是聚合函数的参数MAX()MIN()等,也不在GROUP BY。解决方案很简单

select ITM.Item_Code, ITM.Item_Description,
       SUM(INV.QTY) as [Balance QTY],
       UN.Unit_Code
from Inventory INV join
     items ITM 
     on INV.Item_ID = ITM.Item_ID join
     Units UN
     on ITM.Unit_ID = UN.Unit_ID
where INV.Type1 in ('GRN', 'DTN', 'DGRN', 'SR', 'RN', 'SVN') and
      INV.Stors_ID_1 = '6'
group by ITM.Item_Code, ITM.Item_Description, UN.Unit_Code;