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

时间:2017-03-21 11:59:03

标签: sql sql-server pivot pivot-table

我有以下表格:

enter image description here

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

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

任何帮助请!!

2 个答案:

答案 0 :(得分:2)

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

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;

答案 1 :(得分:1)

如果package main; import java.sql.*; public class Validate { public static boolean checkUser(String username,String password) { boolean st =false; try{ //loading drivers for mysql Class.forName("com.mysql.jdbc.Driver"); //creating connection with the database Connection con=DriverManager.getConnection ("jdbc:mysql:/ /localhost:3306/wpdcourseworkdb","root",""); PreparedStatement ps =con.prepareStatement ("select * from users where username=? and password=?"); ps.setString(1, username); ps.setString(2, password); ResultSet rs =ps.executeQuery(); st = rs.next(); }catch(Exception e) { e.printStackTrace(); } return st; } } 的最大数量未知,则需要使用动态sql。您需要使用row_number()对按plan_date分区的每个列表进行编号,以便与pivot()一起使用。

测试设置:

Child_Code

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

代码生成:

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;

返回

 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