반응형

상황

 월별로 데이터가 가장 많이 들어온 날짜를 구하는 쿼리가 필요

 

방법

Group by & order by & 서브쿼리를 활용
(key = group by 가장 상위의 데이터로 그룹핑 되므로, order by 사용하면 내가 원하는 데이터를 위로 올릴수있다)

 

아이디어

  • 그룹핑 (group by yyyymmdd) + 정렬(order by yyyymm), count(데이터수)
  • 서브쿼리2 : 위의 내용을  월별로 그룹핑

  • 그룹핑 (Group by yyyymm)
  • 그룹함수를 이용한 결과 출력

기존 쿼리

select
    max(bill_dt.readDt) readDt,
    max(bill_dt.oneMonthAgo) oneMonthAgo,
    max(bill_dt.twoMonthAgo) twoMonthAgo,
    max(bill_dt.threeMonthAgo) threeMonthAgo
from (
    select
        case
            when substring(READ_DT,1,6) = date_format(concat( ${read_dt},'01'), '%Y%m') then READ_DT
        end as 'readDt',
        case
            when substring(READ_DT,1,6) = date_format(date_add(concat(${read_dt},'01'),INTERVAL -1 Month), '%Y%m') then READ_DT
        end as 'oneMonthAgo',
        case
            when substring(READ_DT,1,6) = date_format(date_add(concat(${read_dt},'01'),INTERVAL -2 Month), '%Y%m') then READ_DT
        end as 'twoMonthAgo',
        case
            when substring(READ_DT,1,6) = date_format(date_add(concat(${read_dt},'01'),INTERVAL -3 Month), '%Y%m') then READ_DT
        end as 'threeMonthAgo'
    from gnd_meter_billing gmb
    where 조건 1
    and 기간 between 기간1 and 기간2
    group by substring(READ_DT,1,6), substring(READ_DT,7,2)
    order by cnt_readDt desc
    ) bill_dt

수정 쿼리

select
    max(bill_dt.readDt) readDt,
    max(bill_dt.oneMonthAgo) oneMonthAgo,
    max(bill_dt.twoMonthAgo) twoMonthAgo,
    max(bill_dt.threeMonthAgo) threeMonthAgo
from (
    select *
    from (
        select
            count(READ_DT) cnt_readDt,
            substring(READ_DT,1,6) yyyymm, 
            case
                when substring(READ_DT,1,6) = date_format(concat( ${read_dt},'01'), '%Y%m') then READ_DT
            end as 'readDt',
            case
                when substring(READ_DT,1,6) = date_format(date_add(concat(${read_dt},'01'),INTERVAL -1 Month), '%Y%m') then READ_DT
            end as 'oneMonthAgo',
            case
                when substring(READ_DT,1,6) = date_format(date_add(concat(${read_dt},'01'),INTERVAL -2 Month), '%Y%m') then READ_DT
            end as 'twoMonthAgo',
            case
                when substring(READ_DT,1,6) = date_format(date_add(concat(${read_dt},'01'),INTERVAL -3 Month), '%Y%m') then READ_DT
            end as 'threeMonthAgo'
        from gnd_meter_billing gmb
        where 조건 1
        and 기간 between 기간1 and 기간2
        group by substring(READ_DT,1,8)
        order by substring(READ_DT,1,6), cnt_readDt desc
        ) bill_dt_by_yyyymmdd
        group by bill_dt_by_yyyymmdd.yyyymm
    ) bill_dt
반응형

+ Recent posts