0

我的数据在下面

id  DENM                                     DD
1   Point 5-Point 4;  (Sill22);              902
1   Point 3-Point 5;  (Right Jammy);         2014
1   Point 3-Point 5;  (Right Jammy);         2004
1   Point 2-Point 3;  (Head11);              902
1   Point 2-Point 3;  (Head11);              842
1   Point 4-Point 2;  (Left Jammy);          2014
1   Point 4-Point 2;  (Left Jammy);          2004
2   Point 4-Point 2;  (Left Jammy);          885
2   Point 4-Point 2;  (Left Jammy);          800

我按 ID 将上表加入到另一个表中。但在将数据加入数据之前,我希望数据如下所示

1    902    2014    2004    902     842     2014    2004
2    885    800     NULL    NULL    NULL    NULL    NULL

如何在 SQL 中编写查询

4

1 回答 1

1

T-SQL 中的枢轴都是一样的;

  • 找到要分列的列值
  • 找到您为其分配转换的列(总和、最大值、最小值等)
  • 剩下的就是肉汁

在你的情况下,你有一张桌子

select
 id,
 DENM,
 DD
from [table_name]

你想把它加入你的另一张桌子:

select
 id,
 DENM,
 DD,
 t2.[fields]
from [table_name] t1 with (nolock)
join [second_table] t2 with (nolock)
 on t1.id = t2.id

并在其上放置一个支点:

select
 id,
 [field list]
from
(
 select
  id,
  DENM,
  DD,
  t2.[fields]
 from [table_name] t1 with (nolock)
 join [second_table] t2 with (nolock)
  on t1.id = t2.id
) data
pivot
(
 sum(value field)
 for [DD] in (@collist)
) as pvtData

我建议从先前的查询中构建您的 [字段列表],该查询构建了一个漂亮的干净填充值列表。像这样的东西:

    DECLARE @collist nvarchar(max);
    SELECT @collist = STUFF(
    (
        SELECT 
            distinct ',' + quotename(Variable)  
        from
            [table_name] t1
        group by 
            Variable
                    FOR XML PATH(''), root('MyString'), type).value('/MyString[1]','varchar(max)'), 1, 1, '');

这将要求您使用动态 SQL 并完成您的存储过程

exec sp_executesql @queryText
于 2019-05-17T16:21:03.947 回答