SELECT year(soh.OrderDate) 'year',sum(soh.TotalDue) 'Total',st.[Group] TerritoryGroup
FROM Sales.SalesOrderHeader soh
LEFT OUTER JOIN Sales.SalesTerritory st
ON soh.TerritoryID=st.TerritoryID
GROUP BY year(soh.OrderDate),(soh.TotalDue),[Group]
ORDER BY year(soh.OrderDate),(soh.TotalDue)
这就是我想出来的,但这些年份分散而不是每个地区总计一年。 (我想打印每个地区每年的总计) 是否有一种简洁的方法来制作这个选择语句?
答案 0 :(得分:2)
如果您想要每年一行,那么只在group by
中包含该行:
SELECT year(soh.OrderDate) as year, sum(soh.TotalDue) as Total
FROM Sales.SalesOrderHeader soh LEFT OUTER JOIN
Sales.SalesTerritory st
ON soh.TerritoryID = st.TerritoryID
GROUP BY year(soh.OrderDate)
ORDER BY year(soh.OrderDate);
如果您想要每年一行和地区组,则只包括这两列:
SELECT year(soh.OrderDate) as year, sum(soh.TotalDue) as Total, st.[Group] as TerritoryGroup
FROM Sales.SalesOrderHeader soh LEFT OUTER JOIN
Sales.SalesTerritory st
ON soh.TerritoryID = st.TerritoryID
GROUP BY year(soh.OrderDate), [Group]
ORDER BY year(soh.OrderDate), Total;
一些注意事项:
TerritoryGroup
。soh.TotalDue
中加入group by
。您正在对该列求和,而不是按其汇总。order by
子句不应包含soh.TotalDue
;它应该是聚合值(Total
)而不是。答案 1 :(得分:0)
在GROUP BY中,您说您希望每个年份,totaldue和地区组合使用一行。
让我们说你有这些记录:
orderdate totaldue territorygroup 2014-01-01 100 1 2014-01-15 200 1 2014-01-21 100 1 2013-03-03 100 1 2014-04-04 100 2
然后你得到这些结果记录:
year totaldue territorygroup 2014 100 1 2014 200 1 2013 100 1 2014 100 2
(BTW:sum(soh.TotalDue)= soh.TotalDue,因为你按TotalDue分组。)
因此,您的解决方案是实际说明您希望在结果记录中看到的内容。每______一个记录。因此,您将获得GROUP BY子句和您想要的结果。