代码之家  ›  专栏  ›  技术社区  ›  user4833581

我想使用join和dynamic将一些数据转换为SQL Server中的pivot

  •  0
  • user4833581  · 技术社区  · 8 年前

    enter image description here

    最后,这张桌子是我的目标。

    这是我的演示数据库

    create database pvtestDb;
    go
    
    use pvtestDb;
    go
    
    create table custTransaction
    (
        id int,
        custNum int,
        value nvarchar(50)
    )
    go
    
    create table customers
    (
        id int,
        custName nvarchar(50)
    )
    
    insert into Customers(id, custName) 
    values (1, 'aaa'), (2, 'bbb'), (3, 'ccc'), (4, 'ddd'), 
           (5, 'eee'), (6, 'fff'), (7, 'ggg'), (8, 'hhh'), (9, 'iii')
    
    insert into custTransaction (id, custNum, value) 
    values (1, 3, 'a'), (1, 4, 'b'), (1, 5, 'c'),
           (2, 3, 'd'), (2, 4, 'e'), (2, 6, 'f'),
           (3, 3, 'g'), (3, 8, 'h'), (3, 9, 'i')
    
    select * from customers
    select * from custTransaction
    
    
    select custName, custNum, value 
    from customers
    join custTransaction on custTransaction.id = customers.id
    

    我尝试过这样的代码,但根本不起作用

    SELECT 
        custNum, [a], [b], [c], [d]  
    FROM
        customers
    JOIN
        custTransaction ON custTransaction.id = customers.id
    PIVOT
        (COUNT([custName]) 
         FOR [custName] IN ([a], [b], [c], [d])) AS p
    

    我需要先连接两个表。

    如果有任何提示,我将不胜感激

    1 回复  |  直到 8 年前
        1
  •  2
  •   uzi    8 年前

    下面是使用动态SQL的方法

    declare @customers varchar(8000)
    declare @sql varchar(8000)
    
    select @customers = stuff((
        select ',' + quotename(custName)
        from customers
        for xml path('')
    ), 1, 1, '')
    
    set @sql = 'select
            id, ' + @customers + '
        from (
            select
                ct.id, c.custName, ct.value
            from 
                customers c
                join custTransaction ct on ct.custNum = c.id
        ) t
        pivot (
            max(value) for custName in (' + @customers + ')
        ) p'
    
    exec (@sql)
    

    输出

    id  aaa     bbb     ccc   ddd   eee   fff   ggg     hhh     iii
    ----------------------------------------------------------------
    1   NULL    NULL    a     b     c     NULL  NULL    NULL    NULL
    2   NULL    NULL    d     e     NULL  f     NULL    NULL    NULL
    3   NULL    NULL    g     NULL  NULL  NULL  NULL    h       i