试试这个——
CREATE TABLE dbo.staff
(
company_id INT
, staff_name NVARCHAR(50)
, email NVARCHAR(50)
)
INSERT INTO dbo.staff (company_id, staff_name, email)
VALUES
(1, 'John', 'john@abc'),
(1, 'Mandy', 'mandy@aaa'),
(2, 'Jane', 'Jane@jlkj'),
(3, 'Andy', 'Andy@uuu')
CREATE TABLE dbo.client
(
company_id INT
, client_id INT
, client_name NVARCHAR(50)
, client_class NVARCHAR(50)
)
INSERT INTO dbo.client (company_id, client_id, client_name, client_class)
VALUES
(1, 1, 'a', '02'),
(2, 2, 'ss', '01'),
(2, 3, 'd', '08')
DECLARE
@Cols NVARCHAR(MAX)
, @SQL NVARCHAR(MAX)
SELECT @Cols =
STUFF((
SELECT DISTINCT ',' + QUOTENAME(c.client_id)
FROM dbo.client c
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
, 1 , 1, '')
SELECT @SQL = '
SELECT s.staff_name, s.email, d.*
FROM (
SELECT
company_id
, ' + @Cols + '
FROM (
SELECT name = client_name + ''('' + client_class + '')'', client_id, company_id
FROM dbo.client
) x
PIVOT
(
MAX(name)
FOR client_id IN (' + @Cols + ')
) p
) d
JOIN dbo.staff s ON s.company_id = d.company_id
'
EXEC sys.sp_executesql @SQL
SELECT s.company_id
, s.staff_name
, s.email
, c.clients
FROM dbo.staff s
OUTER APPLY (
SELECT clients = STUFF((
SELECT N', ' + c.client_name + '(' + c.client_class + ')'
FROM dbo.client c
WHERE c.company_id = s.company_id
FOR XML PATH(N''), TYPE, ROOT).value(N'root[1]', N'NVARCHAR(MAX)'), 1, 2, '')
) c
WHERE c.clients IS NOT NULL