如何获取一组(天的价值)数据的最大值的小时?

时间:2018-07-17 15:59:54

标签: sql oracle

假设我们已经计算出一天中售出的最大水果数量(存储在value列中)。我需要在time_of_day(即3:00 PM)时达到该最大值。我如何能够做到这一点而不必也按time_of_day分组(因为这样会导致分组失败)。以下是我将从以下内容开始的示例:

 Value        Data_date   Name      Hour
   7          7/17/2018    A        2:00 AM
  15          7/17/2018    A        4:00 AM
  25          7/17/2018    A        7:00 PM
  55          7/18/2018    B        1:00 AM
  17          7/18/2018    B        4:00 AM 

下面是我想要的:

  MAX(Value)  Data_date  Name     Hour
  25          7/17/2018   A       7:00 PM
  55          7/18/2018   B       1:00 AM

以下是我尝试过的内容:

select max(value)
     , data_date
     , name
     , hour
  from table
  group by value, grouping sets(data_date, name), grouping sets(hour, name);

根据我在网上挖出的内容,我认为我必须按组进行分组,但不能完全确定我需要对哪些组进行分组...

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用:

select t.*
from table t
where value = (select max(t1.value) 
               from table t1 
               where t1.name = t.name and
                     t1.data_date = t.data_date
              );

但是,您也可以使用row_number()函数:

select t.*
from (select *, row_number () over (partition by name, data_date order by value desc) as seq
      from table t
     ) t
where seq = 1;

答案 1 :(得分:2)

您可以执行以下操作:

select max(value) as value,
  data_date,
  max(name) keep (dense_rank last order by value) as name,
  max(hour) keep (dense_rank last order by value) as hour
from your_table
group by data_date;

对于每个data_date,它都使用简单的汇总以及相应的名称和小时数using last()获得最高价值。

将示例数据作为CTE,并使用您说过的数据类型:

-- cte for sample data
with your_table (value, data_date, name, hour) as (
            select  7, '7/17/2018', 'A', timestamp '2018-07-17 02:00:00' from dual
  union all select 15, '7/17/2018', 'A', timestamp '2018-07-17 04:00:00' from dual
  union all select 25, '7/17/2018', 'A', timestamp '2018-07-17 19:00:00' from dual
  union all select 55, '7/18/2018', 'B', timestamp '2018-07-18 01:00:00' from dual
  union all select 17, '7/18/2018', 'B', timestamp '2018-07-18 04:00:00' from dual
)
-- actual query
select max(value) as value,
  data_date,
  max(name) keep (dense_rank last order by value) as name,
  to_char(max(hour) keep (dense_rank last order by value), 'HH:MI AM') as hour
from your_table
group by data_date;

     VALUE DATA_DATE N HOUR    
---------- --------- - --------
        25 7/17/2018 A 07:00 PM
        55 7/18/2018 B 01:00 AM

如果hour的日期部分总是与data_date的字符串值匹配,则可以改用它:

select max(value) as value,
  to_char(trunc(hour), 'MM/DD/YYYY') as data_date,
  max(name) keep (dense_rank last order by value) as name,
  to_char(max(hour) keep (dense_rank last order by value), 'HH:MI AM') as hour
from your_table
group by trunc(hour);

     VALUE DATA_DATE  N HOUR    
---------- ---------- - --------
        25 07/17/2018 A 07:00 PM
        55 07/18/2018 B 01:00 AM

如果同一值一天出现超过一个小时,您还应该考虑要显示什么,这似乎是可行的。这些将显示任意匹配的值,但是您可以在order by子句中添加一些内容以选择最早或最新的匹配时间。如果要显示所有匹配项,则需要使用其他方法,例如@Yogesh的方法之一。