쿼리 도와주세요~~
본문
price_test 테이블
num price
1 50000
2 200000
3 250000
4 300000
5 350000
6 380000
7 400000
8 450000
9 480000
쿼리
SELECT price_range, count( * ) cnt
FROM (
SELECT
CASE
WHEN price <99999
THEN '0~10만원'
WHEN price
BETWEEN 100000
AND 199999
THEN '10~20만원'
WHEN price
BETWEEN 200000
AND 299999
THEN '20~30만원'
WHEN price
BETWEEN 300000
AND 399999
THEN '30~40만원'
WHEN price
BETWEEN 400000
AND 499999
THEN '40~50만원'
WHEN price >=500000
THEN '50만원~'
END AS price_range
FROM price_test
)tmp
GROUP BY price_range
ORDER BY price_range ASC
현재 결과
price_range cnt
0~10만원 1
20~30만원 2
30~40만원 3
40~50만원 3
원하는 결과
price_range cnt
0~10만원 1
10~20만원 0
20~30만원 2
30~40만원 3
40~50만원 3
50만원~ 0
현재 cnt가 0인 필드는 데이타가 출력이 안되는데 0인 데이타도 출력 될 수 있게 도와주세요ㅠㅠ
고수님들 꼭 부탁드립니다. ㅠㅠ
답변 6
간단하게 하는 방법은
union all select "0~10만원", 0
union all select "10~20만원", 0
union all select "20~30만원", 0
union all select "30~40만원", 0
union all select "40~50만원", 0
union all select "50만원 ~", 0
이랑 합친뒤에
select max(price_range) as price_range, sum(cnt) as cnt
SELECT '0~10만원' r1, a1, '10~20만원' r2, a2, '20~30만원' r3, a3, '30~40만원' r4, a4,
'40~50만원' r5, a5, '50만원~' r6, a6
FROM (
(SELECT count(*) a1 from price_test where price < 99999) b1,
(SELECT count(*) a2 from price_test where price between 100000
AND 199999 ) b2,
(SELECT count(*) a3 from price_test where price between 200000
AND 299999 ) b3,
(SELECT count(*) a4 from price_test where price between 300000
AND 399999 ) b4,
(SELECT count(*) a5 from price_test where price between 400000
AND 499999 ) b5,
(SELECT count(*) a6 from price_test where price >= 500000) b6
)
IFNULL(COUNT(*), 0) as cnt 해보세요
테이블 하나 더 만들어서 join 처리하세요.
아니면 코드에서 loop로 한번 돌리세요.
쉽게 할수 있는건 쉽게 처리하는게 좋습니다.
SELECT price_range, cnt
FROM (
SELECT '0~10만원' AS price_range, count(*) AS cnt
FROM price_test where price < 99999
UNION
SELECT '10~20만원' AS price_range, count(*) AS cnt
FROM price_test where price BETWEEN 100000 AND 199999
UNION
SELECT '20~30만원' AS price_range, count(*) AS cnt
FROM price_test where price BETWEEN 200000 AND 299999
UNION
SELECT '30~40만원' AS price_range, count(*) AS cnt
FROM price_test where price BETWEEN 300000 AND 399999
UNION
SELECT '40~50만원' AS price_range, count(*) AS cnt
FROM price_test where price BETWEEN 400000 AND 499999
UNION
SELECT '50만원~' AS price_range, count(*) AS cnt
FROM price_test where price >= 500000
)tmp
GROUP BY price_range
여러분들의 의견들을 분석하여
이렇게 처리했습니다.
감사합니다.^^
제일 도움이 되었던 분에게 채택해드렸습니다.
다른분들은 죄송합니다.ㅠㅠ