简体   繁体   English

在表中有效查找最后日期-Teradata SQL

[英]Efficiently find last date in a table - Teradata SQL

Say I have a rather large table in a Teradata database, "Sales" that has a daily record for every sale and I want to write a SQL statement that limits this to the latest date only. 假设我在Teradata数据库中有一个相当大的表,“销售”具有每笔销售的每日记录,我想编写一条SQL语句将其限制为最新日期。 This will not always be the previous day, for example, if it was a Monday the latest date would be the previous Friday. 例如,如果今天不是星期一,那么最近的日期将是前一个星期五。

I know I can get the results by the following: 我知道我可以通过以下方法得到结果:

SELECT s.*
FROM Sales s
JOIN (
      SELECT MAX(SalesDate) as SalesDate 
      FROM Sales
) sd 
ON s.SalesDate=sd.SalesDt

I am not knowledgable on how it would process the subquery and since Sales is a large table would there be a more efficient way to do this given there is not another table I could use? 我对如何处理子查询不了解,并且由于Sales是一个大表,如果没有我可以使用的其他表,将有一种更有效的方法来做到这一点?

That is probably fine, if you have an index on salesdate . 如果您具有salesdate的索引,那可能很好。

If there is only one row, then I would recommend: 如果只有一行,那么我建议:

select top 1 s.*
from sales s
order by salesdate desc;

In particular, this should make use of an index on salesdate . 特别是,这应该利用salesdate的索引。

If there is more than one row, use top 1 with ties . 如果有多于一行,则将top 1 with ties

Another (more flexible) way to get the top n utilizes OLAP-functions: 获得前n名的另一种(更灵活的)方法是利用OLAP函数:

SELECT *
FROM Sales s
QUALIFY
  RANK() OVER (ORDER BY SalesDate DESC) = 1

This will return all rows with the max date. 这将返回具有最大日期的所有行。 If you want only one of them switch to ROW_NUMBER. 如果只希望其中一个切换到ROW_NUMBER。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM