【问题标题】:How to conditionally aggregate a value in a select statement?如何有条件地聚合 select 语句中的值?
【发布时间】:2022-12-07 08:27:21
【问题描述】:

我需要有条件地能够在子选择中获取最小日期值,但是我无法这样做,因为查询希望我将值包含在我的 group by 语句中。

我有一个从子选择中选择的选择语句:

SELECT DISTINCT
  Begin_Date
FROM 
(
  SELECT DISTINCT 
    CASE WHEN (id IS NOT NULL) THEN MIN (start_date)
         ELSE initial_date 
    END AS Begin_Date
  FROM ... 
)
GROUP BY
  Begin_Date

上面的查询不允许我按 begin_date 分组,因为我在子选择中有 MIN 聚合,但是如果 id 不为空,我仍然需要一种方法来获取最小值 start date,或者如果 id 为空,则为非聚合 initial_date

有没有办法解决?

【问题讨论】:

  • 在寻求 SQL 帮助时,minimal reproducible example 是一个很好的开始。
  • 使用两个单独的查询,一个用于空 ID,另一个用于非空 ID。然后将它们与 UNION 结合起来。

标签: mysql sql subquery aggregate-functions


【解决方案1】:

在子选择中,但是我仍然需要一种方法来获取最小值 start_date 如果 id 不为空,或者如果 id 为空则获取非聚合的 initial_date

它看起来像一个窗户min 会做你想做的。假设 MySQL 8.0:

select begin_date, ...
from (
    select case 
        when id is null then initial_date
        else min(start_date) over() 
    end as begin_date
    from ...
) t
group by begin_date

子查询不聚合,而是根据你描述的规则计算出新的begin_date;然后你可以在外部查询中group by

旁注:在 null ids 上,这为您提供了最早的 start_date整张桌子;您可以在over() 子句中添加partition by 来限制要搜索的行的范围。

【讨论】:

    猜你喜欢
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 2017-08-31
    • 1970-01-01
    • 2014-04-05
    相关资源
    最近更新 更多