2013-02-21 60 views
-1

我有這樣的n行到n/2 colums:sqlserver的

insert into attn (StaffNo, ADate, ATime) values ('12345', '12-02-2013', 09.10) 
insert into attn (StaffNo, ADate, ATime) values ('12345', '12-02-2013', 10.03) 
insert into attn (StaffNo, ADate, ATime) values ('12345', '12-02-2013', 10.40) 
insert into attn (StaffNo, ADate, ATime) values ('12345', '12-02-2013', 17.30) 

我想在這個格式表

輸出:

 StaffNo  ADate  InTime  OutTime 
     12333,  12-02-2013  09.10  10.03 
     12333,  12-02-2013  10.40  17.30 
+2

看起來像是使用字符串/文本/ varchar列來處理時態數據。這是一個壞主意。 – 2013-02-21 14:02:36

+0

這是否意味着格式化輸出..? – SenthilPrabhu 2013-02-21 14:05:22

回答

1

像這樣的事情會爲工作您的樣品行:

with attnJoin as 
(
    select attn.StaffNo 
    , attn.ADate 
    , InTime = attn.ATime 
    , OutTime = prev.ATime 
    , eventNumber = row_number() over (partition by attn.StaffNo, attn.ADate order by attn.ATime) 
    from attn 
    outer apply 
    (
    select top 1 ATime 
    from attn prev 
    where attn.StaffNo = prev.StaffNo 
    and attn.ADate = prev.ADate 
    and attn.Atime < prev.ATime 
    order by ATime 
) prev 
) 
select StaffNo 
    , ADate 
    , InTime 
    , OutTime 
from attnJoin 
where eventNumber % 2 = 1 

SQL Fiddle with demo

然而,在某些情況下,這可能是片狀的。缺少數據,多天等等。只有當你查看你的實時數據時你才能確定。另外,如前所述,設計中可能存在更多的基本問題,例如將時間與不需要的日期分開存儲。如果你有一個標誌表示哪一行是進/出,那也會更容易。