Colum X无效 - 它不是聚合函数或组子句

时间:2016-10-17 07:20:30

标签: sql sql-server group-by

试图找到答案,虽然有类似的问题,但我无法从他们的答案中找出答案。

SELECT a.custid as [custid],
       a.country as [country], 
       SUM(n.qty) over (partition by a.custid) as [total qty]
FROM sales.Customers a, sales.orderdetails n
where a.country = 'USA'
GROUP BY custid, country

我所要做的就是让所有美国客户都返回,每个客户的总数量。

它给了我错误。

  

Msg 8120,Level 16,State 1,Line 2
  专栏' sales.orderdetails.qty'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

1 个答案:

答案 0 :(得分:1)

修改您的脚本,如下所示。您必须通过提及适当的JOIN条件来建立两个表之间的关系。还要从聚合运算符中删除OVER()子句。

SELECT a.custid as [custid],a.country as [country], SUM(n.qty)  as [total qty]
FROM sales.Customers a 
  JOIN sales.orderdetails n
    ON a.custid =n.custid --give appropriate join condition
where a.country = 'USA'
GROUP BY a.custid, country