【问题标题】:Is it possible to query multiple records from the same most recent date是否可以从同一最近日期查询多条记录
【发布时间】:2018-06-14 15:15:41
【问题描述】:

我有一个返回以下结果的查询

Date        Type          
6/7/18      R104            
6/7/18      Sunset         
6/7/18      Rabbit-T          
6/7/18      Sunset         
6/8/18      R104            
6/8/18      S400           
6/9/18      Singer        
6/9/18      Sunset          
6/9/18      Rabbit-M      
6/9/18      Sunset         
6/9/18      Sunset         

无论记录是什么,是否可以只提取最近日期(此处为 2018 年 6 月 9 日)的记录?

这是我的查询

 SELECT   
 ot.sale_date AS "Sale Date"  
 , otr.type_33 AS "Type"  
 , ide.s_style AS "Style"  
 , att.att_color AS "Color"  



FROM 
SYSTEM.order_tracking as ot
LEFT OUTER JOIN SYSTEM.order_type as otr
on ot.clientID=otr.clientID and ot.salesperiod=otr.salesperiod and 
ot.CUSTHBDT_UID=otr.CUSTHBDT_UID
LEFT OUTER JOIN SYSTEM.item_descriptions_East as ide 
on otr.clientID=ide.clientID and otr.salesperiod=ide.salesperiod and 
otr.CUSTHBDU_UID=ide.CUSTHBDU_UID
LEFT OUTER JOIN SYSTEM.attributes as att 
on ide.clientID=att.clientID and ide.salesperiod=att.salesperiod and 
 ide.CUSTHBDV_UID=att.CUSTHBDV_UID



WHERE
ot.access_code = '1'

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。包含您正在使用的查询也很好。
  • ORDER BY "Date" DESC FETCH FIRST 1 ROW WITH TIES
  • 试过了。我的程序不喜欢 FETCH 或前 1 行

标签: sql


【解决方案1】:

您可以使用子查询来过滤表中可用的最新日期记录

select *
from table
where date = (select max(date) from table)

记得在table(date) 上建立索引以加快检索速度。


这应该适用于大多数 DBMS,即使是那些不支持的:

  • rank()这样的分析函数
  • TOP n WITH TIES

【讨论】:

    【解决方案2】:

    如果你的数据库支持RANK,那么你可以试试这个:

    SELECT Date, Type
    FROM
    (
        SELECT *, RANK() OVER (ORDER BY Date DESC) rank
        FROM yourTable
    ) t
    WHERE rank = 1;
    

    此选项在您需要打破平局的情况下为您提供了一些灵活性。在这种情况下,您可以简单地将另一个级别的排序添加到与RANK 一起使用的ORDER BY 子句。

    【讨论】:

    • 我添加了我的查询。怎么会适合那里?
    【解决方案3】:

    我最终使用了

    WHERE   
    having date=max(date)  
    

    成功了

    【讨论】:

    • 您应该将其他答案标记为正确,而不是发布您自己的答案。
    • 我提出的解决方案不起作用吗?使用 HAVING 进行比较而不使用 group by 和用于非聚合是一种棘手的方法,人们应该了解它带来了什么。
    • 抱歉,没有。当我尝试提交时,它要求提供标识符
    猜你喜欢
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多