0

我有两张表,我需要在一张表中显示员工列表,横向同一公司的所有客户最多可以有 50 个客户

表一:

Company_id  staff name  email
1       John        john@abc
1       Mandy       mandy@aaa
2       Jane        Jane@jlkj
3       Andy        Andy@uuu

表二:

Company_id  client name client class
1       a       02
2       ss      01
2       d       08

结果表:

Company_Id  staff name  email            client 1   client 2 client3    …..  clientX 
1       John        john@abc     a(02)
1       Mandy       mandy@aaa  a(02)
2       Jane        Jane@jlkj       ss(01)  d(08)
4

2 回答 2

2

试试这个——

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

结果窗口

于 2013-04-15T06:02:18.847 回答
0

USE FOR XML CLAUSE 和 SUBQUERY 解决方案

于 2013-04-15T05:32:22.993 回答