【问题标题】:Is there a better way to write this SQL query?有没有更好的方法来编写这个 SQL 查询?
【发布时间】:2009-07-31 22:33:43
【问题描述】:

我希望返回具有最大 create_dt 的行。这工作正常,但是我想知道是否有更合适的方法来做到这一点?

select * from 
table1 
where job_no='101047' 
and 
create_dt in
     (select max(create_dt) from    
      table1 where job_no='101047')

【问题讨论】:

  • 你没有提到哪种数据库技术。

标签: sql-server tsql


【解决方案1】:

怎么样:

Select top 1 *
from table1
where job_no = '101047'
order by create_dt desc

【讨论】:

  • Select top 1 * from table 1 where job_no = '101047' order by create_dt desc
  • 谢谢。看起来我在你有机会纠正我之前就纠正了。 :)
  • +1 我喜欢这个,我可以使用 asc 获取最小日期。谢谢先生。我不喜欢嵌套查询。
【解决方案2】:

如果 create_dt 存在多行,您的查询将返回多个值
其中job_no = '101047'

这样会更好

 Select top 1 * from table1 
 where job_no='101047'   
 order by create_dt desc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多