在同一查询中从多个中选择最近的记录

时间:2013-04-30 12:40:48

标签: sql sql-server-2012

我的问题与sql select from multiple records only the most recent非常相关,虽然它根本无效。

我有一个view,获取会员名称及其当前的排名。 我还有一个表,它找到所有等级名称大于所述等级数。

按原样,新视图显示当前成员,以及排名标题表中的排名标题>=

这意味着输出会在排名后显示每个标题,而我只想显示第一个(最早的)标题。

我尝试过以上链接的修改示例:

SELECT dbo.vwGetMemberRank.siteMemberId AS ID
     , dbo.vwGetMemberRank.memberNickname AS Nick
     , dbo.vwGetMemberRank.siteMemberRankLevel AS currentPoints
     , dbo.tblSiteMemberRankTitle.siteMemberRankLevel AS neededPoints
     , dbo.tblSiteMemberRankTitle.siteMemberRankTitle AS rankTitle
FROM dbo.vwGetMemberRank 
    INNER JOIN dbo.tblSiteMemberRankTitle
        ON dbo.vwGetMemberRank.siteMemberRankLevel >= dbo.tblSiteMemberRankTitle.siteMemberRankLevel

WHERE dbo.vwGetMemberRank.siteMemberId IN
                 (
                   SELECT  MIN(siteMemberId) AS ID
                   FROM dbo.vwGetMemberRank AS vwGetMemberRank_1
                   GROUP BY siteMemberRankLevel
                  )

这仍然显示所有其他标题。

修改

vwGetMemberRank

SELECT dbo.tblSiteMemberRank.siteMemberId
     , dbo.tblSiteMemberRank.siteMemberRankLevel
     , dbo.tblSiteMemberDetail.memberNickname
FROM dbo.tblSiteMemberDetail 
    INNER JOIN dbo.tblSiteMemberRank ON dbo.tblSiteMemberDetail.siteMemberId = dbo.tblSiteMemberRank.siteMemberId

tblSiteMemberRankTitle

CREATE TABLE [dbo].[tblSiteMemberRankTitle](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [siteMemberRankTitle] [varchar](30) NOT NULL,
    [siteMemberRankDescription] [varchar](80) NULL,
    [siteMemberRankLevel] [int] NULL,
    [thumbnailLocation] [nvarchar](100) NULL,
 CONSTRAINT [PK__tblSiteM__3213E83F1B0907CE] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

1 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBER函数按照您喜欢的顺序(我使用dbo.tblSiteMemberRankTitle.siteMemberRankLevel DESC)对排名进行排序,然后将结果限制为RowNumber为1的位置,从而只获取行每个SiteMemberID(PARTITION BY)

的最高siteMemberRankLevel
WITH CTE AS
(   SELECT dbo.vwGetMemberRank.siteMemberId AS ID
         , dbo.vwGetMemberRank.memberNickname AS Nick
         , dbo.vwGetMemberRank.siteMemberRankLevel AS currentPoints
         , dbo.tblSiteMemberRankTitle.siteMemberRankLevel AS neededPoints
         , dbo.tblSiteMemberRankTitle.siteMemberRankTitle AS rankTitle
         , RowNumber = ROW_NUMBER() OVER(PARTITION BY dbo.vwGetMemberRank.siteMemberId ORDER BY dbo.tblSiteMemberRankTitle.siteMemberRankLevel DESC)
    FROM    dbo.vwGetMemberRank 
            INNER JOIN dbo.tblSiteMemberRankTitle
                ON tblSiteMemberRankTitle.siteMemberRankLevel >= dbo.vwGetMemberRank.siteMemberRankLevel
)
SELECT  ID, Nick, CurrentPoints, NeededPoints, RankTitle
FROM    CTE
WHERE   RowNumber = 1;