选择Sql row to field

时间:2015-08-22 14:35:11

标签: sql sql-server tsql

我在表格中有这些数据:

RowID   PerID      Date       Time     RowNumber
------------------------------------------------
2393    1856    2015-07-29  00:52:55    1
2408    1856    2015-07-29  19:13:32    2
2394    1864    2015-07-29  00:57:17    1
2399    1864    2015-07-29  11:07:26    2
2403    1864    2015-07-29  15:25:42    3
2406    1864    2015-07-29  19:06:37    4
2395    1877    2015-07-29  01:10:23    1
2407    1877    2015-07-29  19:13:26    2
2409    1881    2015-07-29  19:13:52    1
2391    1882    2015-07-29  00:32:15    1
2396    1882    2015-07-29  11:05:51    2
2397    1882    2015-07-29  11:05:53    3
2398    1882    2015-07-29  11:06:01    4
2401    1882    2015-07-29  15:20:16    5
2404    1882    2015-07-29  19:04:07    6
2392    1883    2015-07-29  00:35:50    1
2400    1883    2015-07-29  11:17:30    2
2402    1883    2015-07-29  15:24:10    3
2405    1883    2015-07-29  19:06:20    4

我想从上面的数据创建这个数据表:

RowID       PerID       io_num      ioDate          InTime          OutTime
----------------------------------------------
1           1856        1           2015-07-29      00:52:55        19:13:32
2           1864        1           2015-07-29      00:57:17        11:07:26
3           1864        2           2015-07-29      15:25:42        19:06:37
4           1877        1           2015-07-29      01:10:23        19:13:26
5           1881        1           2015-07-29      19:13:52        null
6           1882        1           2015-07-29      00:32:15        11:05:51
7           1882        2           2015-07-29      11:05:53        11:06:01
8           1882        3           2015-07-29      15:20:16        19:04:07
9           1883        1           2015-07-29      15:24:10        11:17:30
9           1883        2           2015-07-29      00:35:50        19:06:20

请帮帮我 谢谢

1 个答案:

答案 0 :(得分:1)

SQL FIDDLE DEMO

WITH calc_time as (
    SELECT 
        t1.PerID, 
        t1.Date ioDate,
        t1.Time InTime,
        t2.Time OutTime
    FROM mytable t1 left join
         mytable t2 on 
              t1.PerId =  t2.PerID
          and t1.RowNumber = t2.RowNumber - 1
    WHERE 
         (t1.RowNumber % 2) = 1
)
SELECT
     ROW_NUMBER() OVER(ORDER BY PerID) AS RowID, 
     c.PerID, 
     ROW_NUMBER() OVER(Partition BY PerID ORDER BY ioDate, InTime) AS io_num,
     c.ioDate,
     c.InTime,
     c.OutTime
 FROM
     calc_time c