选择涉及操纵日期的语句(最旧的 - 介于最近之间)

时间:2013-03-05 05:44:08

标签: sql-server select

enter image description here

我有这个表,主页上的用户将选择一个fa id,它将能够打印该特定数据的数据。现在我想要实现的是能够使用相同的FAID打印数据,例如是一个,并且无法获得6的用户ID(Eff_from = 2/3/2012),这是FAID的下一个日期= 1(Eff_to(2/2/2012)。

 $sql_exp = "SELECT top 1 b.LaptopID, b.Eff_to
FROM    dbo.users a
        INNER JOIN dbo.FA_Laptop b
            ON a.userID = b.UserID
WHERE b.LaptopID=
    (SELECT x.LaptopID 
    FROM FA_Laptop x
     WHERE x.FAID = $faidf) order by b.Eff_to desc, b.FAID"  

使用此代码我只能使用后面的FAID打印最新日期

1 个答案:

答案 0 :(得分:1)

试试这个: -

Declare @FA_Laptop table 
(FAID int,LaptopID int,userId int,Eff_from date,Eff_to date)

Insert into @FA_Laptop
values
(1,39,1,'1/1/2012','2/2/2012'),
(2,39,4,'5/5/2012','7/7/2012'),
(3,39,6,'2/3/2012','5/4/2012'),
(4,39,8,'7/8/2012','12/24/2012')

;with cte as
(
 Select FAID,LaptopID,userID,Eff_to
 from @FA_Laptop where FAID=1 //Get the value from your PHP page
)
Select c.faid,f.faid as nextFAID,c.userID,f.userId as nextUserID,c.laptopId,
f.laptopId as nextLaptopID from cte c  left join   @FA_Laptop f 
on f.Eff_from=dateadd(day,1,c.eff_to)

Result :

faid  nextFAID  userID    nextUserID    laptopId    nextLaptopID
 1      3             1      6            39               39

使用子查询

Select temp.faid,temp.userID,f.userId as nextUserID,temp.laptopId,
f.laptopId as nextLaptopID
from 
(
Select FAID,LaptopID,userID,Eff_to
from @FA_Laptop where FAID=1
) temp  
left join   @FA_Laptop f 
on f.Eff_from=dateadd(day,1,temp.eff_to)

更新:

SELECT  temp.LaptopID, temp.Eff_to,f.userId as nextUserID,
        f.laptopId as nextLaptopID
FROM    dbo.users a
inner join 
(
  Select FAID,LaptopID,userID,Eff_to
  from FA_Laptop where FAID=$faidf
) temp
on a.userID = temp.UserID
left join   FA_Laptop f 
on f.Eff_from=dateadd(day,1,temp.eff_to)

更新2:

检查sqlFiddle的结果

查询

SELECT  fl.userId as nextUserID,fl.eff_from,
        fl.laptopId as nextLaptopID
FROM  FA_Laptop f
inner join   FA_Laptop fl 
on fl.Eff_from=dateadd(day,1,f.eff_to) and f.faid=$faidf
inner join users a
on a.userID=fl.userID