1

我的问题与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]
4

1 回答 1

1

您可以使用ROW_NUMBER函数以您喜欢的任何顺序(我使用过dbo.tblSiteMemberRankTitle.siteMemberRankLevel DESC)对排名进行排序,然后将结果限制在 RowNumber 为 1 的位置,因此仅获取siteMemberRankLevel每个 SiteMemberID 最高的行(PARTITION BY)

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;
于 2013-04-30T13:36:17.040 回答