Kim Hyeong
sql을 이용한 구구단 만들기 본문
/*테이블 생성*/
CREATE TABLE GUDAN(
DAN NUMBER
);
/*테이블에 데이터 적재 rownum을 쓰기 위해 적당한 갯수를 넣어줌*/
BEGIN
FOR INI IN 1..15 LOOP
INSERT INTO GUDAN VALUES(INI);
END LOOP;
END;
/
/*데이터 적재 확인*/
SELECT * FROM GUDAN;
/*rownum을 활용하여 기본적으로 구구단을 생성*/
SELECT A.AA||'*'||B.BB||'='||A.AA*B.BB
FROM (SELECT ROWNUM AA FROM GUDAN WHERE ROWNUM <10 )A,
(SELECT ROWNUM BB FROM GUDAN WHERE ROWNUM <10 )B
/
/*단을 나눠주기로 함*/
SELECT DECODE(SUBSTR(GGD,1,1),1,GGD) "1단",
DECODE(SUBSTR(GGD,1,1),2,GGD) "2단",
DECODE(SUBSTR(GGD,1,1),3,GGD) "3단",
DECODE(SUBSTR(GGD,1,1),4,GGD) "4단",
DECODE(SUBSTR(GGD,1,1),5,GGD) "5단",
DECODE(SUBSTR(GGD,1,1),6,GGD) "6단",
DECODE(SUBSTR(GGD,1,1),7,GGD) "7단",
DECODE(SUBSTR(GGD,1,1),8,GGD) "8단",
DECODE(SUBSTR(GGD,1,1),9,GGD) "9단"
FROM(SELECT A.AA||'*'||B.BB||'='||A.AA*B.BB GGD
FROM (SELECT ROWNUM AA FROM GUDAN WHERE ROWNUM <10 )A,
(SELECT ROWNUM BB FROM GUDAN WHERE ROWNUM <10 )B
)
/
--1단은 필요없으니 지워주도록하자
/*MAX함수를 사용해서 가장 큰 값을 출력하면서 GROUP BY로 묶어준다.*/
SELECT MAX(DECODE(SUBSTR(GGD,1,1),2,GGD)) "2단",
MAX(DECODE(SUBSTR(GGD,1,1),3,GGD)) "3단",
MAX(DECODE(SUBSTR(GGD,1,1),4,GGD)) "4단",
MAX(DECODE(SUBSTR(GGD,1,1),5,GGD)) "5단",
MAX(DECODE(SUBSTR(GGD,1,1),6,GGD)) "6단",
MAX(DECODE(SUBSTR(GGD,1,1),7,GGD)) "7단",
MAX(DECODE(SUBSTR(GGD,1,1),8,GGD)) "8단",
MAX(DECODE(SUBSTR(GGD,1,1),9,GGD)) "9단"
FROM(SELECT A.AA||'*'||B.BB||'='||A.AA*B.BB GGD
FROM (SELECT ROWNUM AA FROM GUDAN WHERE ROWNUM <10 )A,
(SELECT ROWNUM BB FROM GUDAN WHERE ROWNUM <10 )B
)
GROUP BY SUBSTR(GGD,3,1);
/
/*왜인지는 모르겠으나 ROWNUM의 이상현상으로 ORDER BY를 이용해서 정렬을 해줘야 겠다.*/
SELECT MAX(DECODE(SUBSTR(GGD,1,1),2,GGD)) "2단",
MAX(DECODE(SUBSTR(GGD,1,1),3,GGD)) "3단",
MAX(DECODE(SUBSTR(GGD,1,1),4,GGD)) "4단",
MAX(DECODE(SUBSTR(GGD,1,1),5,GGD)) "5단",
MAX(DECODE(SUBSTR(GGD,1,1),6,GGD)) "6단",
MAX(DECODE(SUBSTR(GGD,1,1),7,GGD)) "7단",
MAX(DECODE(SUBSTR(GGD,1,1),8,GGD)) "8단",
MAX(DECODE(SUBSTR(GGD,1,1),9,GGD)) "9단"
FROM(SELECT A.AA||'*'||B.BB||'='||A.AA*B.BB GGD
FROM (SELECT ROWNUM AA FROM GUDAN WHERE ROWNUM <10 )A,
(SELECT ROWNUM BB FROM GUDAN WHERE ROWNUM <10 )B
)
GROUP BY SUBSTR(GGD,3,1)
ORDER BY SUBSTR(GGD,3,1) ASC;
/
끄읏~!