Finding Similar Records with SQL
I have a SQL Server 2008 database with 2 tables. These tables are Address and Store. These tables are defined as
Address
--------
ID (int)
Line1 (nvarchar(255))
PostalCode (nvarchar(5))
City (nvarchar(255))
State (nvarchar(255))
Store
-----
ID (int)
LocationID (int)
Name
I am trying to find a list of stores that are located at the same address by Line1 and PostalCode. I need to ignore the ID because of duplicate records. I do not care about stores that are the only store at their location. Rather, I only want a list of stores th开发者_C百科at share a location. Unfortunately, I'm not sure how to do this.
How do I write a query that will only return records that are group to address at the same Line1 and PostalCode?
Thank you!
Is this what you want?
SELECT t1.*, s.* FROM
(SELECT Line1 ,PostalCode
FROM Address
GROUP BY Line1 ,PostalCode
HAVING COUNT(*) >1) t2
JOIN Address t1 ON t2.Line1 = t2.Line1
AND t1.PostalCode = t2.PostalCode
JOIN Store s on t1.ID = s.LocationID
select s.ID, s.LocationID, s.Name, a.ID, a.Line1, a.PostalCode
from (
select Line1 + ', ' + PostalCode as Line1PostalCode
from Address a
inner join Store s on a.ID = s.LocationID
group by Line1+ ', ' + PostalCode
having count(*) > 1
) ag
inner join Address a on ag.Line1PostalCode = a.Line1+ ', ' + a.PostalCode
inner join Store s on a.ID = s.LocationID
This query uses a subquery to find all addresses with more than one store, and then uses that as the basis for selecting the stores to show.
WITH StoreAddress AS
(
SELECT * FROM Store s INNER JOIN Address a ON s.LocationID=a.LocationID
)
SELECT sa.* FROM StoreAddress sa INNER JOIN
(SELECT Line1, PostCode FROM StoreAddress
GROUP BY Line1, PostCode
HAVING Count(ID)>1) pairs
ON pairs.Line1=sa.Line1 AND pairs.PostCode=sa.PostCode
ORDER BY sa.Line1, sa.PostCode
The query is sorted by Line1 and PostCode so that stores in the same location are shown together.
精彩评论