Updating one SQL table based on data in another table

╄→гoц情女王★ 提交于 2019-12-11 03:18:03

问题


I am running Microsoft SQL Server 2008 R2, and pulling information from two tables to create one new table.

Table A has leads with a unique lead number and other information.
Table B has sales with a unique sales number, and the lead number associated with it.
Data from both tables are pulled into temp tables in SQL Server so I can change and update whatever I need, and the output of this will go into a new table.

One lead from Table A can have multiple sales associated with it in table B.

I want to update the Number of Sales column in Table A (Leads) based on how many times that lead number appears in Table B (sales). So if Table B (sales) has a lead number tied to seven (7) sales, the Number of Sales column in Table A (leads) will be updated to 7.

I have tried a few variations using the COUNT function but with no success. Any help would be appreciated.


回答1:


This should work for you assuming the field name is leadNo:

update tablea 
set sales = (select count(*) 
             from tableb 
             where tableb.leadNo = tablea.leadNo)

SQL Fiddle Demo



来源:https://stackoverflow.com/questions/15621826/updating-one-sql-table-based-on-data-in-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!