【发布时间】:2021-02-04 14:58:08
【问题描述】:
我希望使用 SQL (Oracle) 通过评估特定 ID 上的日期来将数据从行中提取到列中。以下是我的数据目前的样子:
| ID | Date | Price |
-----------------------------------
| 1234 |10/1/2020 | $12.96 |
| 1234 |10/1/2021 | $11.32 |
| 1234 |10/1/2022 | $10.01 |
| 5678 | 6/1/2020 | $59.96 |
期望的输出:
| ID |Yr1 Price |Yr2 Price |Yr3 Price |
---------------------------------------------
| 1234 | $12.96 | $11.32 | $10.01 |
| 5678 | $59.96 | | |
我尝试了几种不同的方法,但都没有成功。我相信 DENSE_RANK() 函数可能是最好的,但会给出一个错误,即它是一个窗口函数并且不允许在那里。所以我遇到了障碍,不确定如何进行。我当前的 SQL 代码是:
select id,
(select price from price_tbl where DENSE_RANK() Over (partition by id) = 1) as yr_1,
(select price from price_tbl where DENSE_RANK() Over (partition by id) = 2) as yr_2,
(select price from price_tbl where DENSE_RANK() Over (partition by id) = 3) as yr_3
from master_tbl
非常感谢任何帮助!
【问题讨论】:
标签: sql oracle oracle11g pivot oracle-sqldeveloper