我擁有三個不同[時期]的每個物體資料。它們是: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]
如何做到這一點?
行(結束)?但我認為它實際上不會做我想做的事。還有什么其他方法?
uj5u.com熱心網友回復:
當您說更改資料庫時,您的意思是為該物體創建一個新表還是只是希望有一個選擇查詢?您是否確實知道這些日期,或者您是否還需要按日期對它們進行排序并獲得第一、第二和第三?
如果您確實知道這些日期并且它們不會改變,那么您為什么要像這樣使用它們作為硬編碼
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/487006.html
上一篇:3個或更多表之間的一對多關系
下一篇:更新重復列的位置
