使用SUM函数基于ID和名称将我的销售额加在一起

问题描述 投票:0回答:2

我通过SSMS创建了一个请求:

SELECT 
    CONCAT(LastName,' ', FirstName) AS [Nom du vendeur], 
    SalesPersonID, 
    DATEPART(YYYY, [OrderDate]) AS [Annee], 
    FORMAT(SUM(soh.SubTotal), '#,#00.') AS [Ventes]
FROM 
    Sales.SalesOrderHeader AS soh 
INNER JOIN 
    Person.Person AS pp ON soh.SalesPersonID = pp.BusinessEntityID
WHERE 
    pp.PersonType = 'SP' 
    AND soh.OnlineOrderFlag = '0' 
    AND OrderDate NOT BETWEEN CONVERT(DATETIME, '01/01/2011', 101) AND CONVERT(DATETIME, '12/31/2011', 101) 
GROUP BY 
    SubTotal, OrderDate, SalesPersonID,LastName, FirstName
ORDER BY  
    [Annee], [Nom du vendeur]

这是我的输出:

enter image description here

[您可以在代表销售列的[ventes]列中看到,销售额不会根据ID号和名称相加,但是我确实在选择中使用了SUM()功能。关于我的代码有什么问题的任何想法?

sql-server ssms
2个回答
0
投票

如评论中所述,

从group by子句中删除小计,聚合值不需要在group by子句中。


0
投票

问题是您的group by

  1. [求和该列时不想group by SubTotal
  2. [并且当您尝试对一年的总数求和时,您不想group by OrderDate。而是您想group by与您选择的计算相同,例如DATEPART(YYYY, [OrderDate])

所以您更正后的group by是:

GROUP BY DATEPART(YYYY, [OrderDate]), SalesPersonID, LastName, FirstName

FYI:如果您以类似于Minimal Reproducible Example的格式发布问题,则可以更轻松,更容易为人们提供帮助。

declare @SalesOrderHeader table (id int, SalesPersonID int, OrderDate datetime, SubTotal money, OnlineOrderFlag varchar(1))
declare @Person table (id int, FirstName varchar(64), LastName varchar(64), BusinessEntityID int, PersonType varchar(2))

insert into @Person (id, BusinessEntityID, FirstName, LastName)
  select 1, 1, 'Amy', 'Alberts' union all
  select 2, 2, 'Pamela', 'Ansman-Wolfe'

insert into @SalesOrderHeader (SalesPersonID, OrderDate, SubTotal)
  select 1, '5 nov 2019', 12.34 union all
  select 1, '6 nov 2019', 34.56 union all
  select 2, '7 nov 2019', 78.90 union all
  select 2, '8 nov 2019', 43.21

SELECT 
  CONCAT(LastName,' ', FirstName) AS [Nom du vendeur] 
  , SalesPersonID 
  , DATEPART(YYYY, [OrderDate]) AS [Annee] 
  , FORMAT(SUM(soh.SubTotal), '#,#00.') AS [Ventes]
FROM @SalesOrderHeader AS soh 
INNER JOIN @Person AS pp ON soh.SalesPersonID = pp.BusinessEntityID
--WHERE 
--    pp.PersonType = 'SP' 
--    AND soh.OnlineOrderFlag = '0' 
--    AND OrderDate NOT BETWEEN CONVERT(DATETIME, '01/01/2011', 101) AND CONVERT(DATETIME, '12/31/2011', 101) 
-- GROUP BY SubTotal, OrderDate, SalesPersonID,LastName, FirstName
GROUP BY DATEPART(YYYY, [OrderDate]), SalesPersonID, LastName, FirstName
ORDER BY [Annee], [Nom du vendeur]

返回:

Nom du vendeur      | SalesPersonID | Annee | Ventes
----------------------------------------------------
Alberts Amy         | 1             | 2019  | 47
Ansman-Wolfe Pamela | 2             | 2019  | 122
© www.soinside.com 2019 - 2024. All rights reserved.