获取sql中的上一行

时间:2012-09-26 04:33:08

标签: mysql sql

我需要帮助为这个要求创建sql - 我有一个表中的数据:

Empid      Date         Deptid  Location
-----------------------------------------
001    1st Jan 2012    101      BC
002    4th Jan 2012    101      AB
003    6th Jan 2012    103      PQ
004    8th Jan 2012    104      AB
005    10th jan 2012   105      XY

现在我想获取前一行(取决于date字段),其中位置为AB且dept值不同。在上面的示例中,应该提取以下行

003    6th Jan 2012    103      PQ

有什么建议吗?

5 个答案:

答案 0 :(得分:1)

假设SQL Server 2005 +

SELECT * FROM(
SELECT *

FROM(SELECT *,Row_Number() OVER(Order By [Date]) From <Your table>)X

WHERE X.[Date] = '8th Jan 2012' AND Location = 'AB')X WHERE Rn = Rn-1

答案 1 :(得分:1)

SELECT * FROM `YOUR_TABLE`
WHERE `id` < (SELECT `id` FROM `YOUR_TABLE`
              WHERE `location` =  'AB'
              AND `deptid` =  '104') 
ORDER BY id DESC LIMIT 1

这可能会对你有所帮助:D

答案 2 :(得分:1)

create table tblTest (
  Empid char(3)
  ,Date date
  ,Deptid char(3)
  ,Location char(2)
);

insert into tblTest (Empid,Date,Deptid,Location) values ("001","2012/01/01","101","BC");
insert into tblTest (Empid,Date,Deptid,Location) values ("002","2012/01/04","101","AB");
insert into tblTest (Empid,Date,Deptid,Location) values ("003","2012/01/06","103","PQ");
insert into tblTest (Empid,Date,Deptid,Location) values ("004","2012/01/08","104","AB");
insert into tblTest (Empid,Date,Deptid,Location) values ("005","2012/01/10","105","XY");

SELECT
  t2.*
FROM
  tblTest t1
  LEFT JOIN tblTest t2 ON t1.Date<t2.date
                          AND
                          t1.Deptid <> t2.Deptid
WHERE
  t1.Empid = "002"
ORDER BY
  t2.Date
LIMIT 1;

You can test on SQL Fiddle

答案 3 :(得分:0)

使用此模式。实际上我觉得我搞砸了这个条件,应该是LastAB.DeptID!=Emp.DeptID,但你明白了。子查询为您提供了您想要开始的单一记录。外部查询然后在不同的位置(或DeptID或您设置的任何条件)中查找先前日期的记录,并使用ORDER BY + LIMIT 1来精确定位单个记录。

select Emp.*
from Emp
join (
  select *
  from Emp
  where Location = 'AB'
  order by Date desc
  limit 1) LastAB on LastAB.Date>Emp.Date
                 and LastAB.Location!=Emp.Location
order by Emp.Date desc
limit 1;

工作SQL Fiddle复制在

下面
create table Emp (
  Empid char(3),
  Date datetime,
  Deptid int,
  Location char(2)
  );
insert Emp values
('001', '2012-01-01', 101, 'BC'),
('002', '2012-01-04', 101, 'AB'),
('003', '2012-01-06', 103, 'PQ'),
('004', '2012-01-08', 104, 'AB'),
('005', '2012-01-10', 105, 'XY');

--- result

EMPID   DATE    DEPTID  LOCATION
003     January, 06 2012   103  PQ

答案 4 :(得分:0)

select * from table_name where Date < (select Date from table_name where Location="AB") and Deptid NOT IN( select Deptid from table_name where Location="AB") order by Date desc limit 1 ;

如果位置为“AB”,则返回基于日期字段的上一行,并检查该员工是否来自同一部门