프로그래머스 문제: 링크
참고 자료: MySQL doc on With (common table expressions)
WITH
cte1 AS (SELECT a, b FROM table1)
cte2 AS (SELECT c, d FROM table2)
SELECT b, d
FROM cte1
JOIN cte2
WHERE cte1.a=cte2.c
;
A common table expression (CTE) is a named temporary result set that exists within the scope of a single statement and that can be referred to later within that statement, possibly multiple times. The following discussion describes how to write statements that use CTEs.
WITH RECURSIVE TEMP
AS (SELECT 0 AS HOUR
UNION ALL
SELECT HOUR+1 FROM TEMP
WHERE HOUR<23) #with를 이용한 recursive 만들기
SELECT HOUR, COUNT(ANIMAL_OUTS.ANIMAL_ID) AS COUNT
FROM ANIMAL_OUTS
RIGHT JOIN TEMP
ON HOUR(ANIMAL_OUTS.DATETIME) = TEMP.HOUR
GROUP BY HOUR