我有一个带有2个表的SQL Server 2008数据库。这些表是地址和存储。这些表定义为
Address
--------
ID (int)
Line1 (nvarchar(255))
PostalCode (nvarchar(5))
City (nvarchar(255))
State (nvarchar(255))
Store
-----
ID (int)
LocationID (int)
Name
我正在尝试找到Line1和PostalCode位于同一地址的商店列表。由于重复记录,我需要忽略ID。我不关心商店是他们所在地唯一的商店。相反,我只想要一个共享位置的商店列表。不幸的是,我不知道该怎么做。
如何编写一个只返回同一Line1和PostalCode的地址记录的查询?
谢谢!
答案 0 :(得分:3)
这是你想要的吗?
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
答案 1 :(得分:2)
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
答案 2 :(得分:0)
此查询使用子查询查找具有多个商店的所有地址,然后将其用作选择要显示的商店的基础。
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
查询按Line1和PostCode排序,以便同一位置的存储一起显示。