안녕하세요.
오라클 쿼리좀 질문 드립니다.
나이 | 성별 |
20 | 남자 |
15 | 여자 |
45 | 여자 |
34 | 남자 |
35 | 여자 |
60 | 남자 |
65 | 남자 |
이런 형식에 데이터를
나이 | 남자 | 여자 |
1~10세 | 20명 | 30명 |
11~20세 | 30명 | 20명 |
21~30세 | 40명 | 20명 |
31~40세 | 50명 | 11명 |
41~50세 | 22명 | 44명 |
51~60세 | 11명 | 50명 |
61세 이상 | 33명 | 10명 |
이런식으로 뽑아내고 싶은데 쿼리를 어떤식으로 짜야할지 모르겠어서 질문드려봅니다..
감사합니다.
WITH T ( YR , SX ) AS ( SELECT 20 , '남자' FROM DUAL UNION ALL SELECT 15 , '여자' FROM DUAL UNION ALL SELECT 45 , '여자' FROM DUAL UNION ALL SELECT 34 , '남자' FROM DUAL UNION ALL SELECT 35 , '여자' FROM DUAL UNION ALL SELECT 60 , '남자' FROM DUAL UNION ALL SELECT 65 , '남자' FROM DUAL ) SELECT DECODE(GB,'A','1~10세','B','11~20세','C','21~30세','D','31~40세','E','41~50세','F','51~60세','G','61세이상') "나이" ,COUNT(CASE WHEN SX = '남자' THEN 1 END) AS "남자" ,COUNT(CASE WHEN SX = '여자' THEN 1 END) AS "여자" FROM ( SELECT CASE WHEN YR >= 1 AND YR <= 10 THEN 'A' WHEN YR >= 11 AND YR <= 20 THEN 'B' WHEN YR >= 21 AND YR <= 30 THEN 'C' WHEN YR >= 31 AND YR <= 40 THEN 'D' WHEN YR >= 41 AND YR <= 50 THEN 'E' WHEN YR >= 51 AND YR <= 60 THEN 'F' WHEN YR >= 61 THEN 'G' END GB, SX FROM T ) GROUP BY GB ORDER BY GB
WITH t AS
(
SELECT '30'::numeric age, '남자' sex FROM dual
UNION ALL SELECT '20', '남자' FROM dual
UNION ALL SELECT '15', '여자' FROM dual
UNION ALL SELECT '45', '여자' FROM dual
UNION ALL SELECT '34', '남자' FROM dual
UNION ALL SELECT '35', '여자' FROM dual
UNION ALL SELECT '60', '남자' FROM dual
UNION ALL SELECT '65', '남자' FROM dual
UNION ALL SELECT '36', '여자' FROM dual
)
select case when age<11 then '1~10세'
when age<21 then '11~20세'
when age<31 then '21~30세'
when age<41 then '31~40세'
when age<51 then '41~50세'
when age<61 then '51~60세'
else '61세 이상' end 나이 ,
count(case when sex='남자' then 1 end) as 남자,
count(case when sex='여자' then 1 end) as 여자
from t
group by 나이
order by 나이;
WITH T AS( SELECT 20 age, '남자' gen FROM DUAL UNION ALL SELECT 15 age, '여자' gen FROM DUAL UNION ALL SELECT 45 age, '여자' gen FROM DUAL UNION ALL SELECT 34 age, '남자' gen FROM DUAL UNION ALL SELECT 35 age, '여자' gen FROM DUAL UNION ALL SELECT 60 age, '남자' gen FROM DUAL UNION ALL SELECT 65 age, '남자' gen FROM DUAL UNION ALL SELECT 74 age, '남자' gen FROM DUAL ) SELECT CASE age_t WHEN 1 THEN '1~10세' WHEN 2 THEN '21~30세' WHEN 3 THEN '31~40세' WHEN 4 THEN '41~50세' WHEN 5 THEN '51~60세' WHEN 6 THEN '61세 이상' END "나이" , SUM(DECODE(gen, '남자', 1, 0)) "남자" , SUM(DECODE(gen, '여자', 1, 0)) "여자" FROM ( SELECT T.*, CASE WHEN TRUNC((age - 1) / 10) >= 6 THEN 6 ELSE TRUNC((age - 1) / 10) END age_t FROM T ) GROUP BY age_t ORDER BY age_t