对于以下情况,如何在 oracle sql 中执行类似 unpivot 的操作?
How to do something like unpivot like in oracle sql for the following scenario?
这是 table 语句,我想将数据转换成一些不可逆的东西,比如只使用 sql。
create table galy(
pro_Date date,
profit number
);
insert into galy values(sysdate-1,30);
insert into galy values(sysdate,20);
insert into galy values(sysdate+1,40);
insert into galy values(sysdate+2,50);
insert into galy values(sysdate+3,70);
commit;
单个查询中需要输出(不应考虑周六和周日的日期)
Date d-1 d d+1
01-02-2018(sysdate) 30 20 40
....
....
不需要 pivot/unpivot 就可以让数据以您想要的格式显示。只要每天只有1个PRO_DATE
,就可以使用LEAD
和LAG
解析函数
查询
SELECT pro_date,
LAG (profit) OVER (ORDER BY pro_date) AS prior_day_profit,
profit AS current_day_profit,
LEAD (profit) OVER (ORDER BY pro_date) AS next_day_profit
FROM galy;
结果
PRO_DATE PRIOR_DAY_PROFIT CURRENT_DAY_PROFIT NEXT_DAY_PROFIT
____________ ___________________ _____________________ __________________
04-OCT-20 30 20
05-OCT-20 30 20 40
06-OCT-20 20 40 50
07-OCT-20 40 50 70
08-OCT-20 50 70
更新
要排除周末,您只需在查询中添加一个 where 子句
SELECT pro_date,
LAG (profit) OVER (ORDER BY pro_date) AS prior_day_profit,
profit AS current_day_profit,
LEAD (profit) OVER (ORDER BY pro_date) AS next_day_profit
FROM galy
WHERE TO_CHAR (pro_date, 'DY') NOT IN ('SAT', 'SUN');
这是 table 语句,我想将数据转换成一些不可逆的东西,比如只使用 sql。
create table galy(
pro_Date date,
profit number
);
insert into galy values(sysdate-1,30);
insert into galy values(sysdate,20);
insert into galy values(sysdate+1,40);
insert into galy values(sysdate+2,50);
insert into galy values(sysdate+3,70);
commit;
单个查询中需要输出(不应考虑周六和周日的日期)
Date d-1 d d+1
01-02-2018(sysdate) 30 20 40
....
....
不需要 pivot/unpivot 就可以让数据以您想要的格式显示。只要每天只有1个PRO_DATE
,就可以使用LEAD
和LAG
解析函数
查询
SELECT pro_date,
LAG (profit) OVER (ORDER BY pro_date) AS prior_day_profit,
profit AS current_day_profit,
LEAD (profit) OVER (ORDER BY pro_date) AS next_day_profit
FROM galy;
结果
PRO_DATE PRIOR_DAY_PROFIT CURRENT_DAY_PROFIT NEXT_DAY_PROFIT
____________ ___________________ _____________________ __________________
04-OCT-20 30 20
05-OCT-20 30 20 40
06-OCT-20 20 40 50
07-OCT-20 40 50 70
08-OCT-20 50 70
更新
要排除周末,您只需在查询中添加一个 where 子句
SELECT pro_date,
LAG (profit) OVER (ORDER BY pro_date) AS prior_day_profit,
profit AS current_day_profit,
LEAD (profit) OVER (ORDER BY pro_date) AS next_day_profit
FROM galy
WHERE TO_CHAR (pro_date, 'DY') NOT IN ('SAT', 'SUN');