数据:
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
我需要获取基于MediaId
和MedisTagName
分区的数据。基本上最终结果应该是:
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等主要用于主要的最后一个等级的增量。
答案 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;