【问题标题】:SQL Cross join to use max value for calculation in a case statement without group bySQL交叉连接在没有分组依据的case语句中使用最大值进行计算
【发布时间】:2018-07-07 04:05:42
【问题描述】:

我有下表:

|BoreholeID|Mins|
-----------------
|BH1       |0.5 |
|BH1       |1   |
|BH1       |1.5 |

并且我想选择名为时间线的第三列,它有一个 case 语句,如果 mins 值大于 max mins 值的 80% 并且如果 mins 值大于 max mins 值减去,则返回 1 5. 我有以下查询:

select boreholeid, mins,
(case when mins < (max(max_query.maxts)*0.8) and
mins<(max(max_query.maxts)-5) then 1 else 0 end) as Timeline
from maxrawcalcs
cross join
(select max(maxrawcalcs.mins) maxts from maxrawcalcs) as max_query  
;

我过去曾使用交叉连接来使用这样的最大值,它没有问题,但这个查询告诉我,我需要对其他两个我不使用的选定字段使用分组查询想要做。如何使用 group by?

【问题讨论】:

    标签: sql amazon-web-services amazon-athena presto


    【解决方案1】:

    我使用了嵌套 SQL 并保持您的逻辑如下:

    select q.boreholeid, q.mins,
          (case when q.mins > ((q.maxts)*0.8) and
                     q.mins > ((q.maxts)-5) 
           then 1 else 0 
           end )         as Timeline
      from
    (
    select boreholeid, mins, 
           (select max(mins) maxts from maxrawcalcs) as maxts
      from maxrawcalcs
    ) q;
    
    boreholeid  mins    Timeline
         BH1     0.5        0
         BH1      1         0
         BH1     1.5        1
    

    SQL Fiddle Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多