创建rank()或row_number()列

时间:2017-10-29 12:29:50

标签: sql-server tsql

我有如下表格,

enter image description here

如果我们检查“n”列,它的双倍 - 如果问题重复,则用ansSecID分隔多个答案。

QuestionId + AnsSecId = unique row

我可以为“n”创建rank()列吗? e.g. n = 8, has 2 rows. So i want 8_1, 8_2.

for n = 17, can I get 17_1,17_2,17_3

或类似rank()列。 some 1,2,3 row no。 ˚For repetitive n.

最多1个问题将是3个答案。

2 个答案:

答案 0 :(得分:2)

这样的事情:

select (cast(n as varchar(255)) +
        (case when count(*) over (partition by n) > 1
              then '_' + cast(row_number() over (partition by n order by anssecid) as varchar(255))
              else ''
         end)
        ) as new_n

实际上,您的repeat列似乎为when做了工作:

select (cast(n as varchar(255)) +
        (case when repeat > 0
              then '_' + cast(row_number() over (partition by n order by anssecid) as varchar(255))
              else ''
         end)
        ) as new_n

答案 1 :(得分:2)

试试这个,我不在电脑上,但这应该有效。也可以使用n作为分区

select Cast (n as varchar)+'-'+cast (r as varchar) str
from (
     Select n, row_number() over (partition by q_id order by anssecid) r
     from table
     ) x