将具有动态日期的行转换为列
Posted
技术标签:
【中文标题】将具有动态日期的行转换为列【英文标题】:Transforming rows having dynamic dates into columns 【发布时间】:2015-12-20 15:24:11 【问题描述】:需要转换这个:
DATE VALUE
18-DEC-15 2877544
17-DEC-15 2974276
16-DEC-15 4862020
进入
18-DEC-15 17-DEC-15 16-DEC-15
2877544 2974276 4862020
日期每天都会更新,我只需要选择最近的 3 个日期并将它们转换为具有以下相应值的列。 我尝试使用 Pivots,但我能够动态创建列标题。
【问题讨论】:
【参考方案1】:试试这个
WITH pivot_data AS (
select date, value from table)
SELECT *
FROM pivot_data
PIVOT (
max(value) --<-- pivot_clause
FOR table --<-- pivot_for_clause
);
【讨论】:
【参考方案2】:SQL 查询具有明确定义的列名,因此对于可变列名,您需要动态 SQL。但是,你可以用固定的名字做你想做的事:
select max(case when seqnum = 1 then value end) as MostRecentDay,
max(case when seqnum = 2 then value end) as SecondMostRecentDay,
max(case when seqnum = 3 then value end) as ThirdMostRecentDay
from (select t.*, dense_rank() over (order by date desc) as seqnum
from t
) t;
您甚至可以添加三列来指定日期值:
select max(case when seqnum = 1 then value end) as MostRecentDay,
max(case when seqnum = 2 then value end) as SecondMostRecentDay,
max(case when seqnum = 3 then value end) as ThirdMostRecentDay,
max(case when seqnum = 1 then date end) as MostRecentDate,
max(case when seqnum = 2 then date end) as SecondMostRecentDate,
max(case when seqnum = 3 then date end) as ThirdMostRecentDate
from (select t.*, dense_rank() over (order by date desc) as seqnum
from t
) t;
【讨论】:
【参考方案3】:使用Conditional Aggregate
旋转数据
select MAX(case when "DATE" = '18-DEC-15' then VALUE END) as '18-DEC-15',
MAX(case when "DATE" = '17-DEC-15' then VALUE END) as '17-DEC-15',
MAX(case when "DATE" = '16-DEC-15' then VALUE END) as '16-DEC-15'
from yourtable
注意:由于日期未知,需要使用EXECUTE IMMEDIATE
【讨论】:
您能否详细说明如何在此处使用 EXECUTE IMMEDIATE 功能?同样在尝试上述查询时,我收到一条错误消息,提示“未在预期的位置找到 FROM 关键字”。以上是关于将具有动态日期的行转换为列的主要内容,如果未能解决你的问题,请参考以下文章