Sql从另一个表中选择(循环?)

时间:2012-11-08 18:19:02

标签: sql-server

我的SQL技能不是很好,所以帖子。

我正在尝试根据公司获取所有联系人姓名。

例如,我有两个陈述:

Select Id, CompanyName, Address From Clients
Select ClientId, ContactName From Contacts

您可能与单个客户有很多联系

结果:(我需要一列中的所有联系人姓名)

ContactName         Company    Address
----------------------------------------
Johh, Steve         123 Comp   12345 Address
David,Mike, Sarah   44 Comp    111 Address

非常感谢一个工作范例。

4 个答案:

答案 0 :(得分:1)

SELECT DISTINCT (
SELECT ISNULL(ct.ContactName, '') + ', '
FROM dbo.Clients cl JOIN dbo.Contacts ct ON cl.Id = ct.ClientId
WHERE cl.ID = cl2.Id
FOR XML PATH('')) AS ContactName, CAST(cl2.Id AS nvarchar(7)) + ' ' + cl2.CompanyName AS Company, Address
FROM dbo.Clients cl2
ORDER BY 2

SQLFiddle上的演示

答案 1 :(得分:0)

听起来你需要做桌子加入。

示例:此处有两个表

1. Person
2. Orders

查询:

SELECT 
    Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders ON Persons.P_Id = Orders.P_Id
ORDER BY Persons.LastName

答案 2 :(得分:0)

首先将公司的所有联系人姓名构建为单个列。假设数据库是SQL Server,我使用公用表表达式来存储单列联系人列表。构建CTE后,将其与Clients表连接以获取ContactNames。 FOR XML用于连接行。

WITH CTEContactList(ClientID,ContactNames) 
AS
(

 SELECT c1.ClientID,
        Names = SUBSTRING(( SELECT ', ' + c2.ContactName
                            FROM Contacts c2
                            WHERE c1.ClientID = c2.ClientID
                            FOR XML PATH ('')),3,8000 ))
 FROM Contacts c1
 GROUP BY c1.ClientID

 )

SELECT 
       cl.ID,
       cl.CompanyName,
       cl.Address,
       ctelist.ContactNames

FROM Clients cl
INNER JOIN CTEContactList ctelist
ON cl.ID = cteList.ClientID

答案 3 :(得分:0)

你没有指定你的DBMS,所以我假设P​​ostgreSQL:

select string_agg(ct.contactName, ', '), cl.companyname, cl.address
from contacts ct
  join clients cl on cl.id = ct.clientId
group by cl.companyname, cl.address