안녕하세요.
MySQL에서의 부분합 표현관련 문의입니다.
테이블의 데이타는 다음과 같습니다.
url count
/test/a/1/temp.txt 10
/test/a/2/temp.txt 10
/test/a/3/temp.txt 10
/test/b/1/temp.txt 10
/test/b/1/temp.txt 10
/test/b/1/temp.txt 10
/test/b/1/temp.txt 10
이를 다음과 같이 보여줘야 합니다. (/ 구분자로 부분합)
result
url count level
/test 70 1
/test/a 30 2
/test/a/1 10 3
/test/a/1/temp.txt 10 4
/test/a/2 10 3
/test/a/2/temp.txt 10 4
/test/a/3 10 3
/test/a/3/temp.txt 10 4
/test/b 40 2
/test/b/1 40 3
/test/b/1/temp.txt 40 4
MySQL 쿼리로 가능할까요?
고수님들 도와주세요. ㅠ
SELECT url , cnt , LENGTH(url) - LENGTH(REPLACE(url, '/', '')) lv FROM (SELECT url_1, url_2, url_3, url_4 , COALESCE(url_4, url_3, url_2, url_1) url , SUM(cnt) cnt FROM (SELECT SUBSTRING_INDEX(url, '/', 2) url_1 , SUBSTRING_INDEX(url, '/', 3) url_2 , SUBSTRING_INDEX(url, '/', 4) url_3 , url url_4 , cnt FROM (SELECT '/test/a/1/temp.txt' url, 10 cnt UNION ALL SELECT '/test/a/2/temp.txt', 10 UNION ALL SELECT '/test/a/3/temp.txt', 10 UNION ALL SELECT '/test/b/1/temp.txt', 10 UNION ALL SELECT '/test/b/1/temp.txt', 10 UNION ALL SELECT '/test/b/1/temp.txt', 10 UNION ALL SELECT '/test/b/1/temp.txt', 10 ) t ) a GROUP BY url_1, url_2, url_3, url_4 WITH ROLLUP HAVING url_1 IS NOT NULL ) a ORDER BY url ;
SELECT SUBSTRING_INDEX(url, '/', lv+1) url , SUM(cnt) cnt , lv FROM (SELECT '/test/a/1/temp.txt' url, 10 cnt UNION ALL SELECT '/test/a/2/temp.txt', 10 UNION ALL SELECT '/test/a/3/temp.txt', 10 UNION ALL SELECT '/test/b/1/temp.txt', 10 UNION ALL SELECT '/test/b/1/temp.txt', 10 UNION ALL SELECT '/test/b/1/temp.txt', 10 UNION ALL SELECT '/test/b/1/temp.txt', 10 UNION ALL SELECT '/z1/2/3/4/5/6/7/8/9/10', 10 ) t INNER JOIN (SELECT 1 lv UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15 ) copy_t ON lv <= LENGTH(url) - LENGTH(REPLACE(url, '/', '')) GROUP BY SUBSTRING_INDEX(url, '/', lv+1), lv ORDER BY url ;