我有下表
id || Account
=======================
101 || A1
102 || A2
103 || A3
104 || A3
105 || A3
我想编写一个select查询,如果帐户相同,则会给我相同的ID。因此,对于所有帐户A3,我希望新ID为103.
预期结果是
OldId || Account || NewID
==================================
101 || A1 || 101
102 || A2 || 102
103 || A3 || 103
104 || A3 || 103
105 || A3 || 103
答案 0 :(得分:2)
假设ID是序列
Declare @Table table (Id int,Account varchar(25))
Insert @Table values
(101,'A1'),
(102,'A2'),
(103,'A3'),
(104,'A3'),
(105,'A3')
Select OldID = ID
,Account
,NewID = min(ID) over (Partition By Account)
From @Table
Group by Account,ID
返回
OldID Account NewID
101 A1 101
102 A2 102
103 A3 103
104 A3 103
105 A3 103
答案 1 :(得分:1)
试试这个......如果您需要任何澄清,请告诉我
在这种情况下,ID不必按顺序排列。
select
a.id as OldId,
a.account,
b.newID as newID
From
accountstable a inner join
(
select account, min(id) as NewID from accountstable -- Get the Min or Max id that will become the NewId
group by account
) b
on a.account = b.account
答案 2 :(得分:0)
声明@Table表(Id int,Account varchar(25))
插入@Table
值(101,' A1'),(102,' A2'),(103,' A3'),(104,' A3') ;),(105,' A3')
选择*,排名()(按帐户排序)+100作为NewID 来自@table