SQL:根据最小值和最大值显示关联值

时间:2013-06-25 16:32:41

标签: sql ms-access max min having

我有tblDump,它有~52,000条记录。它是具有相应给药时间的ID列表。相关变量为SubjectNumberRECDATERECTIMEFoodType。每位患者每天服用两次,因此每Min(RECTIME) Max(RECTIME)RECDATE。为了显示这个,我到目前为止:

 SELECT tblDump.SubjectNumber, tblDump.RECDATE, 
        Min(RECTIME) As MornDose, Max(RECTIME) As EveDose
 FROM tblDump
 GROUP BY tblDump.SubjectNumber, tblDump.RECDATE
 ORDER BY tblDump.SubjectNumber, tblDump.RECDATE Asc;

对于变量FoodType,有三种可能性:1,2或3.我需要打印Min(RECTIME)与1关联且Max(RECTIME)与之关联的主题3,每天。

我试图制作HAVING语句,Foodtype = 1 Min(RecTIME) Foodtype = 3Max(RECTIME) SELECT a.SubjectNumber, a.RECDATE, First(a.colm AS MornDose), First(m.FoodType) FROM (SELECT SubjectNumber, RECDATE, MIN(RECTIME) as colm FROM tblDump GROUP BY SubjectNumber, RECDATE) AS a INNER JOIN tblDump AS m ON (a.colm=m.RECTIME) AND (a.RECDATE = m.RECDATE) AND (a.SubjectNumber = m.SubjectNumber) GROUP BY a.SubjectNumber, a.RECDATE ORDER BY a.SubjectNumber, a.RECDATE; ,但我无法获得语言学正确。

解决:

好的,我确定有一种更有效的方法可以做到这一点,但这很有效。希望这将有助于某人或某人发布更有效的方法。我使用了3个查询,一个用于最小剂量时间,一个用于最大剂量时间,一个用于将它们连接在一起。

qryMin:

SELECT a.SubjectNumber, a.RECDATE, First(a.colm) AS MornDose, First(m.FoodType)
FROM (SELECT SubjectNumber, RECDATE, MAX(RECTIME) AS colm 
      FROM tblDump GROUP BY SubjectNumber, RECDATE)  AS a 
INNER JOIN tblDump AS m 
        ON (a.SubjectNumber = m.SubjectNumber) 
           AND (a.RECDATE = m.RECDATE) 
           AND (a.colm = m.RECTIME)
GROUP BY a.SubjectNumber, a.RECDATE
ORDER BY a.SubjectNumber, a.RECDATE;

qryMax:

SELECT qryMin.*, qryMax.*
FROM qryMin
INNER JOIN qryMax 
        ON qryMin.SubjectNumber = qryMax.SubjectNumber
WHERE qryMin.RECDATE = qryMax.RECDATE 
      AND qryMin.FoodType = 1 
      AND qryMax.FoodType = 3;

qryCombo:

{{1}}

0 个答案:

没有答案