【问题标题】:sql sum join where group bysql sum join where group by
【发布时间】:2016-08-11 09:53:55
【问题描述】:

我的 SQL 代码

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.

解释我解决这个问题。

谢谢

【问题讨论】:

  • 首先,你应该描述你想要达到的目标。
  • 其次,您应该了解GROUP BY 的工作原理。在发布问题之前,您可以找到很多结果。

标签: sql sql-server group-by


【解决方案1】:
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,

试试上面的查询。

【讨论】:

  • 分组依据无效。 (但是可以在旧的 MySQL 版本上执行,返回任意结果。)'
【解决方案2】:

改用相关子查询:

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 列表中的每个列引用必须要么标识一个分组列,要么是一个集合函数的参数。)

【讨论】:

    【解决方案3】:

    您收到此错误是因为 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; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多