2009-04-15 17 views
0

Ich habe die folgende Anfrage erhalten.Aktualisiere Teilmenge von Daten in sqlserver

Bitte geben Sie jedem neuen Vertriebsmitarbeiter 7% der aktuellen Kontakte für den neuen Vertriebsmitarbeiter ("Peter") an.

Was ich beschloss zu tun war, um die Gesamtzahl der Datensätze für jeden Vertriebsmitarbeiter zu erhalten und 7% der Datensätze zu berechnen.

Zum Beispiel David verfügt über 200 200/7% = 14

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

Nun kann ich die Daten auswählen, aber ich kämpfen, um sie zu aktualisieren; Ich dachte, das würde es aber keine Freude machen.

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

Irgendwelche Ideen, wo ich falsch liege? Jede Hilfe, sehr geschätzt.

Antwort

0

PK_Of_tb_Contact - Primärschlüssel in Ihrer tb_Contact Tabelle

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

Try this:

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 

Wenn Sie versuchen möchten, wenn Sie die Datensätze aktualisieren Sie möchten, können Sie dies tun:

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 

Wie Sie sehen können, sind die einzigen Änderungen zwischen Aktualisierungen oder Prüfungen die Zeilen vor der FROM-Klausel.

1

Warum nicht TOP 7 PERCENT oder TOP 7 PERCENT WITH TIES verwenden?

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() 
) 
Verwandte Themen