년, 월, 성별 별 상품 구매 회원 수 구하기

2023. 1. 17. 20:28Programmers/SQL

가장 정답이 이해 안 가는 문제

 

문제

 

결과 화면

결과 화면과 같이 나타나기 위해서는 날짜 부분의 달에서 0이 없어야 한다고 생각했다 

01월이 아니라 1월로 뜨도록

그래서 정규식으로 0을 없앴는데 계속해서 오답이 나왔다

1
2
3
4
5
6
7
8
9
10
11
12
SELECT  to_char(a.sales_date, 'yyyy') year, 
        decode(
           substr(to_char(a.sales_date, 'mm'),1,1), 
           '0',
           regexp_substr(to_char(a.sales_date, 'mm'), '[^0]' ,1,1)
        ) month,
        gender, count(distinct a.user_id) users
FROM ONLINE_SALE A, USER_INFO B
WHERE A.USER_ID = B.USER_ID
group by to_char(a.sales_date, 'yyyy'),to_char(a.sales_date, 'mm'), gender
having b.gender is not null 
order by year, month, gender asc
cs

ltrim으로 없애봤는데도 다 안 됐다.

1
2
3
4
5
6
7
8
SELECT  to_char(a.sales_date, 'yyyy') year, 
        ltrim(to_char(a.sales_date, 'mm'), '0') month,
        gender, count(distinct a.user_id) users
FROM ONLINE_SALE A, USER_INFO B
WHERE A.USER_ID = B.USER_ID
group by to_char(a.sales_date, 'yyyy'),to_char(a.sales_date, 'mm'), gender
having b.gender is not null 
order by year, month, gender asc
cs

 

그래서 혹시나 하는 마음에 정규식 대신에 to_char를 사용했는데 정답이 나왔다

1
2
3
4
5
6
7
8
SELECT  to_char(a.sales_date, 'yyyy') year, 
        to_char(a.sales_date, 'mm') month,
        gender, count(distinct a.user_id) users
FROM ONLINE_SALE A, USER_INFO B
WHERE A.USER_ID = B.USER_ID
group by to_char(a.sales_date, 'yyyy'),to_char(a.sales_date, 'mm'), gender
having b.gender is not null
order by year, month, gender asc
cs

 

왜 이게 정답인지 아직도 이해가 안 가는 문제