SQL Server:如何连接两个表并水平旋转第二个表

时间:2013-04-15 04:45:04

标签: sql sql-server tsql

我有两张桌子,我需要在一张桌子上列出一份工作人员名单,并且横向同一公司的所有客户,最多可以有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)

2 个答案:

答案 0 :(得分: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

Result Window

答案 1 :(得分:0)

使用XML条款和子查询 Solution