SELECT FOOD_TYPE, REST_ID, REST_NAME, FAVORITES
FROM REST_INFO
WHERE (FOOD_TYPE, FAVORITES) IN
(SELECT FOOD_TYPE, MAX(FAVORITES) FROM REST_INFO GROUP BY FOOD_TYPE)
ORDER BY FOOD_TYPE DESC;
SELECT ANIMAL_TYPE, COUNT(ANIMAL_TYPE) as count
FROM ANIMAL_INS
GROUP BY ANIMAL_TYPE
ORDER BY ANIMAL_TYPE;
SELECT ANIMAL_TYPE, COUNT(*) as count
FROM ANIMAL_INS
GROUP BY ANIMAL_TYPE
ORDER BY ANIMAL_TYPE;
SELECT NAME, COUNT(NAME) as COUNT
FROM ANIMAL_INS
GROUP BY NAME
HAVING COUNT(NAME) > 1
ORDER BY NAME;
SELECT YEAR(s.SALES_DATE) as YEAR, MONTH(s.SALES_DATE) as MONTH, u.GENDER as GENDER, COUNT(DISTINCT(u.USER_ID)) as USERS
FROM USER_INFO as u
JOIN ONLINE_SALE as s
ON u.USER_ID = s.USER_ID
WHERE u.GENDER IS NOT NULL
GROUP BY YEAR(s.SALES_DATE), MONTH(s.SALES_DATE), u.GENDER;
SELECT YEAR(s.SALES_DATE) as YEAR,
MONTH(s.SALES_DATE) as MONTH,
u.GENDER as GENDER, COUNT(DISTINCT s.USER_ID) as USERS
FROM ONLINE_SALE as s
LEFT JOIN USER_INFO as u
ON s.USER_ID = u.USER_ID
WHERE u.GENDER IS NOT NULL
GROUP BY YEAR(s.SALES_DATE), MONTH(s.SALES_DATE), u.GENDER
ORDER BY YEAR, MONTH, GENDER;
SELECT HOUR(DATETIME) as HOUR, COUNT(DATETIME) as COUNT
FROM ANIMAL_OUTS
GROUP BY HOUR(DATETIME)
HAVING HOUR BETWEEN 9 AND 19
ORDER BY HOUR;
SET 함수 사용
WITH RECURSIVE
SET 함수 사용
SET @변수 = 값 set 사용 시에만 =
@변수 := 값 그 이후 대입에서는 :=
SET @hour = -1;
SELECT (@hour := @hour + 1) AS HOUR,
(SELECT COUNT(HOUR(DATETIME))
FROM ANIMAL_OUTS
WHERE HOUR(DATETIME) = @hour)
FROM ANIMAL_OUTS
WHERE @hour < 23;
WITH RECURSIVE 테이블 이름
AS (
SELECT 1 AS n // 비반복, 처음 한 번 실행
UNION ALL
SELECT n + 1 AS n // 반복, 행 위치 기억하여 다음 행에서 계속 실행됨
FROM 테이블 이름
WHERE n < 10 // 종료 조건
)
WITH RECURSIVE CTE AS
(
SELECT 0 as HOUR
UNION ALL
SELECT HOUR + 1 AS HOUR
FROM CTE
WHERE HOUR < 23
)
# SELECT c.HOUR, CASE WHEN IFNULL(COUNT(DATETIME), 0)
SELECT c.HOUR, COUNT(a.DATETIME) as COUNT
FROM CTE as c
LEFT JOIN ANIMAL_OUTS as a
ON c.HOUR = HOUR(a.DATETIME)
GROUP BY c.HOUR
ORDER BY c.HOUR;
SELECT TRUNCATE(PRICE, -4) AS PRICE_GROUP, COUNT(PRICE) as PRODUCTS
FROM PRODUCT
GROUP BY PRICE_GROUP
ORDER BY PRICE_GROUP;
SELECT PRICE DIV 10000 * 10000 AS PRICE_GROUP, COUNT(PRICE) as PRODUCTS
FROM PRODUCT
GROUP BY PRICE DIV 10000
ORDER BY PRICE DIV 10000;
'코딩테스트(Coding Test) > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 인사고과 (2) | 2024.05.01 |
---|---|
[프로그래머스] 괄호 회전하기 (1) | 2024.02.10 |
[프로그래머스.SQL] SUM, MAX, MIN (0) | 2023.11.24 |
[프로그래머스/SQL] 오프라인/온라인 판매 데이터 통합하기 (0) | 2023.10.17 |