-1

現在、次の 2 つの列を含む巨大なテーブル (100 万件を超えるレコード) がありますCustomerNameAmountBilled

と呼ぶことができる別の列を追加したいPurchaseIDので、CustomerName + PurchaseIDそれは一意の組み合わせになり、主キーを作成できます。

たとえば、元のデータは次のようになります。

CustomerName AmountBilled
-------------------------    
Bill          $2
Bill          $3.5
Joe           $5

新しいテーブルを次のようにします。

Bill    1    $2
Bill    2    $3.5
Joe     1    $5

で計算された 2 番目の列を使用しSQLます。

これに対する正しいSQLステートメントは何ですか?

4

1 に答える 1

2
alter table TableName
    add PurchaseID int NULL
GO
;with cte as (
  select *, rn = row_number() over (partition by CustomerName order by @@spid)
  from TableName
)
update cte set PurchaseID = rn
GO
alter table TableName
    alter column PurchaseID int not NULL
GO
于 2013-08-08T12:26:29.343 に答える