获取列中的特定行值

Getting a specific row value in a column

我有当年和明年的数据 table。

示例 Table 数据:

Year,Period,prd_Desc,Amount
2014,11,    Humira,  120
2015,11,    humira,  140

关键列为年、期间、prd_Desc

如果明年和同一时期的数据存在,我需要在单独的列中显示该值。喜欢下面

Year,Period,prd_Desc,Amount_curnt_yr,Amount_next_yr
2014,11,    humira,  120,            140

我可以通过使用以下查询在相同 table 之间添加左外连接来实现此目的:

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

我试图在不使用左外连接的情况下在单一查询中获取它,但做不到。如果有人可以分享任何想法,那将有所帮助

您可以使用子查询来实现。

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

您可以使用 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>

假设您的真实 table 比您向我们展示的更多行(即更多年份和更多时期),这将是一个更通用的解决方案:

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;