-1

我需要完成任务,但不太想象如何实施。我在 SQL Server 数据库中有以下列的表:

ID     Start    End      Time       Ostart    OEnd  
1       111     222   01-01-2013     111      555  
1       222     333   02-01-2013     111      555  
1       333     444   03-01-2013     111      555
1       444     555   04-01-2013     111      555
1       444     555   01-01-2013     444      666  
1       555     666   02-01-2013     444      666  

我想从 Start 到 End 取一个中间点,直到 End 不等于 OEnd 并放在一行。对于此示例,结果表应包含 2 行:对于 111 - 555 Ostart-OEnd,中间点为 222-333-444 和 444-666 Ostart-Oend,中间点为 555。中间点的最大计数为 5。所以结果表是这样的:

 ID     OStart   OEnd     Time      Point1     Time1      Point2    Time2      Point3   Point4   Point5  
 1       111     555   01-01-2013     222    02-01-2013    333    03-01-2013    444      
 1       444     666   01-01-2013     555    02-01-2013    

我怎样才能得到这样的结果表?

4

1 回答 1

1

您可以使用 PIVOT 函数将结果从多行值中获取到多列中。如果您应用row_number()窗口函数,那么您可以获得点值 1-5:

select id, ostart, oend, Point1, Point2, Point3, Point4, Point5
from
(
  select id, [end], ostart, oend,
    'Point'
      +cast(row_number() over(partition by id, ostart 
                              order by start) as varchar(10)) seq
  from yourtable
) d
pivot
(
  max([end])
  for seq in (Point1, Point2, Point3, Point4, Point5)
) piv;

请参阅SQL Fiddle with Demo

如果要在两列上进行 PIVOT,则需要先取消透视,然后再旋转数据:

select id, ostart, oend, 
  Point1, Time1, Point2, Time2, 
  Point3, Time3, Point4, Time4, Point5, Time5
from
(
  select id, ostart, oend, col+cast(seq as varchar(10)) col,
    value
  from
  (
    select id, [end], time, ostart, oend,
      cast(row_number() over(partition by id, ostart 
                                order by start) as varchar(10)) seq
    from yourtable
  ) src
  cross apply
  (
    select 'Time', convert(varchar(10), time, 120) union all
    select 'Point', cast([end] as varchar(10))
  ) c (col, value)
) d
pivot
(
  max(value)
  for col in (Point1, Time1, Point2, Time2, 
              Point3, Time3, Point4, Time4, Point5, Time5)
) piv;

请参阅带有演示的 SQL Fiddle

于 2013-06-22T15:09:38.203 回答