我在 SQL Server 2014 中使用 Nortwind 数据库,我尝试进行查询以划分两个不同年份的订单结果,我在查询中想要的格式是
category |anio one | anio two
年份可能会有所不同,到目前为止我尝试的是
SELECT ca.CategoryName , YEAR(o.OrderDate), SUM(ot.UnitPrice*ot.Quantity) as total
FROM Orders o
INNER JOIN [Order Details] ot ON O.OrderID = ot.OrderID
INNER JOIN Products pro ON ot.ProductID = pro.ProductID
INNER JOIN Categories ca ON pro.CategoryID = ca.CategoryID
GROUP BY ca.CategoryName,YEAR(o.OrderDate)
ORDER BY ca.CategoryName;
这给了我不同年份每个类别的总数,1996-1997-1998
在列中YEAR(o.OrderDate)
我想得到例如
CategoryName | 1996 | 1997
Beverages |53879,20 | 110424,00
Condiments |19458,30 | 59679,00
....
使用“条件聚合”。
SELECT
ca.CategoryName
, SUM(case when year(o.OrderDate) = 1996 then ot.UnitPrice * ot.Quantity end) AS total_1996
, SUM(case when year(o.OrderDate) = 1997 then ot.UnitPrice * ot.Quantity end) AS total_1997
FROM Orders o
INNER JOIN [Order Details] ot ON o.OrderID = ot.OrderID
INNER JOIN Products pro ON ot.ProductID = pro.ProductID
INNER JOIN Categories ca ON pro.CategoryID = ca.CategoryID
where o.OrderDate >= '19960101' and o.OrderDate < '19980101'
GROUP BY
ca.CategoryName
ORDER BY
ca.CategoryName
基本上这意味着在聚合函数中使用 case 表达式。
我的情况你想知道为什么我没有在 where 子句中使用“之间:见坏习惯踢:错误处理日期/范围查询
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句