在 SQL 服务器中使用 Pivot 将列转换为行

Converting Columns Into Rows Using Pivot In SQL Server

我有如下table如下:

我想按如下方式转换:

+------------+---------------------+---------------------+
| Child_Code |     SewingStart     |      SewingEnd      |
+------------+---------------------+---------------------+
|     000001 | 2017-02-21 00:00:00 | 2017-03-21 00:00:00 |
+------------+---------------------+---------------------+

请帮忙!!

如果行数有限,可以使用条件聚合或数据透视表。但是,为此您需要一个专栏。所以:

select child_code,
       max(case when seqnum = 1 then plan_date end) as plan_date_1,
       max(case when seqnum = 2 then plan_date end) as plan_date_2
from (select t.*,
             row_number() over (partition by child_code order by plan_date) as seqnum
      from t
     ) t
group by child_code;

如果您知道所需的最大计划日期数,则只能使用此方法。否则,您将需要使用动态枢轴。思路是一样的,但是需要构造查询字符串,然后传递给sp_executesql.

编辑:

如果您只有两个值,那么 group by 可能更容易。以下处理只有一个值的情况:

select child_code, min(plan_date) as plan_date_1,
       (case when min(plan_date) <> max(plan_date) then max(plan_date)
        end) as plan_date_2
from t
group by child_code;

如果 plan_date 的最大数量未知,您将需要使用动态 sql。您将需要使用 row_number() to number each list partitioned by Child_Code for use with pivot().

测试设置:

create table t (child_code varchar(6), plan_date datetime);
insert into t values ('000001','20170221'),('000001','20170321');
declare @cols nvarchar(max);
declare @sql  nvarchar(max);

  select @cols = stuff((
    select distinct 
      ',' + quotename('Plan_Date_'
          +convert(nvarchar(10),row_number() over (
              partition by Child_Code 
              order by     Plan_Date 
          ))
          )
      from t 
      for xml path (''), type).value('.','nvarchar(max)')
    ,1,1,'');

select @sql = '
 select Child_Code, ' + @cols + '
 from  (
  select 
      Child_Code
    , Plan_Date
    , rn=''Plan_Date_''+convert(nvarchar(10),row_number() over (
          partition by Child_Code 
          order by     Plan_Date 
        ))
  from t
    ) as a
 pivot (max([Plan_Date]) for [rn] in (' + @cols + ') ) p';
 select @sql as CodeGenerated;
 exec sp_executesql @sql;

rextester 演示http://rextester.com/YQCR87525

代码生成:

 select Child_Code, [Plan_Date_1],[Plan_Date_2]
 from  (
  select 
      Child_Code
    , Plan_Date
    , rn='Plan_Date_'+convert(nvarchar(10),row_number() over (
          partition by Child_Code 
          order by     Plan_Date 
        ))
  from t
    ) as a
 pivot (max([Plan_Date]) for [rn] in ([Plan_Date_1],[Plan_Date_2]) ) p

returns

+------------+---------------------+---------------------+
| Child_Code |     Plan_Date_1     |     Plan_Date_2     |
+------------+---------------------+---------------------+
|     000001 | 21.02.2017 00:00:00 | 21.03.2017 00:00:00 |
+------------+---------------------+---------------------+