Sum Sql列加入

时间:2016-10-10 19:13:10

标签: sql-server sql-server-2005

我正在尝试这段代码:

Select  C.CustomerNum
      , C.Coupon
      , C.name
      , C.Surname
      , Sum(P.Points)
From    customers C
Join    Points P
        On P.CustomerNum = C.CustomerNum
Where   C.Coupon = 'xxx-xxx-xxx-x'; 

我收到错误:

  

Msg 8118,Level 16,State 1,Line 1 Column'C.CustomerNum'无效   在选择列表中,因为它不包含在聚合中   函数,没有GROUP BY子句。

6 个答案:

答案 0 :(得分:1)

您也可以使用。

endpoint_url:String = "http://cors.io/?u=" + 
   encodeURIComponent("http://wingerweb.azurewebsites.net/WingerApp/rest/menuitems/1");

避免必须将SELECT C.CustomerNum, C.Coupon, C.name, C.Surname, P.Points FROM customers C INNER JOIN (SELECT Sum(Points) AS Points, CustomerNum FROM Points GROUP BY CustomerNum) P ON P.CustomerNum = C.CustomerNum WHERE C.Coupon = 'xxx-xxx-xxx-x'; 中的所有选定列添加到customers列表。

答案 1 :(得分:0)

错误消息将其解决。您可以这样做(仅选择没有分组的聚合):

Select  Sum(P.Points)
From    customers C
Join    Points P
        On P.CustomerNum = C.CustomerNum
Where   C.Coupon = 'xxx-xxx-xxx-x'; 

或者(如果列在分组中,则选择聚合和列):

Select  C.CustomerNum
      , Sum(P.Points)
From    customers C
Join    Points P
        On P.CustomerNum = C.CustomerNum
Where   C.Coupon = 'xxx-xxx-xxx-x'
group by c.customernum

但不是这个(选择没有分组的聚合和列):

Select  C.CustomerNum
      , C.Coupon
      , C.name
      , C.Surname
      , Sum(P.Points)
From    customers C
Join    Points P
        On P.CustomerNum = C.CustomerNum
Where   C.Coupon = 'xxx-xxx-xxx-x';  

答案 2 :(得分:0)

使用聚合功能时,您需要使用GROUP BY。试试这个:

Select  C.CustomerNum
      , C.Coupon
      , C.name
      , C.Surname
      , Sum(P.Points)
From    customers C
Join    Points P
        On P.CustomerNum = C.CustomerNum
Where   C.Coupon = 'xxx-xxx-xxx-x'; 
GROUP BY C.CustomerNum
      , C.Coupon
      , C.name
      , C.Surname

现在,您可能希望缩小实际选择的范围。例如,最好只按C.Surname或C.CustomerNum分组

答案 3 :(得分:0)

如果有聚合(SUM,COUNT,AVERAGE),则需要按返回的所有非聚合列对查询进行分组。为此:

Select  C.CustomerNum
      , C.Coupon
      , C.name
      , C.Surname
      , Sum(P.Points)
From    customers C
Join    Points P
        On P.CustomerNum = C.CustomerNum
Where   C.Coupon = 'xxx-xxx-xxx-x'; 
Group By C.CustomerNum
      , C.Coupon
      , C.name
      , C.Surname

答案 4 :(得分:0)

您不能在不使用SUM()的情况下将聚合函数(在本例中为GROUP BY)与其他非聚合列一起使用。但是,您可以通过将其设置为窗口SUM()函数来实现:

Select  C.CustomerNum
      , C.Coupon
      , C.name
      , C.Surname
      , Sum(P.Points) Over (Partition By C.CustomerNum)
From    customers C
Join    Points P
        On P.CustomerNum = C.CustomerNum
Where   C.Coupon = 'xxx-xxx-xxx-x'; 

但也许您想要按CustomerNumCouponNameSurname对它们进行分组,在这种情况下,您只需要添加{ {1}}:

GROUP BY

答案 5 :(得分:0)

@ User6927546

如果你使用的是mysql而不是它应该工作,因为我已经交叉检查了它并且工作正常。

从员工中选择employee.empId,employee.Name,sum(w.workcode) 在employee.workId = w.id上加入工作w,其中employee.Name =' anoop'

我得到的结果集如下: empId名称总和(w.workcode) 1 Anoop 200