【问题标题】:SQL Server - Compare months of current year with months of the previous yearSQL Server - 将当年的月份与上一年的月份进行比较
【发布时间】:2020-03-24 19:45:17
【问题描述】:

我想将当年(2020 年)的月份与上一年(2019 年)的月份进行比较。我必须以百分比计算增量,但这是我可以自己解决的任务。

我尝试将表与自身连接起来。我需要的列是Month_YearRevenue 1Revenue 2

我的问题是收入不正确。

这是我目前的查询:

select 
    a.Month_Year 'Month_Year1'
    ,b.Month_Year 'Month_Year2'
    ,sum(a.[Revenue1]) 'Revenue1'
    ,sum(a.[Revenue2]) 'Revenue2'
    ,sum(b.[Revenue1_last_year]) 'Revenue1_last_year'
    ,sum(b.[Revenue2_last_year]) 'Revenue2_last_year'
from 
    #a
join
    #b on a.Month = b.Month and a.Year= b.Year -1
group by
    a.Month_Year, b.Month_Year
order by
    [Month_Year1] asc, [Month_Year2] asc

在我的输出中,月份是正确的,但我的收入似乎只是随机数相加。

【问题讨论】:

  • 不可能回答,除非您提供一些样本数据来显示/说明“加起来随机数”声明......
  • 您说您正在将表连接到自身,但join 有两个不同的表。

标签: sql sql-server


【解决方案1】:

只选择有问题的年份,然后按月份分组并每年有条件地总结:

select 
  month,
  sum(case when year = year(getdate()) then revenue1 end) as r1_this_year,
  sum(case when year = year(getdate()) then revenue2 end) as r2_this_year,
  sum(case when year < year(getdate()) then revenue1 end) as r1_last_year,
  sum(case when year < year(getdate()) then revenue2 end) as r2_last_year
from mytable
where year in (year(getdate()), year(getdate()) - 1)
group by month
order by month;

如果您希望仅显示当前月份(即现在显示 1 月到 3 月,而不是 4 月到 12 月),请将 and month &lt;= month(getdate()) 添加到 where 子句。

至于您自己的查询:您将每个 #a 行与每个月和年匹配的每个 #b 行连接起来。因此,假设 2019 年 1 月的 10 #a 行和 2020 年 1 月的 5 #b 行,您会产生 10 x 5 = 50 行。然后你聚合和总结,得到实际值的倍数(因为 1+2 与 1+1+1+2+2+2 不同:-)。

【讨论】:

    【解决方案2】:

    如果数据在一个表中,并且每个月都有表,则可以使用lag()

    select a.Month_Year as month_year
           sum(a.Revenue1)  as Revenue1,
           sum(a.Revenue2) as Revenue2,
           lag(sum(a.Revenue1), 12) over (order by a.Month_Year) as Revenue1_ly,
           lag(sum(a.Revenue2)) over (order by a.Month_Year) as Revenue2_ly
    from #a
    group by a.Month_Year;
    

    【讨论】:

    • 谢谢!这可能在第一次尝试时没有解决问题,但让我有了更好的理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多