开发者

Need help with a T-SQL query

开发者 https://www.devze.com 2023-02-21 03:53 出处:网络
I have a table of locations (addresses) similar to this: location_id int identity (primary key) contact_id int (foreign key to contact table; one-to-many relationship from contacts to locations)

I have a table of locations (addresses) similar to this:

location_id int identity (primary key)
contact_id int (foreign key to contact table; one-to-many relationship from contacts to locations)
<address info>
is_primary int (1 if this is the contact's primary address, zero otherwise)

There can be only one primary address per contact. Due to an error with a recent data upload, this开发者_JAVA百科 rule has been violated and I now have several contacts with more than one primary address. I need help formulating a query to find out which ones. Ideally I'd like the output to be:

contact_id       count(is_primary)

I have no idea how to do it and would appreciate your assistance. Thank you.


SELECT contact_id, SUM(IS_PRIMARY) 
FROM table_name 
GROUP BY contact_id 
HAVING SUM(IS_PRIMARY) > 1    
0

精彩评论

暂无评论...
验证码 换一张
取 消