【问题标题】:Use CASE statements with PARTITION in sql在 sql 中使用带有 PARTITION 的 CASE 语句
【发布时间】:2016-10-01 18:09:03
【问题描述】:

鉴于以下table_a

 id  | status | reg_date | so_date
 ----+------------------------------
  1  |   abc  | 15-11-01 | 15-11-02 
  1  |   def  | 15-11-01 | 15-11-04
  1  |   abc  | 15-11-01 | 15-11-06
  2  |   abc  | 15-11-01 | 15-11-03
  2  |   abc  | 15-11-01 | 15-11-04
  2  |   abc  | 15-11-01 | 15-11-06
  2  |   abc  | 15-11-01 | 15-11-08
  3  |   xyz  | 15-11-01 | 15-11-03
  3  |   def  | 15-11-01 | 15-11-08
  3  |   def  | 15-11-01 | 15-11-09

以下是必需的: 对于每组id,如果status 是“abc”,则so_datereg_date 之间的最小差异。这会产生下表:

 id  | min_date  
 ----+----------
  1  |    1   
  2  |    2   
  3  |   Null  

下面的代码就足够了:

select 
    id,
    distinct datediff('day', reg_date, min(so_date) over (partition by id)) as min_date
from table_a  
where status ilike '%abc%'

但是,由于其他“选择”的限制,在基表中使用过滤器where status ilike '%abc%' 是不可行的。我尝试使用

 select 
        id,
        case when status is like '%abc%' then (distinct datediff('day', reg_date, min(so_date) over (partition by id))) end as min_date
    from table_a  

但这不起作用。任何见解/建议将不胜感激。谢谢

【问题讨论】:

    标签: sql case partitioning where-in


    【解决方案1】:

    根据你的样本应该是

    select 
        id
      , min (datediff( so_date, reg_date )) as min_date
    from table_a 
    where status ='abc'
    group by id
    

    如果你不想要蝙蝠案例,那么

    select 
       case status when 'abc' then  id end
      , case status when 'abc' then min (datediff( so_date, reg_date ))  end as min_date
    from table_a 
    group by id
    

    【讨论】:

    • 谢谢。但是,根据问题中的要求,有没有办法在不使用基表中的 where status = 'abc' 过滤器的情况下对此进行编码?
    • 你想如何过滤 abc 的行?为什么你不想要 =
    • 无论如何我已经用案例更新了答案(避免在哪里)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    相关资源
    最近更新 更多