T-SQL返回具有唯一字段的行

时间:2013-11-05 23:28:40

标签: sql-server tsql

我有以下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的第一行 e.g。

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

1 个答案:

答案 0 :(得分: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