2009-04-15 62 views
0

我已被給出以下請求。在sqlserver中更新數據子集

請將每個銷售員的當前聯繫人的7%登記給新的銷售員('Peter')。

我決定做的是獲得每個銷售人員的總記錄並計算7%的記錄。

例如 大衛具有200 200/7%= 14

SELECT TOP 14 ContactAssociate 
FROM tb_Contact 
WHERE tb_Contact.ContactAssociate = 'David' 
ORDER BY NEWID() 

現在,我可以選擇的數據,但很努力來更新它們; 我認爲這樣做,但沒有喜悅。

UPDATE tb_Contact 
SET ContactAssociate = 'Peter' 
IN 
(
SELECT TOP 14 ContactAssociate 
FROM tb_Contact 
WHERE tb_Contact.ContactAssociate = 'David' 
ORDER BY NEWID() 
) 

任何想法,我要錯了嗎? 任何幫助,非常感謝。

回答

0

PK_Of_tb_Contact - 在你tb_Contact表的主鍵

UPDATE tb_Contact 
SET ContactAssociate = 'Peter' 
where PK_Of_tb_Contact 
IN 
(
SELECT TOP 14 PK_Of_tb_Contact 
FROM tb_Contact 
WHERE tb_Contact.ContactAssociate = 'David' 
ORDER BY NEWID() 
) 
1

試試這個:

UPDATE c 
SET ContactAssociate = 'Peter' 
FROM tb_Contact c 
INNER JOIN (
    SELECT TOP 14 ContactAssociate FROM tb_Contact 
    WHERE tb_Contact.ContactAssociate = 'David' 
) q ON c.ContactAssociate = q.ContactAssociate 

如果您想嘗試,如果你正在更新所需的記錄,你可以這樣做:

SELECT c.* 
FROM tb_Contact c 
INNER JOIN (
    SELECT TOP 14 ContactAssociate FROM tb_Contact 
    WHERE tb_Contact.ContactAssociate = 'David' 
) q ON c.ContactAssociate = q.ContactAssociate 

如您所見,更新或檢查之間的唯一更改是FROM子句之前的行。

1

爲什麼不使用TOP 7 PERCENTTOP 7 PERCENT WITH TIES

DECLARE @sample int 
SET @sample = 7 

UPDATE tb_Contact 
SET ContactAssociate = 'Peter' 
where PK_Of_tb_Contact 
IN 
(
SELECT TOP (@sample) PERCENT PK_Of_tb_Contact 
FROM tb_Contact 
WHERE tb_Contact.ContactAssociate = 'David' 
ORDER BY NEWID() 
)