【问题标题】:Select less nearest date from table [group by and order by]从表中选择较短的日期 [group by and order by]
【发布时间】:2023-02-06 01:11:56
【问题描述】:

我正在尝试为每个组 Type,Subtype,s_stype,category_id 找到最近的日期,如果没有找到日期,则使用默认值

样本数据 :

Type subtype s_stype category_Id date
1 1 1 211 20000000
1 1 1 211 30000000
1 1 2 211 20000000
1 1 2 211 20000000
1 1 3 211 null
1 1 2 311 50000000
1 1 2 311 40000000
1 1 2 311 null

例如 : 输入日期 = 25000000

Select * from Table  where date<=input_date or date is null 
group by Type,Subtype,s_stype,category_id 
order by date desc

查询应为每种类型、子类型、s_stype、类别采用较短的最近日期

喜欢..

Type subtype s_stype category_Id date
1 1 1 211 20000000
1 1 2 211 20000000
1 1 3 211 null
1 1 2 311 null

查询应该给出上面的结果,而不是给出不正确的行,该行采用满足给定组条件的 where 条件的第一行

因为我使用过 mysql 5.7,所以我需要没有像上面那样的窗口函数解决方案的解决方案

【问题讨论】:

    标签: mysql sql database rdbms


    【解决方案1】:

    删除 WHERE 子句并使用条件聚合:

    SELECT Type, Subtype, s_stype, category_id,
           COALESCE(MAX(CASE WHEN date <= input_date THEN date END), default_date) AS date  
    FROM tablename  
    GROUP BY Type, Subtype, s_stype, category_id 
    ORDER BY date DESC;
    

    default_date 替换为所需的默认日期。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 2012-09-29
      • 2011-06-28
      相关资源
      最近更新 更多