今天的大脑全都融化了,如果道歉这么简单,就道歉,可笑。
基本上,我有一个Sales表,其中列出了销售值,客户ID,日历年和月份的Branch ID等。
我需要一个查询,列出2011年及其2012年销售的前100名销售
我有2011年-轻松(见下文)
select top 100
C.Name as [Customer],
SUM (S.SalesTotal) as [Sales for the Year 2011]
from
Sales S
Left Join
CustomerName C with (NOLOCK) on C.CustomerID = S.CustomerID
where
S.Year = '2011' and S.BranchID = 10
Group By
C.Name
但是,我需要在2011年销售额的旁边单独列出2012年的销售额。在表的year列中,它们仅根据年份进行了标记,因此它将仅提取2012年作为下一列。
我希望这是有道理的
一种方法是在您的总和中使用CASE语句:
select top 100
C.Name as [Customer],
SUM (CASE WHEN S.Year='2011' THEN S.SalesTotal ELSE 0) as [Sales for the Year 2011]
SUM (CASE WHEN S.Year='2012' THEN S.SalesTotal ELSE 0) as [Sales for the Year 2012]
SUM (CASE WHEN S.Year='2013' THEN S.SalesTotal ELSE 0) as [Sales for the Year 2013]
from Sales S
Left Join CustomerName C with (NOLOCK) on C.CustomerID=S.CustomerID
where S.BranchID=10
Group By C.Name
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句