我正在使用Northwind database在T-SQL中进行一些练习,我应该得到TotalSold / Year SUM(OrderDetails.UnitPrice * OrderDetails.Quantity) 对于每家公司,到目前为止我所做的是获得每家公司的TotalSold或获得每笔订单的销售,但不知道如何获得TotalSold / Year。
USE Northwind
GO
SELECT C.CompanyName, O.OrderDate,
SUM(OD.UnitPrice * OD.Quantity) AS TotalSold
FROM Customers AS C
INNER JOIN Orders AS O
ON C.CustomerID = O.CustomerID
INNER JOIN [Order Details] AS OD
ON O.OrderID = OD.OrderID
GROUP BY O.OrderDate, C.CompanyName
GO
结果是
CompanyName OrderDate TotalSold
Alfreds Futterkiste 1997-08-25 00:00:00.000 1086.00
Alfreds Futterkiste 1997-10-03 00:00:00.000 878.00
Alfreds Futterkiste 1997-10-13 00:00:00.000 330.00
Alfreds Futterkiste 1998-01-15 00:00:00.000 851.00
Alfreds Futterkiste 1998-03-16 00:00:00.000 491.20
Alfreds Futterkiste 1998-04-09 00:00:00.000 960.00
...
解决问题的任何想法或线索?
答案 0 :(得分:2)
只需使用函数YEAR
而不是订单日期本身。
USE Northwind
GO
SELECT C.CompanyName, YEAR(O.OrderDate) AS [Year],
SUM(OD.UnitPrice * OD.Quantity) AS TotalSold
FROM Customers AS C
INNER JOIN Orders AS O
ON C.CustomerID = O.CustomerID
INNER JOIN [Order Details] AS OD
ON O.OrderID = OD.OrderID
GROUP BY YEAR(O.OrderDate), C.CompanyName
GO