Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Sum values by odd/even hour daily

PugzlyMay 4 2024

I'm trying to SUM() the values for each day based on whether the hour of the day is odd or even.

I have some code, which is incomplete. I know I can use extract to pull out the hour and I need an odd even CASE statement and possibly some subquery but I'm having some difficulty putting it all together and was hoping someone can help me out.

Based on my test data I'm expecting the following result.

MEASUREMENT_DAY ODD_VALUES EVEN_VALUES
01-MAY-2024 120 125
02-MAY-2024  90   0

01-MAY-2024

5+15+25+35+45=125 18hrs

8+16+24+32+40=120 19hrs

02-MAY-2024

6+12+18+24+30 90 11hrs

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY';

ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'DD-MON-YYYY  HH24:MI:SS.FF';

create table measurements(
  seq_num NUMBER GENERATED BY DEFAULT AS IDENTITY (START WITH 1) NOT NULL,
  measurement_value NUMBER,
  measurement_date timestamp
);

insert into measurements (measurement_value,measurement_date)
    select  ((2*LEVEL-1) * 5) measurement_value, 
   TIMESTAMP '2024-05-01 00:00:00' + INTERVAL '18' HOUR + ((LEVEL-1) * INTERVAL '0 00:10:01' DAY TO SECOND)  +   ((LEVEL-1) * interval '0.02' second) 
          as measurement_date
    from    dual
    connect by level <= 5 UNION ALL 
select  ((2*LEVEL) * 4), 
   TIMESTAMP '2024-05-01 00:00:00' + INTERVAL '19' HOUR + ((LEVEL-1) * INTERVAL '0 00:00:13' DAY TO SECOND)  +   ((LEVEL-1) * interval '0.00125' second) 
    from    dual
    connect by level <= 5
 UNION ALL 
select  ((2*LEVEL) * 3), 
   TIMESTAMP '2024-05-02 00:00:00' + INTERVAL '11' HOUR + ((LEVEL-1) * INTERVAL '0 00:12:13' DAY TO SECOND)  +   ((LEVEL-1) * interval '0.02125' second) 
    from    dual
    connect by level <= 5;

SELECT measurement_day,
       SUM(CASE odd_even WHEN 1 THEN measurement_value END) AS odd_values,
       SUM(CASE odd_even WHEN 0 THEN measurement_value END) AS even_values
FROM   (
  SELECT measurement_value,
TO_CHAR(measurement_date, 'HH24') hr 
…
…
…

                  ) AS odd_even
  FROM   measurements
)
GROUP BY measurement_day;
This post has been answered by Frank Kulash on May 4 2024
Jump to Answer
Comments
Post Details
Added on May 4 2024
4 comments
245 views