2

我的 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

4 回答 4

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

Demo on SQLFiddle

于 2012-11-08T22:57:47.697 回答
0

你没有指定你的 DBMS,所以我假设 PostgreSQL:

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
于 2012-11-08T23:04:51.373 回答
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
于 2012-11-08T19:05:49.063 回答
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
于 2012-11-08T18:24:15.073 回答