重新对齐数据集,使不同的周期出现在同一行



我有三个不同时期的每个实体数据。它们是:2022-03-31、2021-09-30和2021-03-31

我想改变数据集,并有

2022-03-31  AS [curr_period], 2021-09-30 AS [prev_period] and 2021-03-31 AS [prev2_period].

这可以很容易地通过case语句完成。

问题是,我想让数据对齐,这样[entity]出现,然后在同一行[curr_period], [prev_period], [prev2_period]

如何做到这一点?

行(over) ?但我不认为它会做我想做的事。还有其他的方法吗?

当你说alter database时,你的意思是为这个实体创建一个新表,还是你只是想要一个选择查询?你确定知道这些日期吗?还是你还需要按日期排序,得到第一,第二和第三?

如果你确实知道这些日期并且它们不会改变,那么为什么要像这样使用硬编码呢

SELECT entity, '2022-03-31'  AS [curr_period], '2021-09-30' AS [prev_period], '2021-03-31' AS [prev2_period]
FROM entities
Group by entity

我可能错过了一些东西,但没有示例数据很难确定。

这对我来说没有硬编码的日期。

SELECT e1.entity, 
e1.date AS [curr_period], 
e2.date AS [prev_period], 
e3.date AS [prev2_period]
FROM entities e1
join entities e2 on e2.entity = e1.entity and e1.date > e2.date
join entities e3 on e3.entity = e1.entity and e2.date > e3.date
order by e1.entity, e1.date desc

最新更新