加入三个表,一个连接使用cte,其他连接是正常的。如何将此第三个表加入到使用cte的现有查询中?

时间:2015-07-13 20:37:06

标签: sql-server-2008 common-table-expression

数据很简单。 tblLog 是一个包含UserID,Time和Action的日志。 tblRole 具有UserID和Role以及Date字段。 tblActionDesc 具有Action和ActionDesc(描述)。我希望查询在 tblLog 中提供信息,但也包括来自 tblRole 的角色(对于每个UserID)和来自 tblActionDesc 的ActionDesc(对于每个行动)。

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

enter image description here

如何将 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

中的问题



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的问题:Need query to relate unique parent to child that is not unique but can be made unique with MAX

2 个答案:

答案 0 :(得分:1)

;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

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

编辑:已在评论中更新了问题。