Group By Clause显示聚合方法错误

时间:2013-12-09 14:12:40

标签: sql-server tsql group-by aggregate-functions

我尝试使用此SQL查询但显示聚合方法错误请解决此问题。我在存储过程中使用此查询。谢谢你的推荐

BEGIN
    SELECT CustomerName + ' - ' + StoreName                                                                     AS 'CustomerName',
           CreateDate                                                                                           AS 'OrderDate',
           DeliveryDate,
           RegDelDate,
           CONVERT(VARCHAR(10), WeekStart, 101) + ' - ' + CONVERT(VARCHAR(10), DATEADD(DAY, 6, WeekStart), 101) AS 'WeekName',
           TotalCost,
           TotalCount,
           CONVERT(VARCHAR(10), O.OrderId)                                                                      AS 'OrderId',
           Comment,
           CASE
             WHEN TicketNo IS NULL
                   OR TicketNo = '' THEN 'DDM'
             ELSE TicketNo
           END                                                                                                  AS 'TicketNo',
           [Status]
    FROM   [Order] O
           INNER JOIN Store S
             ON S.StoreID = O.StoreId
           INNER JOIN Customer C2
             ON C2.CustomerID = O.CustId
           INNER JOIN (SELECT SUM(OrderQty)            AS TotalCount,
                              SUM(OrderQty * CaseCost) AS TotalCost,
                              OrderId
                       FROM   OrderItem OI
                       GROUP  BY OrderId) OI
             ON OI.OrderId = O.OrderId
           INNER JOIN AllWeeks
             ON WeekNo = [Week]
                AND YearNo = [Year],
           OrderItem OI1
    GROUP  BY O.CreateDate
END 

1 个答案:

答案 0 :(得分:0)

如果您正在使用聚合,则列需要位于group by或聚合

group by没有意义,因为您将拥有多个客户,而客户并没有真正汇总。

我猜你想要这样的东西

  SELECT O.CustomerName, O.CreateDate, sum(TotalCost) as 'SumCost', sum(TotalCount)  as 'SumCount'                             
    FROM   [Order] O
           INNER JOIN Store S
             ON S.StoreID = O.StoreId
           INNER JOIN Customer C2
             ON C2.CustomerID = O.CustId
           INNER JOIN (SELECT SUM(OrderQty)            AS TotalCount,
                              SUM(OrderQty * CaseCost) AS TotalCost,
                              OrderId
                       FROM   OrderItem OI
                       GROUP  BY OrderId) OI
             ON OI.OrderId = O.OrderId
           INNER JOIN AllWeeks
             ON WeekNo = [Week]
                AND YearNo = [Year],
           OrderItem OI1
    GROUP  BY O.CustomerName, O.CreateDate