[SQL] data format 하기( 전화번호 xxx-xxxx-xxxx로 표현하기 )

도리·2025년 3월 3일

programmers (string,date) lv3 조건에 맞는 사용자 정보 조회하기

문제

USED_GOODS_BOARD와 USED_GOODS_USER 테이블에서 중고 거래 게시물을 3건 이상 등록한 사용자의 사용자 ID, 닉네임, 전체주소, 전화번호를 조회하는 SQL문을 작성해주세요. 이때, 전체 주소는 시, 도로명 주소, 상세 주소가 함께 출력되도록 해주시고, 전화번호의 경우 xxx-xxxx-xxxx 같은 형태로 하이픈 문자열(-)을 삽입하여 출력해주세요. 결과는 회원 ID를 기준으로 내림차순 정렬해주세요.

내 코드

with three as (
SELECT writer_id, count(contents) as num
from used_goods_board 
group by writer_id)
select t.writer_id , u.nickname, concat(u.city,' ', u.street_address1,' ',u.street_address2) as '전체주소',
        date_format('xxx-xxxx-xxx',tlno)
from three t 
join used_goods_user u on t.writer_id = u.user_id
where num>=3
order by t.writer_id

정답 코드

SELECT  USER_ID
        , NICKNAME
        , CONCAT(CITY, ' ', STREET_ADDRESS1, ' ', STREET_ADDRESS2) AS '전체주소'
        , CONCAT(SUBSTR(TLNO, 1, 3), '-', SUBSTR(TLNO, 4, 4), '-', SUBSTR(TLNO, 8)) AS '전화번호'
FROM    USED_GOODS_USER 
WHERE   USER_ID IN (
                     SELECT  WRITER_ID
                     FROM    USED_GOODS_BOARD
                     GROUP BY WRITER_ID
                     HAVING  COUNT(*) >= 3
                 )
 ORDER 
    BY  USER_ID DESC;

틀린 이유

전화번호 01012345678 -> 010-1234-5678
이런식으로 변환해야하는데 ,
날짜변환 date_format 밖에 사용본적이 없어서 헤맸다.

CONCAT(SUBSTR(TLNO, 1, 3), '-', SUBSTR(TLNO, 4, 4), '-', SUBSTR(TLNO, 8)) AS '전화번호'

substr 함수로 원하는 구간만큼 자르고 원하는 문자 - 등을 concat으로 추가하면 된다.

profile
인공지능응용학과 졸업

0개의 댓글