如何从sql server中的行计算数据?

时间:2014-01-13 20:56:50

标签: sql sql-server

我有一张如下表:

datatime      in_out     
---------------------
08:00         IN
08:30         OUT
09:30         OUT
10:00         IN
10:30         OUT  

在SQL服务器查询后有没有机会得到这样的东西:

IN       OUT
---------------
08:00    08:30
NULL     09:30
10:00    10:30

我花了大约2个星期才找到解决方案。我是初学者。单一解决方案是minmax,但它对我没有帮助。

2 个答案:

答案 0 :(得分:1)

这将使用row_numbering解决它:

with Ordered as (
    select *, rn = row_number() over (order by datatime)
    from Input
)
select
    [In] = o_in.datatime
,   [Out] = o_out.datatime
from Ordered o_out
 left join Ordered o_in
   on o_in.rn = o_out.rn - 1
  and o_in.in_out = 'IN'
where o_out.in_out = 'OUT'

答案 1 :(得分:0)

猜猜我回答有点慢,但这是我使用内部查询得到的:

select
  (select top 1 
     IIF(a.in_out = b.in_out, null, datatime)
   from clk b 
   where a.datatime > b.datatime 
   order by b.datatime desc
  ) as [IN],
  a.datatime as [OUT]
from clk a
where a.in_out = 'OUT'

注意:这样做会“向前或向后”跳过空行,具体取决于它的实现方式......