简体   繁体   中英

Calculating average minutes for items within different time frames

例 I have a data set that needs to be separated into two subsets. Each subset must include only items within particular time frame. Then, I need to take MAX(last edited time)-MIN(item added time) and divide by amount of items in the subset. Therefore my goal is to calculate AVERAGE amount of time it takes to work on all items within two timeframes. See the picture.!

I tried this, but it seems not working- results are not correct; the query produces result for MIN and MAX for the whole period of time outlined in the WHERE clause (so period of multiple days dramatically screws up the result).

SELECT 
  CASE
    WHEN TO_CHAR(ADDED, 'HH24') BETWEEN 09 AND 11
    THEN TRUNC(((MAX(MODIFIED) - MIN(ADDED))*24*60)/COUNT(TRANSACTIONS))
    ELSE 0
  END 
    +
  CASE
    WHEN TO_CHAR(ADDED, 'HH24') BETWEEN 15 AND 19
    THEN TRUNC(((MAX(MODIFIED) - MIN(ADDED))*24*60)/COUNT(TRANSACTIONS))
    ELSE 0
  END AS subsets_average
FROM TABLE

I see what you are trying to do. The case statement is in the wrong place. You want conditions inside the aggregation functions:

SELECT TRUNC(((MAX(MODIFIED END)-
               MIN(ADDED ))*24*60)/COUNT(TRANSACTIONS) as grand_average,
       TRUNC(((MAX(TO_CHAR(ADDED, 'HH24') BETWEEN 09 AND 11 THEN MODIFIED END)-
               MIN(TO_CHAR(ADDED, 'HH24') BETWEEN 09 AND 11 THEN ADDED END))*24*60)/COUNT(TRANSACTIONS)
             ) +
       TRUNC(((MAX(TO_CHAR(ADDED, 'HH24') BETWEEN 15 AND 19 THEN MODIFIED END)-
               MIN(TO_CHAR(ADDED, 'HH24') BETWEEN 15 AND 19 THEN ADDED END))*24*60)/COUNT(TRANSACTIONS) AS subsets_average
FROM TABLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM