Calculate the length of appointment in each hour and save it in multiple columns in SQL developer or R

Viewed 40

I am new to SQL (Oracle SQL Developer) and want to create multiple columns that calculate the length of appointment in each hour and store that in a new column. For instance, if start date is "2021-12-01 16:40:00 EST" and end date is "2021-12-01 18:15:00 EST", I want to create three columns 16:00 with the value of 20 minutes, 17:00 with the value 60 and 18:00 with the value of 15 minutes. Please check the picture attached. I have the start and end date and need to create the other columns. I added my answer in R. My idea was to merge wide_end and wide_start and then fill the time between by 60. However, I don't know how to merge both data sets. I guess there must be a better way to do this. Thanks in advance.

library(tidyverse)
library(lubridate)
df <- data.frame(
  id = c(1,2,3,4,5,6,7,8,9),
  start_time = c("2021-09-02 11:15:00", "2021-09-02 13:35:00",
                 "2021-09-02 03:00:00", "2021-09-02 03:50:00",
                 "2021-09-02 07:05:00", "2021-09-02 06:45:00", 
                 "2021-09-02 06:04:00", "2021-09-02 07:51:00",
                  "2021-09-02 08:16:00"),
  end_time = c("2021-09-02 11:55:00", "2021-09-02 14:20:00",
               "2021-09-02 03:30:00", "2021-09-02 06:15:00",
               "2021-09-02 08:05:00", "2021-09-02 09:15:00", 
               "2021-09-02 08:34:00", "2021-09-02 08:15:00",
                "2021-09-02 08:55:00"))


df <- df %>% mutate(start_time=as.POSIXct(start_time), end_time= as.POSIXct(end_time))

df <- df %>% mutate(start.hours = format(floor_date(start_time, "hour"), format = "%H:%M"),
                        end.hours= format(floor_date(end_time, "hour"), format = "%H:%M"))


df <- df  %>% mutate(start_duration= 
                ifelse(start.hours== end.hours, difftime(end_time, start_time, units = "mins"), 
                          difftime(ceiling_date(start_time, "hour", change_on_boundary = TRUE), 
                                                        start_time, units = "mins")))
                                              

df <- df %>% mutate(end_duration= ifelse(start.hours!= end.hours, 
          difftime(end_time, floor_date(end_time, "hour"), units = "mins"), NA),
                        end_duration= ifelse(end_duration==0, NA, end_duration))

wide_start <- df %>%  pivot_wider(names_from = start.hours,
                               values_from = start_duration, names_sort = T)

wide_end <- df %>%  pivot_wider(names_from = end.hours,
                                  values_from = end_duration, names_sort = T)

``

![enter image description here][1]


  [1]: https://i.stack.imgur.com/e0l0J.png
0 Answers
Related