具有最大功能的SQL INNER JOIN DISTINCT

时间:2013-05-28 07:05:09

标签: sql sql-server-2005

我有表tbMeasurement和tbPatientMeasurement。

tbMeasurement

MeasurementIDP
MeasurementName

tbPatientMeasurement

PatientMeasurementIDP
MeasurementIDF
MeasurementValue
Taken (Datetime)

执行以下查询时:

SELECT DISTINCT dbo.tbMeasurement.MeasurementName
      , dbo.tbPatientMeasurement.MeasurementValue
      , dbo.tbPatientMeasurement.Taken
  FROM dbo.tbMeasurement
 INNER JOIN dbo.tbPatientMeasurement
   ON  dbo.tbMeasurement.MeasurementIDP = dbo.tbPatientMeasurement.MeasurementIDF

这将返回其中一个MeasurementName的双重条目。 我也想要MeasurementName,MeasurementValue by max Taken(datetime).

2 个答案:

答案 0 :(得分:5)

试试这个 -

SELECT DISTINCT 
      m.MeasurementName
    , p2.MeasurementValue
    , p2.Taken
FROM dbo.tbMeasurement m
JOIN (
    SELECT 
          p.MeasurementValue
        , Taken = MAX(p.Taken) 
    FROM dbo.tbPatientMeasurement p 
    GROUP BY m.MeasurementName, p.MeasurementValue
) p2 ON m.MeasurementIDP = p2.MeasurementIDF

答案 1 :(得分:3)

SELECT  
      m.MeasurementName
    , p.MeasurementValue
    , a.Taken 
FROM dbo.tbMeasurement m
INNER JOIN dbo.tbPatientMeasurement p ON m.MeasurementIDP = p.MeasurementIDF
INNER JOIN
(
select MeasurementIDF,MAX(Taken) as taken 
from tbPatientMeasurement
group by MeasurementIDF
) a on a.MeasurementIDF=p.MeasurementIDF and a.taken=p.Taken