2

我需要帮助来创建满足此要求的 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

有什么建议么?

4

5 回答 5

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

于 2012-09-26T04:55:48.377 回答
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;

您可以在 SQL Fiddle 上进行测试

于 2012-09-26T06:11:05.643 回答
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
于 2012-09-26T04:42:56.603 回答
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”,根据日期字段返回上一行,并检查员工是否来自同一部门

于 2012-09-26T05:31:42.527 回答
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
于 2012-09-26T05:07:27.867 回答