如何通过分配序号来重命名项目?

时间:2018-09-20 20:00:05

标签: sql sql-server tsql pivot

我有下表:

DECLARE @OperatorPrice TABLE 
(
    ID INT NOT NULL, DealerId INT NULL, DealerName VARCHAR(50) NULL
)

和示例数据:

INSERT INTO @OperatorPrice 
(
    ID, DealerId, DealerName
)
VALUES
  (226, 1,  'WestCarDealer')
, (112, 1,  'WestCarDealer')
, (266, 2, 'AO')
, (112, 2, 'AO')
, (93,  3, 'Best on the West')
, (93,  3, 'Best on the West')

我想要的是将所有经销商重命名为'Dealer1','Dealer2','Dealer3'。数字应按升序分配:AO应重命名为'Dealer1'原因AOA开头,Best on the West应重命名为Dealer2原因它以B开头,WestCarDealer应该重命名为Dealer3,因为它以W开头。

因此所需的输出应如下所示:

  (226, 1, 'Dealer3')
, (112, 1, 'Dealer3')
, (266, 2, 'Dealer1')
, (112, 2, 'Dealer1')
, (93,  3, 'Dealer2')
, (93,  3, 'Dealer2')

唯一DealerName的唯一数量约为50个经销商。

如何以这种方式重命名汽车经销商?

我试图为此目的使用游标,但无法存储要递增的数字。

1 个答案:

答案 0 :(得分:4)

您可以使用CTE更新表变量

示例

@Override
public void widgetSelected(SelectionEvent e) {
    //how to know in which row is clicked the checkbox?
    System.out.println("Row selected: " + membersTable.indexOf(tableItem));
    System.out.println("Participación Habitual: " + tableItem.getText(2));
}

更新了@OperatorPrice

;with cte as (
Select *
      ,NewVal = concat('Dealer',dense_rank() over ( order by DealerName))
 From  @OperatorPrice
)
Update cte Set DealerName = NewVal