2013-06-22 22 views
-1

我需要完成任务,但不太想象如何实现。 我在SQL Server数据库中的表列如下: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 

我想借此从开始的中间点结束,直到结束不等于OEnd,把一排。对于这个例子,结果表应该有2行:for 111 - 555 Ostart-OEnd with 222-333-444 and 444-666 Ostart-Oend with intermidiate point 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  

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

+1

重读这一点,为什么它在MySQL类别?它应该是MS SQL Server吗? –

+0

如果没有OP的说明,不应假定它是错误标记的。 –

+0

在说明中,他说SQL Server,列的命名约定看起来像SQL Server。 –

回答

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

如果你想支点上两列,那么你就需要逆转置,然后转动数据:

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 with Demo

+0

非常感谢!这是我需要的。你能告诉我如何跳过最后一点?因为现在它将OEnd值放在那里。我只需要中间点。 – Alexander

+0

'from yourtable'后加'WHERE [end] <> oend' –

+0

Thanks.One更多的问题。我怎样才能在多列上旋转?例如也添加TIME列。 – Alexander

相关问题