Business Unit | Date | Sales
North America | 5/1/17 | 5,000
North America | 4/1/17 | 4,000
North America | 3/1/17 | 3,000
North America | 2/1/17 | 2,000
North America | 1/1/17 | 1,000
............
North America | 5/1/16 | 4,000
North America | 4/1/16 | 3,000
North America | 3/1/16 | 2,000
North America | 2/1/16 | 2,000
North America | 1/1/16 | 500
............
Asia | 5/1/17 | 5,000
Asia | 4/1/17 | 2,000
Asia | 3/1/17 | 1,000
Asia | 2/1/17 | 3,000
Asia | 1/1/17 | 1,500
............
Asia | 5/1/16 | 4,000
Asia | 4/1/16 | 2,000
Asia | 3/1/16 | 500
Asia | 2/1/16 | 1,500
Asia | 1/1/16 | 1,000
每个月包含所有38天,30天或31天 - 但为了便于举例,我只是展示了上述数据中的第一天。
以下是我希望实现的输出示例:
Business Unit | Date | Sales | Year over Year Change |
North America | 5/1/17 | 5,000 | 25% |
North America | 4/1/17 | 4,000 | 33% |
North America | 3/1/17 | 3,000 | 50% |
North America | 2/1/17 | 2,000 | 0% |
North America | 1/1/17 | 1,000 | 50% |
............
North America | 5/1/16 | 4,000 | xx% |
North America | 4/1/16 | 3,000 | xx% |
North America | 3/1/16 | 2,000 | xx% |
North America | 2/1/16 | 2,000 | xx% |
North America | 1/1/16 | 500 | xx% |
............
Asia | 5/1/17 | 5,000 | 25% |
Asia | 4/1/17 | 2,000 | 0% |
Asia | 3/1/17 | 1,000 | 100% |
Asia | 2/1/17 | 3,000 | 100% |
Asia | 1/1/17 | 1,500 | 50% |
............
Asia | 5/1/16 | 4,000 | xx% |
Asia | 4/1/16 | 2,000 | xx% |
Asia | 3/1/16 | 500 | xx% |
Asia | 2/1/16 | 1,500 | xx% |
Asia | 1/1/16 | 1,000 | xx% |
如上所述,这些数据是每日发布的,可以追溯到多年。非常感谢您提供任何帮助!
答案 0 :(得分:1)
您可以查询如下:
Select coalesce(lastyear.[Business Unit], currentyear.[Business Unit]) as BusinessUnit, currentyear.[date], lastyear.[date] as [LastYear Date],
Format((1-(lastyear.Sales*1.0)/currentyear.Sales), 'p')
from #yoydata lastyear
left join #yoydata currentyear
on lastyear.[date] = dateadd(yy,-1,currentyear.[date])
and lastyear.[Business Unit] = currentyear.[Business Unit]
答案 1 :(得分:1)
SELECT
COALESCE(lastyear.[bu], currentyear.[bu]) AS BusinessUnit
, currentyear.[dt]
, lastyear.[dt] AS [LastYear Date]
, Format((1-(lastyear.Sales*1.0)/currentyear.Sales), 'p')
FROM
#yoydata lastyear
LEFT JOIN #yoydata currentyear ON lastyear.[dt] = dateadd(yy,-1,currentyear.[dt])
AND lastyear.bu = currentyear.bu