1

我有以下 CTE 表达式:

WITH DocDetails_CTE 
 AS
(
SELECT   d.DocumentId,    
         dd.AutUser,           
        rank() over (order by d.DocumentId) as [r]
  FROM   Document d
         INNER JOIN DocumentItems di
                 ON d.DocumentId = di.DocumentId           
         INNER JOIN DocumentDetails dd
                 ON dd.DocumentDetailsId = di.DocDetailsId           
  )
  SELECT *
  FROM DocDetails_CTE

它返回以下结果:

documentId| AuthUser |      [r]
-------------------------------
52  Derck       1
52  John        1
53  Niall       3
53  Bill        3
53  John        3
53  Andy        3
54  Rob         7
54  Noel        7

如何修改 CTE,以便我只获得具有新 documentId 的第一行,例如

documentId| AuthUser |      [r]
-------------------------------
52  Derck       1    
53  Niall       3
54  Rob         7
4

1 回答 1

1

您必须确定“第一行”的含义 - 通过制作minmax或其他方式来识别您想要的行。这将按字母顺序返回“第一个”:-

select cte.DocumentId, min(cte.AutUser) as AutUser, cte.[r]
from (
  SELECT   d.DocumentId,    
             dd.AutUser,           
            rank() over (order by d.DocumentId) as [r]
      FROM   Document d
             INNER JOIN DocumentItems di
                     ON d.DocumentId = di.DocumentId           
             INNER JOIN DocumentDetails dd
                     ON dd.DocumentDetailsId = di.DocDetailsId

) cte
group by cte.DocumentId, cte.[r]

或者您可以嵌套两个窗口函数并重现您的(可能)随机代码:-

select
    pass2.documentid, 
    pass2.autuser, 
    pass2.r
from (
    select
        pass1.*,
        row_number() over (partition by [r] order by documentid ) as rownumber
    from (
        select
            d.documentid,
            dd.autuser,
            rank() over (order by d.documentid) as [r]
        from document d
        join documentitems di on di.documentid = d.documentid           
        join documentdetails dd on dd.documentdetailsid = di.docdetailsid 
    ) pass1
) pass2
where pass2.rownumber=1
于 2013-11-06T00:36:20.157 回答