【问题标题】:Multiple Column results from the same table同一个表的多列结果
【发布时间】:2015-03-09 22:05:27
【问题描述】:

今天的大脑都融化了,如果这太简单了太可笑了,请道歉。

基本上我有一个销售表,其中列出了销售价值、客户 ID、日历年和月份、分支机构 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  

但我需要将 2012 年的销售额与 2011 年的销售额放在一个单独的列中。在表中的年份列上,它们只是根据年份进行标记,因此下一列将仅提取 2012 年。

我希望这是有道理的

【问题讨论】:

  • @sgeddes,对不起,我错了,将删除。 (读 C 而不是 S……同时忙着做其他事情……)

标签: sql sql-server


【解决方案1】:

一种方法是在总和中使用 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  

【讨论】:

    【解决方案2】:

    您需要更改过滤器以包含 2012 年,并为您的总和使用 case 语句:

     select top 100 
        C.Name as [Customer],
        SUM (case when year '2011' then S.SalesTotal else 0 end) as [Sales for the Year 2011],
    SUM (case when year '2012' then S.SalesTotal else 0 end) as [Sales for the Year 2012]
        from Sales S
        Left Join CustomerName C with (NOLOCK) on C.CustomerID=S.CustomerID
        where S.Year in ('2011','2012' and S.BranchID=10
        Group By C.Name
    

    【讨论】:

    • 太棒了,谢谢@Andrew 和@D Stanley,我一看到这个案子就回复了——我不能投票,但我很害怕
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多