如果表中只有两列,如何将行转换为列?

时间:2014-04-28 10:46:37

标签: sql-server

表包含以下列和数据:

Id | Date
1 | 04/09/2014 13:00:00 1 | 04/10/2014 15:00:00 1 | 04/12/2014 16:00:00 1 | 04/13/2014 18:00:00 2 | 04/11/2014 13:00:00 2 | 04/12/2014 15:00:00 2 | 04/12/2014 16:00:00

我需要为每个Id获取每个垂直对并将其转换为水平视图,结果应如下所示:

Id | Date1               | Date2
1  | 04/09/2014 13:00:00   04/10/2014 15:00:00
1  | 04/12/2014 16:00:00   04/13/2014 18:00:00
2  | 04/11/2014 13:00:00   04/12/2014 15:00:00
2  | 04/12/2014 16:00:00   NULL 

由于在一对Id = 2中缺少日期,因此存在空值。表中没有列。

2 个答案:

答案 0 :(得分:4)

SQL Fiddle

MS SQL Server 2008架构设置

create table T
(
  Id int,
  Date datetime
)

go

insert into T values
(1  ,'04/09/2014 13:00:00'),
(1  ,'04/10/2014 15:00:00'),
(1  ,'04/12/2014 16:00:00'),
(1  ,'04/13/2014 18:00:00'),
(2  ,'04/11/2014 13:00:00'),
(2  ,'04/12/2014 15:00:00'),
(2  ,'04/12/2014 16:00:00')

查询1

select T.Id,
       min(T.Date) as Date1,
       case when count(*) = 2 then max(T.Date) end as Date2
from (
     select T.Id,
            T.Date,
            (1 + row_number() over(partition by T.Id order by T.Date)) / 2 as rn
     from T
     ) as T
group by T.Id, T.rn
order by T.Id, T.rn

<强> Results

| ID |                        DATE1 |                        DATE2 |
|----|------------------------------|------------------------------|
|  1 | April, 09 2014 13:00:00+0000 | April, 10 2014 15:00:00+0000 |
|  1 | April, 12 2014 16:00:00+0000 | April, 13 2014 18:00:00+0000 |
|  2 | April, 11 2014 13:00:00+0000 | April, 12 2014 15:00:00+0000 |
|  2 | April, 12 2014 16:00:00+0000 |                       (null) |

答案 1 :(得分:1)

SQL Fiddle

MS SQL Server 2008架构设置

create table T
(
  Id int,
  Date datetime
)

go

insert into T values
(1  ,'04/09/2014 13:00:00'),
(1  ,'04/10/2014 15:00:00'),
(1  ,'04/12/2014 16:00:00'),
(1  ,'04/13/2014 18:00:00'),
(2  ,'04/11/2014 13:00:00'),
(2  ,'04/12/2014 15:00:00'),
(2  ,'04/12/2014 16:00:00')

查询1

select T1.Id,
       T1.Date as Date1,
       T3.Date2
from T as T1
    outer apply (
                select top(1) T2.Date
                from T as T2
                where T1.Date < T2.Date and
                      T1.Id = T2.Id
                order by T2.Date
                ) as T3(Date2)

<强> Results

| ID |                        DATE1 |                        DATE2 |
|----|------------------------------|------------------------------|
|  1 | April, 09 2014 13:00:00+0000 | April, 10 2014 15:00:00+0000 |
|  1 | April, 10 2014 15:00:00+0000 | April, 12 2014 16:00:00+0000 |
|  1 | April, 12 2014 16:00:00+0000 | April, 13 2014 18:00:00+0000 |
|  1 | April, 13 2014 18:00:00+0000 |                       (null) |
|  2 | April, 11 2014 13:00:00+0000 | April, 12 2014 15:00:00+0000 |
|  2 | April, 12 2014 15:00:00+0000 | April, 12 2014 16:00:00+0000 |
|  2 | April, 12 2014 16:00:00+0000 |                       (null) |