1

我有一个表 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.

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

4

3 回答 3

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
于 2012-05-25T15:30:13.033 回答
1

SQL 摆弄一个工作演示

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
于 2012-05-25T15:33:30.940 回答
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
于 2012-05-25T15:31:17.803 回答