-1

我有这样的桌子

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
4

1 回答 1

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 与演示

然而,在某些情况下,这可能是不稳定的,例如丢失数据、多天等。只有在查看实时数据时才能确定。

此外,如前所述,设计可能存在更多基本问题,例如将时间与不需要的日期分开存储。如果您有一个指示哪一行进/出的标志,那也会更容易。

于 2013-02-21T14:37:06.040 回答