加入三个table,一个join使用cte,另一个join正常。我如何将这第三个 table 加入到我现有的使用 cte 的查询中?

Joining three tables, one join uses cte, other join is normal. How do i join this third table to my existing query which uses cte?

数据简单。 tblLog 是一个带有用户 ID、时间和操作的日志。 tblRole 具有用户 ID 和角色以及日期字段。 tblActionDesc 有 Action 和 ActionDesc(描述)。我希望查询为我提供 tblLog 中的信息,但还包括 tblRole 中的角色(对于每个用户 ID)和 [=41 中的 ActionDesc =]tblActionDesc(每个动作)。

我遇到的第一个问题是 tblRole 中的数据不是唯一的。它包含每个用户的许多角色,但它也有一个日期字段。我想出了如何利用 cte 获得唯一的 UserID。 (HT @Siyual)

如何将 tblActionDesc 添加到此 cte 的结果中?

这是cte:

;With Cte As
(
    Select  L.[ID],
            L.[UserID],
            L.[Time],
            L.[Action],
            R.[Role],
            Row_Number() Over (Partition By [L].[UserId] Order By [R].[TransDate] Desc) Row_Number
    From    [TEST111].[dbo].[tblLog]    as L
    Join    [TEST111].[dbo].[tblRole]   as R    On  L.[UserID] = R.[UserID]
)
Select  [Id], [UserId], [Time], [Action], [Role]
From    Cte
Where   [Row_Number] = 1

如果我在 tblRole

中没有 "many" 问题,这是可以使用的代码

SELECT L.[ID]
      ,L.[UserID]
      ,L.[Time]
      ,L.[Action]
      ,R.Role
      ,A.ActionDesc
  FROM [TEST111].[dbo].[tblLog] as L
  Join [TEST111].[dbo].[tblRole] as R
  On  L.[UserID] = R.[UserID]
  Join [TEST111].[dbo].[tblActionDesc] as A
  On  L.[Action] = A.[Action]

我想这就是我回答这个问题所需的全部信息。这是给了我 cte 的问题:

;With Cte As
(
    Select  ID, UserID, Role, TransDate,
            Row_Number OVER (PARTITION BY UserID ORDER BY TransDate DESC) Row_Number
    From    tblRole
)

SELECT L.[ID]
      ,L.[UserID]
      ,L.[Time]
      ,L.[Action]
      ,R.Role
      ,A.ActionDesc
  FROM [TEST111].[dbo].[tblLog] as L
  Join cte as R
  On  L.[UserID] = R.[UserID]
  Join [TEST111].[dbo].[tblActionDesc] as A
  On  L.[Action] = A.[Action]
  WHERE R.Row_Number = 1

这个怎么样:

 with cte1 as (
    -- Get the most recent TransDate for each UserID.
    select UserID, max(TransDate) as max_trans_date
    from tblRole
    group by UserID
),
cte2 as (
    -- Now that we know the most recent record for each user, 
    -- get the actual data (i.e. "Role") for each UserID.
    select r.UserID, r.[Role]
    from tblRole as r
        inner join cte1 on r.UserID = cte1.UserID and r.TransDate = cte1.max_trans_date
)
select l.ID, l.UserID, l.[Time], l.[Action], cte2.[Role], ad.ActionDesc
from tblLog as l
    left join cte2 on l.UserID = cte2.UserID
    left join tblActionDesc as ad on l.[Action] = ad.[Action]

编辑:针对评论中的问题进行了更新。