在TSQL中排名数据

时间:2016-06-14 21:03:26

标签: sql-server-2008-r2

数据:

DECLARE @tblData TABLE (MediaID int,MediaTagName varchar(2000),MediaTypeName varchar(2000),keyitem varchar(2000),value varchar(2000))
INSERT INTO @tblData VALUES (48229,'Primary','Video','videoid','1234')
INSERT INTO @tblData VALUES (48229,'Primary','Video','src','somesrc')
INSERT INTO @tblData VALUES (48229,'Primary','Video','url','someurl')
INSERT INTO @tblData VALUES (48211,'Secondary','Video','videoid','1234')
INSERT INTO @tblData VALUES (48211,'Secondary','Video','src','somesrc')
INSERT INTO @tblData VALUES (48311,'Primary','Video','videoid','123456')
INSERT INTO @tblData VALUES (48311,'Primary','Video','src','somesrc')
INSERT INTO @tblData VALUES (48311,'Primary','Video','url','someurl')

查询已尝试:

SELECT 
    MediaID, MediaTagName, 
    RANK() OVER (PARTITION BY mediaid,mediatagname ORDER BY mediatagname) as rnk 
FROM 
    @tblData

我需要获取基于MediaIdMedisTagName分区的数据。基本上最终结果应该是:

DECLARE @tblDataExpected TABLE (MediaID int,MediaTagName varchar(2000),MediaTypeName varchar(2000),keyitem varchar(2000),value varchar(2000),rnk int)
INSERT INTO @tblDataExpected VALUES (48229,'Primary','Video','videoid','1234','1')
INSERT INTO @tblDataExpected VALUES (48229,'Primary','Video','src','somesrc','1')
INSERT INTO @tblDataExpected VALUES (48229,'Primary','Video','url','someurl','1')
INSERT INTO @tblDataExpected VALUES (48211,'Secondary','Video','videoid','1234','1')
INSERT INTO @tblDataExpected VALUES (48211,'Secondary','Video','src','somesrc','1')
INSERT INTO @tblDataExpected VALUES (48311,'Primary','Video','videoid','123456','2')
INSERT INTO @tblDataExpected VALUES (48311,'Primary','Video','src','somesrc','2')
INSERT INTO @tblDataExpected VALUES (48311,'Primary','Video','url','someurl','2')

SELECT * from @tblDataExpected
order by MediaID

摘要 - 分区应该基于mediatag和媒体ID来生成排名,但是如果有重复的mediaTag(例如" Primary")具有不同的媒体ID,它应该使用以前的媒体ID等主要用于主要的最后一个等级的增量。

1 个答案:

答案 0 :(得分:1)

首先,您需要使用DENSE_RANK而不是RANK,因为您的分区中有重复项。这只会增加不同行的排名。

其次,分区只需要在MediaTagName上,因为您希望为每个MediaID的每个不同MediaTagName增加分区。因此,MediaID会移至ORDER BY条件。

我相信以下内容会产生你想要的结果:

SELECT  td.MediaID,
        td.MediaTagName,
        td.MediaTypeName,
        td.keyitem,
        td.value,
        DENSE_RANK() OVER (PARTITION BY MediaTagName ORDER BY MediaID) AS rnk
FROM    @tblData AS td
ORDER BY td.MediaID;