将计算列添加到SQL Server查询

时间:2019-03-07 17:15:46

标签: sql sql-server group-by

我试图通过将两个列相乘并按项目编号分组来在查询中添加一列(请参阅底部),但是出现以下错误:

  

选择列表中的“ IV00102.LOCNCODE”列无效,因为它既不包含在聚合函数中也不在GROUP BY子句中。

我确定这是一个简单的解决方案,已经在这里进行了介绍,但是我找不到我想要的东西。任何帮助将不胜感激

 SELECT        
     IV00101.ITEMNMBR, IV00102.LOCNCODE, IV00102.BINNMBR, IV00101.STNDCOST,
     IV00101.CURRCOST, IV00101.USCATVLS_3, IV00101.USCATVLS_4, 
     IV00101.USCATVLS_2, IV00102.QTYONHND, 
     SUM(IV00101.CURRCOST * IV00102.QTYONHND) AS 'CxQ'
 FROM            
     IV00101 
 INNER JOIN
     IV00102 ON IV00101.ITEMNMBR = IV00102.ITEMNMBR
 WHERE
     IV00102.LOCNCODE <> ''
 GROUP BY
     IV00101.ITEMNMBR; 

2 个答案:

答案 0 :(得分:0)

除聚合列外,选择列还需要添加GROUP BY

  SELECT        IV00101.ITEMNMBR, IV00102.LOCNCODE, IV00102.BINNMBR, IV00101.STNDCOST, IV00101.CURRCOST, IV00101.USCATVLS_3, IV00101.USCATVLS_4, IV00101.USCATVLS_2, 
                                 IV00102.QTYONHND,
     SUM(IV00101.CURRCOST*IV00102.QTYONHND) AS 'CxQ'
        FROM            IV00101 INNER JOIN
                                 IV00102 ON IV00101.ITEMNMBR = IV00102.ITEMNMBR
        WHERE               IV00102.LOCNCODE <> ''

        GROUP BY        IV00101.ITEMNMBR,IV00102.LOCNCODE, IV00102.BINNMBR, IV00101.STNDCOST, IV00101.CURRCOST, IV00101.USCATVLS_3, IV00101.USCATVLS_4, IV00101.USCATVLS_2, 
                                 IV00102.QTYONHND

答案 1 :(得分:0)

使用apply可能会更容易:

SELECT i1.*, i2.CxQ
FROM IV00101 i1 CROSS APPLY
     (SELECT i2.ITEMNMBR, SUM(i1.CURRCOST * i2.QTYONHND) as CxQ
      FROM IV00102 i2
      WHERE i2.ITEMNMBR = i1.ITEMNMBR AND
            i2.LOCNCODE <> ''
    ) i2;

还要注意,表别名使查询更易于编写和阅读。