2014-03-07 59 views
0

我想写查询,并与一个card_nr工作正常。例如:返回列表值与功能

Declare @card_nr as nvarchar(50) 

set @card_nr = '704487442952000472' 

select 
    a.times, b.times 
from 
    (select 
     stat_id, times 
    from info 
    where card_nr = @card_nr) as a 
left outer join 
    (select 
     stat_id, times 
    from info 
    where card_nr = @card_nr) as b on a.stat_id = b.stat_id+1 

而且我得到了正确的结果:

2014-02-04 11:20:00.000 NULL 
2014-02-06 09:44:00.000 2014-02-04 11:20:00.000 
2014-02-12 09:59:00.000 2014-02-06 09:44:00.000 
2014-02-13 10:31:00.000 2014-02-12 09:59:00.000 
2014-02-21 09:49:00.000 2014-02-13 10:31:00.000 

我想这样做,每card_nr从表列表。所以,首先我写的函数:

alter FUNCTION tabletest 
    (@card_nr as nvarchar(50)) 
RETURNS smalldatetime 
AS BEGIN 
    Declare @sqldata as smalldatetime 

    select 
     @sqldata = b.times 
    from 
     (select 
      stat_id, times 
     from info where card_nr = @card_nr) as a 
    left outer join 
     (select 
      stat_id, times 
     from info where card_nr = @card_nr) as b on a.stat_id = b.stat_id + 1 

    RETURN @datas 
END 

我试图选择我的查询功能后:

select name, times, dbo.tabletest(card_nr) 
from dbo.info 

而且我得到不正确的结果:

User1 2014-02-04 11:20:00.000 2014-02-21 09:49:00 
User1 2014-02-06 09:44:00.000 2014-02-21 09:49:00 
User1 2014-02-12 09:59:00.000 2014-02-21 09:49:00 
User1 2014-02-13 10:31:00.000 2014-02-21 09:49:00 
User1 2014-02-21 09:49:00.000 2014-02-21 09:49:00 
User2 2014-02-14 13:41:00.000 2014-02-28 12:20:00 
User2 2014-02-24 11:46:00.000 2014-02-28 12:20:00 
User2 2014-02-28 12:20:00.000 2014-02-28 12:20:00 

我想得到这个:

User1 2014-02-04 11:20:00.000 NULL 
User1 2014-02-06 09:44:00.000 2014-02-04 11:20:00.000 
User1 2014-02-13 10:31:00.000 2014-02-12 09:59:00.000 
User1 2014-02-13 10:31:00.000 2014-02-12 09:59:00.000 
User1 2014-02-21 09:49:00.000 2014-02-13 10:31:00.000 
User2 2014-02-14 13:41:00.000 NULL 
User2 2014-02-24 11:46:00.000 2014-02-14 13:41:00.000 
User2 2014-02-28 12:20:00.000 2014-02-24 11:46:00.000 

回答

0

它应该b é可能得到所需的结果只使用表信息:

select name, times, 
(select max(times) from info i2 where i2.times<i1.times and i1.name=i2.name and [email protected]_nr) 
from info i1 
where [email protected]_nr 
+0

我会尝试它,但如果我想使用的功能。什么是正确的功能和查询? –

+1

我不想使用一个函数,它们(至少是标量)有时可能会变慢。作为一个经验法则,如果你可以用“普通”sql做到这一点。 – jean

+0

@jean同意,如果可能,我会避免函数调用 – Jayvee