case语句错误

kupeojn6  于 2021-07-27  发布在  Java
关注(0)|答案(4)|浏览(317)

我想用case语句编写一个select查询。要求以秒为单位获得col1和col2之间的时差,case语句如下:如果时差<60秒,则为low;如果diff>60,则为high end as range。
到目前为止我尝试的是:

select id, ((col1-col2)*24*60)*60 as diff_secs from table;

这给了我以秒为单位的差异,这是完美的。但为了合并案例陈述,我尝试了下面的方法,但不起作用。

select id, case when (((col1-col2)*24*60)*60) < 60 then low
                when (((col1-col2)*24*60)*60) > 60 then high
                then end as range
from tble;
xfyts7mz

xfyts7mz1#

通过内联视图可以实现:

select id,case when diff_secs < 60 then 'low' 
                when diff_secs > 60 then 'high'
           end as Range 
  from 
       (select id, ((col1-col2)*24*60)*60 as diff_secs 
        from table) 
  diff_secs_data

ps:查询不能处理等于60的数据,您可能需要根据您的要求进行修改。
编辑:要查找“高”和“低”记录的计数,使用附加的内联视图进行聚合就足够了。可以有多种方式,但我更喜欢使用内联视图,因为这样可以提供更好的可读性。

select Range,count(*)
 from 
 (select id,case when diff_secs < 60 then 'low' 
                when diff_secs > 60 then 'high'
           end as Range 
  from 
       (select id, ((col1-col2)*24*60)*60 as diff_secs 
        from table) 
  diff_secs_data) range_data
  group by Range;
mrfwxfqh

mrfwxfqh2#

除了小的拼写错误,我想说你可以把它改为:

select 
  id, 
  case when col1 < col2 + interval '1' minute then 'low'
       else 'high' 
  end as range
from tble;

参见db<>fiddle上的运行示例。

k75qkfdt

k75qkfdt3#

我认为你的代码应该有用,但我建议:

(case when col1 < col2 + interval '1' minute then 'low'
      when col1 > col2 + interval '1' minute then 'high'
 end)
llycmphe

llycmphe4#

如果您确实在使用teradata(您还标记了oracle),可以使用别名将其简化:

SELECT id, (((col1-col2)*24*60)*60) AS time_diff,
  CASE 
    WHEN time_diff < 60 THEN 'low'
    WHEN time_diff > 60 THEN 'high'
  END AS range
from tble;

您可能还希望通过向case表达式中的一个操作数添加“=”来说明时差正好为60的情况。

相关问题