Q. 이 서비스에서는 공간을 둘 이상 등록한 사람을 "헤비 유저"라고 부릅니다.
헤비 유저가 등록한 공간의 정보를 아이디 순으로 조회하는 SQL문을 작성하시오.
다른 사람들의 풀이를 보던 중 with로 푼 사람이 있어서 with 문에 대해서 찾아봤다.
WITH 문이란?
문법은 다음과 같다
/* 1개의 임시테이블 */
WITH 임시테이블명 AS (
SUB QUERY문 (SELECT절)
)
SELECT 컬럼, [컬럼, ...]
FROM 임시테이블명
/* 2개 이상의 임시테이블 */
WITH
임시테이블명1 AS (
SUB QUERY문 (SELECT절)
),
임시테이블명2 AS (
SUB QUERY문 (SELECT절)
)
SELECT 컬럼, [컬럼, ...]
FROM 임시테이블명1
, 임시테이블명2
(정답)
with temp as (
SELECT host_id, count(*) cnt from places
group by host_id having cnt >=2
)
select * from places
where host_id in (select host_id from temp)
order by 1
Q. 데이터 분석 팀에서는 우유(Milk)와 요거트(Yogurt)를 동시에 구입한 장바구니가 있는지 알아보려 합니다.
우유와 요거트를 동시에 구입한 장바구니의 아이디를 조회하는 SQL 문을 작성해주세요.
이때 결과는 장바구니의 아이디 순으로 나와야 합니다.

한 아이디에 여러가지 속성이 있는게 아니라, 한 컬럼에 한가지 데이터로 이루어져 있어서 많이 헤맸다.
찾아보니 서로 다른 결과를 한줄로 합쳐서 보여주는 함수가 있었다.
group_concat(
합칠 컬럼SEPARETOR '원하는 구분자')
select * from test;| type | name |
|---|---|
| fruit | apple |
| fruit | banana |
| fruit | orange |
| fruit | apple |
select type, group_concat(name) from test group by type;| type | name |
|---|---|
| fruit | apple, banana, orange, apple |
기본 구분자는 쉼표(,) 이며,
구분자를 변경하고 싶은 경우 SEPARATOR '구분자' 를 쓴다.
select type, group_concat(name separator '|') from test group by type;| type | name |
|---|---|
| fruit | apple|banana|orange|apple |
select type, group_concat(distinct name) from test group by type;중복되는 문자열을 제거 할때는 distinct를 사용한다.
| type | name |
|---|---|
| fruit | apple, banana, orange |
select type, group_concat(distinct name order by name) from test group by type;order by를 이용해 문자열을 정렬 할 수 있다.
| type | name |
|---|---|
| fruit | apple, banana, orange |
(정답)
select cart_id
from (select CART_ID , group_concat(NAME) AS NAME
from CART_PRODUCTS
WHERE NAME IN ('Yogurt' , 'MILK')
group by CART_ID) a
where name like '%Milk%' and name like '%Yogurt%'