SQL查询以获取ToTime,其中max(EndMeasDepth)和min(ReportNo)和Min(SeqNo)

时间:2019-10-03 14:39:37

标签: sql sql-server

enter image description here

请帮助。查询是我所能得到的。这是txt格式的查询。由于max(EndMeasDepth)为NULL或0,我想使用min(ReportNo)和min(SeqNO)来获取列[ToTime]

select D.wellid, min(ToTime) as [ToTime]from 
DailyOperations d
INNER JOIN (select WellID, max(ISNULL(EndMeasDepth,0)) AS MaxEndMeasDepth 
from DailyOperations Group By WellID) DM on DM.WellID = D.WellID and 
DM.MaxEndMeasDepth = ISNULL(D.EndMeasDepth,0)
where D.JobID ='Drilling' and D.wellid ='102193.01'
GROUP BY D.WellID
order by D.WellID

1 个答案:

答案 0 :(得分:0)

首先我们找到最小值和最大值,然后获取数据。

WITH dMax AS
(
    SELECT 
        WellID          =   d.WellID
    ,   EndMeasDepth    =   ISNULL(MAX(d.EndMeasDepth), 0)
    ,   ReportNo        =   MIN(d.ReportNo)
    ,   SeqNo           =   MIN(d.SeqNo)
    FROM
        DailyOperations AS d
    WHERE   1 = 1   --if needed
    --  AND d.JobID ='Drilling' 
    --  AND d.wellid ='102193.01'
    GROUP BY
        d.WellID
)
SELECT
    WellID  =   d.WellID
,   ToTime  =   d.ToTime
FROM
                DailyOperations AS d
    LEFT JOIN   dMax            AS dm   ON  dm.WellID = d.WellID
                                        AND dm.EndMeasDepth = ISNULL(d.EndMeasDepth, 0)
                                        AND dm.ReportNo = d.ReportNo
                                        AND dm.SeqNo = d.SeqNo