我有一个数据表,它在同一张表中重复两次以形成三组。
它的“ ReferenceID”是主键,我想以某种方式将3个相同的ReferenceID分组,并将这三个值“ f2f”“ NF2F”“ Travel”以任意顺序注入“ Type”行中,但要确保每个ReferenceID仅具有这些值之一。
例如:
ReferenceID | Type
------------|-------
1 f2f
1 nf2f
1 Travel
2 f2f
2 nf2f
2 Travel
3 f2f
3 nf2f
3 Travel
等等等...
有可能吗?
答案 0 :(得分:1)
You can do this with a row_number
that you mod
by the number of groups you have (in your case 3):
declare @t table(RefType varchar(10));
insert into @t values ('f2f'),('nf2f'),('Travel'),('f2f'),('nf2f'),('Travel'),('f2f'),('nf2f'),('Travel');
select (row_number() over (order by RefType) % 3) + 1 as ReferenceID
,RefType
from @t
order by ReferenceID
,RefType;
+-------------+---------+
| ReferenceID | RefType |
+-------------+---------+
| 1 | f2f |
| 1 | nf2f |
| 1 | Travel |
| 2 | f2f |
| 2 | nf2f |
| 2 | Travel |
| 3 | f2f |
| 3 | nf2f |
| 3 | Travel |
+-------------+---------+