我需要显示单个员工在各个年份的交易次数(ID,2011、2012、2013、2014),并且应该在年份编号下查看每年的交易次数,但是现在我收到此表格:
如何更改它?
我认为我应该使用WHERE,但我不知道该怎么做
我当前的查询是:
SELECT oh.SalesPersonID AS perID,
YEAR(oh.OrderDate) AS [Year], COUNT(*)
FROM Sales.SalesOrderHeader oh
JOIN Person.Person per ON oh.SalesPersonID = per.BusinessEntityID
GROUP BY SalesPersonID, YEAR(OrderDate)
ORDER BY perID, [Year];
答案 0 :(得分:2)
只需使用条件聚合:
SELECT oh.SalesPersonID AS perID,
SUM(CASE WHEN YEAR(oh.OrderDate) = 2011 THEN 1 ELSE 0 END) as cnt_2011,
SUM(CASE WHEN YEAR(oh.OrderDate) = 2012 THEN 1 ELSE 0 END) as cnt_2012,
SUM(CASE WHEN YEAR(oh.OrderDate) = 2013 THEN 1 ELSE 0 END) as cnt_2013,
SUM(CASE WHEN YEAR(oh.OrderDate) = 2014 THEN 1 ELSE 0 END) as cnt_2014
FROM Sales.SalesOrderHeader oh JOIN
Person.Person per
ON oh.SalesPersonID = per.BusinessEntityID
GROUP BY SalesPersonID
ORDER BY perID;