加入列时忽略列具有多个值

时间:2012-05-25 15:20:04

标签: tsql join count

我有一个包含以下数据的表Orgs:

ID   Name            AddressID
0    McDonalds          4
1    Starbucks          5
2    Burger King        7

我还有一个表,地址,包含以下数据:

ID   OrgID   Address
3     0      123 Main St.
4     0      456 East Ave.
5     1      789 Young St.
6     2      5 Riverside Dr.
7     2      8 Lakeview Ave.

我需要创建一个select语句,从Orgs表中选择公司名称及其地址。 Orgs表中的公司可以有1个或多个地址。如果公司只有一个地址,我不想退回该公司的任何地址。如果公司有多个地址,我想返回Orgs.AddressID = Addresses.ID

的地址

所以我的结果应该是这样的:

ID   Name         Address
0    McDonalds    456 East Ave.
1    Starbucks
2    Burger King  8 Lakeview Ave.

我不知道该怎么做。谢谢你的帮助!

3 个答案:

答案 0 :(得分:1)

SELECT 
    O.ID, O.Name, A.Address
FROM 
    Orgs O
LEFT OUTER JOIN 
    (SELECT OrgID FROM Addresses GROUP BY OrgID HAVING COUNT(*) > 1) X ON O.ID = X.OrgID
LEFT OUTER JOIN 
    Addresses A ON X.OrgID = A.OrgID AND O.AddressID = A.ID

答案 1 :(得分:1)

SQL fiddle with a working Demo

SELECT O.ID, O.Name, IsNull(A.addr, '') as Address
FROM Org O
LEFT JOIN 
(
  SELECT OrgID 
  FROM Address 
  GROUP BY OrgID 
  HAVING COUNT(*) > 1
) c 
  ON O.ID = c.OrgID
LEFT JOIN Address A 
  ON c.OrgID = A.OrgID 
  AND O.AddressID = A.ID

答案 2 :(得分:0)

没有数据本身很困难,但这样的事情呢?

SELECT 
    orgs.OrgID
,   orgs.Name
,   CASE 
        WHEN OrgCount > 1 THEN ad.Address
        ELSE '' 
    END AS Address
FROM        
(
    SELECT 
        OrgID
    ,   Name
    ,   COUNT(*) AS OrgCount
    FROM 
    Orgs
) orgs
INNER JOIN 
Addresses ad
    ON 
    ad.AddressID = orgs.AddressID 
GROUP BY 
    orgs.OrgID
,   orgs.Name
,   CASE 
        WHEN OrgCount > 1 THEN ad.Address
        ELSE '' 
    END AS Address