我在当前年份和明年都有数据表。
样本表数据:
Year,Period,prd_Desc,Amount
2014,11, Humira, 120
2015,11, humira, 140
Key Coulmn是Year,Period,prd_Desc
如果明年和同一时期的数据存在,我需要在单独的列中输入该值。如下所示
Year,Period,prd_Desc,Amount_curnt_yr,Amount_next_yr
2014,11, humira, 120, 140
我可以通过使用以下查询在同一个表之间执行左外连接来实现此目的:
select a.Year,a.Period,a.prd_Desc,a.Amount as Amount_curnt_yr,b.Amount as Amount_next_yr
from (select Year,Period,prd_Desc,Amount
from tableA) a
left outer join (select Year,Period,prd_Desc,Amount from tableA) b on
b.year=a.year+1 and a.Period=b.period and a.prd_Desc=b.prd_Desc
我试图在不使用左外连接的情况下在simngle查询中获取它,但不能。如果有人可以分享任何想法,那将有所帮助
答案 0 :(得分:2)
假设您的真实表格中有更多行(即更多年份和更多期间),那么这将是一个更通用的解决方案:
WITH t AS
(SELECT YEAR,Period,prd_Desc,Amount,
LEAD(amount, 1) OVER (PARTITION BY prd_Desc, period ORDER BY YEAR) AS amount_next_year
FROM a_table)
SELECT *
FROM t
WHERE amount_next_year IS NOT NULL;
如果列YEAR
中的值不连续,您可以这样做:
WITH t AS
(SELECT YEAR,Period,prd_Desc,Amount,
LAST_VALUE(amount) OVER
(PARTITION BY period, prd_Desc ORDER BY YEAR
RANGE BETWEEN 1 FOLLOWING AND 1 FOLLOWING) AS amount_next_year
FROM A_TABLE)
SELECT *
FROM t
WHERE amount_next_year IS NOT NULL;
答案 1 :(得分:1)
您可以使用子查询来实现此目的。
select t.*, (select amount from sampleTableData where year = t.year+1 and period = t.period and prd_desc = t.prd_desc) Amount_next_yr from sampleTableData t
答案 2 :(得分:1)
您可以使用 SUBQUERY 执行此操作。使用 WITH 子句,可以使其看起来很精细。
因此,每年可以在每个子查询中处理句柄 -
SQL> WITH data AS
2 (SELECT '2014' yr, 11 period, 'Humira' prd_desc, 120 amount FROM dual
3 UNION ALL
4 SELECT '2015', 11, 'humira', 140 amount FROM dual
5 ),
6 cur_yr AS
7 (SELECT *
8 FROM
9 (SELECT t.*, Row_number() over( ORDER BY yr) rn FROM data t
10 )
11 WHERE rn = 1
12 ),
13 next_yr AS
14 (SELECT *
15 FROM
16 (SELECT t.*, Row_number() over( ORDER BY yr) rn FROM data t
17 )
18 WHERE rn > 1
19 )
20 SELECT c.yr,
21 c.period,
22 c.prd_desc,
23 c.amount Amount_curnt_yr,
24 n.amount Amount_next_yr
25 FROM cur_yr c,
26 next_yr n
27 WHERE c.period = n.period
28 /
YR PERIOD PRD_DE AMOUNT_CURNT_YR AMOUNT_NEXT_YR
---- ---------- ------ --------------- --------------
2014 11 Humira 120 140
SQL>