我想在sql中获取最新记录

时间:2014-02-11 13:57:05

标签: sql sql-server join inner-join aggregate-functions

我有两个表Employee和Transaction:

员工: enter image description here

反式:

enter image description here

现在我希望从Transaction获取最新记录,其中该记录的execeution标志为0,事务中的employee应该等于employee表中的empshortid。

输出:

1497163 SKANNAN27 0 2012-02-08 19:13:33.840

1498704 AETHODE 0 2012-02-08 18:45:08.380

我不会得到其他记录,因为对于其他记录,如果我们采用max transdate记录,则执行标志为“1”。如上面的输出我有很多记录应该检索所有。

请指导我如何实现这一目标。

4 个答案:

答案 0 :(得分:3)

使用最新TransSQL Fiddle)获取TransDate表格中的最后一条记录:

SELECT TOP(1) e.EmployeeID, e.EmpShortID, t.ExecutionFlag, t.TransDate
FROM Employee AS e
INNER JOIN Trans AS t ON t.Employee = e.EmpShortID
WHERE t.ExecutionFlag = 0
ORDER BY t.TransDate DESC

编辑,以获取Trans表格中的最后一条记录,其中包含每位员工的最新TransDateSQL Fiddle):

SELECT e.EmployeeID, e.EmpShortID, t.ExecutionFlag, MAX(t.TransDate)
FROM Employee AS e
INNER JOIN Trans AS t ON t.Employee = e.EmpShortID
WHERE t.ExecutionFlag = 0
GROUP BY e.EmployeeID, e.EmpShortID, t.ExecutionFlag

编辑,以下查询检索Trans表中的最后一条记录,其中包含每位员工的最新TransDate,无论ExecutionFlag如何。然后它会获取这些结果并仅提取ExecutionFlag =0SQL Fiddle):

所在的记录
SELECT m.*
FROM
(
  SELECT e.EmployeeID, e.EmpShortID, MAX(t.TransDate) AS MaxTransDate
  FROM Employee AS e
  INNER JOIN Trans AS t ON t.Employee = e.EmpShortID
  GROUP BY e.EmployeeID, e.EmpShortID
) AS m
INNER JOIN Trans AS tm ON
m.EmpShortID = tm.Employee AND
m.MaxTransDate = tm.TransDate
WHERE tm.ExecutionFlag = 0

答案 1 :(得分:1)

非常简单的查询。假设dbo架构:

SELECT TOP 1 * 
FROM dbo.Transaction T
INNER JOIN dbo.Employee E
ON T.Employee = E.EmpshortID
WHERE T.ExecutionFlag = 0
ORDER BY T.TransDate DESC

请参阅SQLFiddle

编辑:为每位员工更改:

SELECT * 
FROM dbo.Transaction T
INNER JOIN dbo.Employee E
ON T.Employee = E.EmpshortID
WHERE T.ExecutionFlag = 0
ORDER BY T.TransDate DESC

答案 2 :(得分:0)

SELECT TOP 1
    *
FROM Employee AS emp
INNER JOIN Transaction AS tran 
    ON tran.Employee = emp.EmpShortID
WHERE tran.ExecutionFlag = 0
ORDER BY TransDate DESC

答案 3 :(得分:0)

有些喜欢吗?

 Select top1 from Employee, Transaction 
    where Employee.EmployeeID = Transaction.EmployeeID 
    and ExecutionFlag=0
    order by TransDate desc;