반응형
상황
월별로 데이터가 가장 많이 들어온 날짜를 구하는 쿼리가 필요
방법
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
반응형
'개발 > DB' 카테고리의 다른 글
DB Index 팁 간단 정리 (ft. Maria DB, MySQL) (0) | 2022.07.07 |
---|---|
[mySql, mariaDB] case 문 사용 방법 (0) | 2022.04.06 |
(Mybatis) Where 1=1 처럼 동적으로, update set 컬럼을 바꾸고 싶을때 (0) | 2022.03.22 |
(MariaDB) 범위 별로 카운트 구하기 (Group by가 아닌 범위 별 통계) (0) | 2022.01.20 |
(펌) [DBMS] [MySQL] COUNT의 잘못된 인식과 속도차이 (0) | 2022.01.18 |