从查询中获取最新记录

Get the lastest record from the query

我有一个查询,它在 sql 中给了我 5 条记录,但我想显示一条最新的记录。

下面是我的查询

Select a.mkey, c.type_desc DOC_TYPE, a.doc_no INWARD_NO,  
 convert(varchar, a.doc_date,103)date, 
 a.to_user, a.No_of_pages, Ref_No, d.type_desc DEPT_RECEIVED,  b.first_name    + ' ' + 
 b.last_name EMP_RECEIVED, b.first_name + ' ' + b.last_name NAME, 
 b.email 
  from inward_doc_tracking_hdr a , user_mst b ,type_mst_a c,
    type_mst_a d 
 where a.to_user = b.mkey  and a.doc_type = c.master_mkey  
 and a.dept_received = d.Master_mkey   and a.to_user = '1260'

结果如下

[![查询][1]][1]

我正在使用 sql-server-2005

我试过 TOP1 但它没有给我最新的记录

您需要在查询中加入 ORDER BY。如果没有 ORDER BY 子句,则无法保证 TOP 命令会 return 预期结果:

SELECT TOP 1
    <column_list>
FROM ....
ORDER BY a.doc_date DESC

另外,你应该avoid using the old-style JOIN syntax.

试试这个查询:

SELECT TOP 1 a.mkey, c.type_desc DOC_TYPE, a.doc_no INWARD_NO,  
 convert(varchar, a.doc_date,103)date, 
 a.to_user, a.No_of_pages, Ref_No, d.type_desc DEPT_RECEIVED,  b.first_name    + ' ' + 
 b.last_name EMP_RECEIVED, b.first_name + ' ' + b.last_name NAME, 
 b.email 
  from inward_doc_tracking_hdr a , user_mst b ,type_mst_a c,
    type_mst_a d 
 where a.to_user = b.mkey  and a.doc_type = c.master_mkey  
 and a.dept_received = d.Master_mkey   and a.to_user = '1260'
 ORDER BY a.doc_date DESC