0

自从我做了比最基本的 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
4

1 回答 1

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
于 2015-07-26T17:55:44.310 回答