获取包括MAX和NULL在内的许多表的值

时间:2011-02-14 11:14:51

标签: sql tsql sql-server-2000 join

所以我试着解释数据库设置

tblEDS

eID | eVal1     | eVal2
-------------------------------------
1   | Monday    | Joe
2   | Tuesday   | Bob
3   | Wednesday | Jan
4   | Thursday  | Pete

tblPatient(我意识到这不是最好的数据库设计!)

pID | pVal1     | pVal2 | pEDS
------------------------------
1   | Monday    | 123   | 1
2   | Tuesday   | 456   | 2

tblPatientRecords

pID | rID
------------
1   | 1
1   | 2
2   | 3
2   | 4

tblRecords

rID | rVal1 | rVal2
-------------------
1   | Ok    | Boy
2   | Well  | Man
3   | Dead  | Kid
4   | Dead  | Girl

我需要的是一个查询来回退tblAlert中的所有记录,无论它是否在tblPatient中都有相应的值。对于tblPatient中存在的每条记录,我需要相关的最大rID和给出的相关值,即

eID | eVal1     | eVal2 | pID  | pVal1   | pVal2 | rID  | rVal1  | rVal2     
-------------------------------------------------------------------------
1   | Monday    | Joe   | 1    | Monday  | 123   | 2    | Well   | Man
2   | Tuesday   | Bob   | 2    | Tuesday | 456   | 4    | Dead   | Girl
3   | Wednesday | Jan   | NULL | NULL    | NULL  | NULL | NULL   | NULL   
4   | Thursday  | Pete  | NULL | NULL    | NULL  | NULL | NULL   | NULL   

tblEDS,tblPatient和tblRecords有更多列但未在此处显示

1 个答案:

答案 0 :(得分:2)

SELECT
  a.eID,
  a.eValue,
  t.pID,
  t.pName,
  t.rID,
  t.rValue
FROM tblAlert a
  LEFT JOIN (
    SELECT
      p.pID,
      p.pName,
      p.eID,
      r.rID,
      r.rValue
    FROM tblPatient p
      INNER JOIN (
        SELECT pID, MAX(rID) AS rID
        FROM tblPatientRecords
        GROUP BY pID
      ) pr ON p.pID = pr.pID
      INNER JOIN tblRecords r ON pr.rID = r.rID
  ) t ON a.eID = t.eID