0

好的,这是选择语句

SELECT dbo.tbl_inspectors.user_firstname, 
       dbo.tbl_inspectors.user_lastname, 
       dbo.tbl_inspectors.user_loc, 
       dbo.tbl_appraisals.appPartA, 
       dbo.tbl_appraisals.appPartB, 
       dbo.tbl_appraisals.appAppraised, 
       dbo.tbl_appraisals.appFinalized,
       dbo.tbl_appraisals.appDate,
       dbo.tbl_inspectors.appProcStart, 
       dbo.tbl_inspectors.appDue, 
       dbo.tbl_inspectors.inspAdhocStaff, 
       dbo.tbl_inspectors.access_id, 
       dbo.tbl_appraisals.appraiseID, dbo.tbl_inspectors.user_id
FROM   dbo.tbl_inspectors 
       LEFT OUTER JOIN
       dbo.tbl_appraisals ON dbo.tbl_inspectors.user_id = bo.tbl_appraisals.inspectID

如果 tbl_appraisals 表中有多个针对 tbl_inspectors.user_id 的结果,那么我会为每个检查员获得多个结果,我只想让它从 tbl_appraisals 中针对 tbl_inspectors user_id 提取最新匹配,我怎样才能简单地实现这一点?

PS tbl_appraisals.appDate 是确定 tbl_appraisals 最新结果的字段

4

1 回答 1

1

假设引擎不是 MySQL ......

这是“每组 TOP 1”问题

SELECT
    *
FROM
    (
    SELECT I.user_firstname, 
           I.user_lastname, 
           I.user_loc, 
           A.appPartA, 
           A.appPartB, 
           A.appAppraised, 
           A.appFinalized,
           A.appDate,
           I.appProcStart, 
           I.appDue, 
           I.inspAdhocStaff, 
           I.access_id, 
           A.appraiseID,
           I.USER_ID,
           ROW_NUMBER() OVER (PARTITION BY I.user_id ORDER BY COALESCE(A.appDate, '19000101') DESC) AS rn
    FROM   dbo.tbl_inspectors I
           LEFT OUTER JOIN
           dbo.tbl_appraisals A ON I.user_id = A.inspectID
    ) X
WHERE
    X.rn = 1
于 2013-02-21T10:11:43.227 回答