我发现使用 CTE 有助于保持代码的组织和整洁。您需要重新格式化数字并将 Q4 与明年的 Q1 匹配的混乱部分可以在那里处理,并且您的主要查询很简单。
with NewSales (QtrDate, DisplayDate, Year, Quarter, Sales) as (
select
Year - 0.25 + (Quarter / 4.0) as QtrDate,
cast(Year as varchar(10)) + '-Q' + cast(Quarter as varchar(10)) as DisplayDate,
Year, Quarter, Sales
from
@sales
)
select
a.DisplayDate, a.Sales,
b.DisplayDate, b.Sales,
b.Sales - a.Sales as SalesIncrease,
(b.Sales / (a.Sales * 1.0)) - 1 as SalesPctIncrease
from
NewSales a left outer join
NewSales b on a.QtrDate + 0.25 = b.QtrDate
where
a.Sales is not null and b.Sales is not null
我在季度格式和百分比计算方面添加了一点天赋(最低限度:),您可以使用这些示例来帮助自定义输出。