我通过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]
这是我的输出:
[您可以在代表销售列的[ventes]
列中看到,销售额不会根据ID号和名称相加,但是我确实在选择中使用了SUM()
功能。关于我的代码有什么问题的任何想法?
如评论中所述,
从group by子句中删除小计,聚合值不需要在group by子句中。
问题是您的group by
:
group by
SubTotal
。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