简体   繁体   中英

How to aggregate a measure on a year-month level based on start and end date in SQL?

I have a SQL query that pulls in three columns as below

employee_id  start_date  end_date       hours
123          09-01-2019  09-02-2019     8
123          09-28-2019  10-01-2019     32

I want to rewrite the query so instead of going granular, i just want to know the sum(hrs) an employee has on a year month level like below:

employee_id  Year_Month       hours
123          201909            32
123          201910            8

The employee has 4 days in September so 4*8=32 and one day in october so 8 hours for the month of October. My issue is when there are start and end dates that cross between adjacent months. I'm not sure how to write a query to get my desired output and I'd really appreciate any help on this

It might be simpler to use a recursive query to generate series of days in each month, then aggregate by month and count:

with
    data as (< your existing query here >), 
    cte (employee_id, dt, max_dt) as (
        select employee_id, start_date, end_date from data
        union all
        select employee_id, dt + 1, max_dt from cte where dt + 1 < max_dt
    )

select employee_id, to_char(dt, 'yyyymm')  year_months, count(*) * 8 hours
from mytable
group by employee_id, to_char(dt, 'yyyymm')

This assumes 8 hours per day, as explained in your question.

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