根据另一个字段最早出现的情况选择一行值

时间:2018-10-02 15:25:17

标签: sql-server tsql filter sql-server-2008-r2

我有一个表格,其中包含重复的模具编号:jodbom.fbompart。我希望能够选择最早的工作编号:jomast.fjobno和优先级编号:jomast.fschdprior的数据行。该表应从7行增加到4行。

http://sqlfiddle.com/#!18/d226e/1/0

    SELECT
    jodbom.fbompart as MoldNo, 
    jomast.fjobno as Job No,
    jomast.frel_dt as DueDate,
    jomast.fschdprior as Priority

    FROM jodbom 
    INNER JOIN jomast ON jodbom.fjobno =  jomast.fjobno
    INNER JOIN jodrtg ON jomast.fjobno = jodrtg.fjobno 
    INNER JOIN inmastx ON jodbom.fbompart = inmastx.fpartno
    LEFT JOIN sorels ON jomast.fsono+jomast.fkey = sorels.fsono+sorels.finumber+sorels.frelease 

    WHERE     (jomast.fstatus = 'RELEASED' OR
                          jomast.fstatus = 'OPEN') AND (jomast.flisapl = 1) AND (jodbom.fltooling = 1) AND 
                          (jodrtg.fpro_id <> '09') 

Order by jomast.frel_dt, jomast.fpriority

1 个答案:

答案 0 :(得分:1)

为您完成以下工作:

SELECT
    MoldNo
    , [Job No]
    , DueDate
    , Priority
FROM

(
SELECT
    jodbom.fbompart as MoldNo, 
    jomast.fjobno as [Job No],
    jomast.frel_dt as DueDate,
    jomast.fschdprior as Priority,
    ROW_NUMBER() OVER (PARTITION BY jodbom.fbompart ORDER BY jomast.fjobno, jomast.fschdprior) R

    FROM jodbom 
    INNER JOIN jomast ON jodbom.fjobno =  jomast.fjobno
    INNER JOIN jodrtg ON jomast.fjobno = jodrtg.fjobno 
    INNER JOIN inmastx ON jodbom.fbompart = inmastx.fpartno
    LEFT JOIN sorels ON jomast.fsono+jomast.fkey = sorels.fsono+sorels.finumber+sorels.frelease 

    WHERE     (jomast.fstatus = 'RELEASED' OR
                          jomast.fstatus = 'OPEN') AND (jomast.flisapl = 1) AND (jodbom.fltooling = 1) AND 
                          (jodrtg.fpro_id <> '09') 
) Q

WHERE R = 1
Order by DueDate, Priority