数据透视-如果行中有Null,如何编写代码

时间:2019-05-17 15:13:49

标签: sql sql-server

我的数据在下面

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编写查询

1 个答案:

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

完成存储的proc
exec sp_executesql @queryText