我收到了以下请求。
请将每位销售人员登记的当前联系人的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 :(得分: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 :(得分:1)
为什么不使用TOP 7 PERCENT
或TOP 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()
)
答案 2 :(得分: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()
)