繁体   English   中英

在SQL Server中使用数据透视表将列转换为行

[英]Converting Columns Into Rows Using Pivot In SQL Server

我有如下表:

在此输入图像描述

我想将其转换为以下内容:

+------------+---------------------+---------------------+
| 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()Child_Code分区的每个列表进行Child_Code ,以便与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

回报

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM