【问题标题】:Oracle query stumped - derived tableOracle 查询难倒派生表
【发布时间】:2015-10-16 20:45:42
【问题描述】:

我已经很久没有做过比最基本的 sql 查询更多的事情了。但是我今天遇到了这个并且花了几个小时在它上面并且卡住了我的派生表尝试(这是针对 Oracle 数据库的)。寻找一些提示。谢谢。

TABLE: dtree
DataID  Name
-------------
10001   A.doc
10002   B.doc
10003   C.doc
10004   D.doc

TABLE: collections
CollectionID   DataID
---------------------
201     10001
201     10002   
202     10003
203     10004

TABLE: rimsNodeClassification
DataID  RimsSubject  RimsRSI  Status
---------------------------------------
10001   blah         IS-03  Active
10002   blah         LE-01  Active
10003   blah         AD-02  Active
10004   blah         AD-03  Active

TABLE:  rsiEventSched 
RimsRSI  RetStage  DateToUse  RetYears
--------------------------------------
IS-03   SEM-PHYS   95       1
IS-03   ACT       NULL      2
LE-01   SEM-PHYS   94       1
LE-01   INA-PHYS   95       2
LE-01   ACT       NULL      NULL
LE-01   OFC       NULL      NULL
LE-02   SEM-PHYS   94       2

尝试查询 CollectionID=201

INTENDED RESULT:
DataID  Name    RimsRSI  Status  SEMPHYS_DateToUse  INAPHYS_DateToUse      SEMPHYS_RetYears  INAPHYS_RetYears
-------------------------------------------------------------------------------------------------------
10001   A.doc   IS-03    Active   95               null                     1               null
10002   B.doc   Le-01    Active   94               95                   1                 2

【问题讨论】:

  • 您能否更清楚您的问题到底是什么?

标签: sql oracle derived-table


【解决方案1】:

您不需要派生表,只需连接表(最后一个使用左连接),然后应用 MAX(CASE) 聚合:

select c.DataID, t.Name, rnc.RimsRSI, rnc.Status,
   max(case when res.RetStage = 'SEM-PHYS' then res.DateToUse end) SEMPHYS_DateToUse,
   max(case when res.RetStage = 'INA-PHYS' then res.DateToUse end) INAPHYS_DateToUse,
   max(case when res.RetStage = 'SEM-PHYS' then res.RetYears end) SEMPHYS_RetYears,
   max(case when res.RetStage = 'INA-PHYS' then res.RetYears end) INAPHYS_RetYears
from collections c
join dtree t
  on c.DataID = t.DataID
join rimsNodeClassification rnc
  on c.DataID = rnc.DataID
left join rsiEventSched res 
  on rnc.RimsRSI = res.RimsRSI
where c.CollectionID= 201
group by c.DataID, t.Name, rnc.RimsRSI, rnc.Status

【讨论】:

  • 谢谢dnoeth。非常有帮助,我正忙于从派生表中进行选择,在该派生表中,我使用 max case 将多行合并为具有多列的一行。 :)
猜你喜欢
  • 2012-10-12
  • 2014-09-17
  • 2013-08-03
  • 2016-07-17
  • 2016-01-05
  • 2021-11-03
  • 2012-06-20
  • 1970-01-01
  • 2012-06-12
相关资源
最近更新 更多