본문 바로가기
DBMS

[Oracle] 능력단위평가 풀이

by amoomar 2022. 1. 28.
반응형

 

 

이전 포스팅의 내용을 활용하여 5가지의 문제를 풀어보았고, 본인의 풀이와 필요에 의해 강사풀이가 추가될 수 있다.

 

 


 

 

1. 검색의 조건_대·소문자

: 다음의 테이블에서 e(E)가 들어가지않은 과일의 이름과 가격만을 출력하세요.

create table test(
   num int primary key,
   name varchar(20),
   price int
);

insert into test values(1,'apple',5000);
insert into test values(2,'BANANA',6000);
insert into test values(3,'kiwi',7000);
insert into test values(4,'oRaNgE',8000);
insert into test values(5,'Shine Muscat',9000);
insert into test values(6,'PINEapple',10000);
insert into test values(7,'grApE',11000);

select * from test;
drop table test;

 

 

1) 본인풀이

select name, price from test where not lower(name) like lower('%'||'e'||'%');

 

2) 강사풀이

select * from test where not lower(name) like '%e%';
select * from test where not upper(name) like '%E%';

 

 


 

 

2. 랜덤생성

: □□○○○형식의 랜덤값을 5개 생성(중복허용)하여 TEST2 테이블에 저장하세요.
 ex) AB178, XJ992, QQ436, ...

 

1) 본인풀이

insert into test2 values ((select dbms_random.string('U',2) from dual),(SELECT CEIL(DBMS_RANDOM.VALUE(100,200)) FROM DUAL));
insert into test2 values ((select dbms_random.string('U',2) from dual),(SELECT CEIL(DBMS_RANDOM.VALUE(100,200)) FROM DUAL));
insert into test2 values ((select dbms_random.string('U',2) from dual),(SELECT CEIL(DBMS_RANDOM.VALUE(100,200)) FROM DUAL));
insert into test2 values ((select dbms_random.string('U',2) from dual),(SELECT CEIL(DBMS_RANDOM.VALUE(100,200)) FROM DUAL));
insert into test2 values ((select dbms_random.string('U',2) from dual),(SELECT CEIL(DBMS_RANDOM.VALUE(100,200)) FROM DUAL));

 

2) 강사풀이

select dbms_random.string('U',2) from dual;
select floor(dbms_random.value(100,1000)) from dual;
insert into test2 values(concat((select dbms_random.string('U',2) from dual),(select floor(dbms_random.value(100,1000)) from dual)));
select * from test2;

 

 


 

 

3. SimpleDateFormat

: 이클립스 Console에서 "1. 출석 2. 점심 3. 퇴실" 을 선택하면 알맞은 문구를 출력해주세요. 단, SimpleDateFormat 등을 활용하여 코드를 작성하세요.


ex)09:05 출석했습니다. | 11:50 오늘 ㅁㅁㅁ을 먹으러갑니다!~~ (❁´◡`❁) | 05:50 집집

 

 

 

1) 본인풀이

: 별도의 SQL파일 없이 JAVA에서 날짜(String -> date타입으로 형변환)와 출력문구 생성

package day024;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class Test01 {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);

		// date타입으로 변환할 문자열생성
		String date1="202201270905";
		String date2="202201271150";
		String date3="202201271750";

		// Strig date들 date타입으로 변경하기위한 목적
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmm");
		//원하는 형식으로 자르기위한 목적
		SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm"); 

		try {
			// 문자열 -> date타입으로 바꾸는 작업
			Date formatDate1 = sdf1.parse(date1);
			Date formatDate2 = sdf1.parse(date2);
			Date formatDate3 = sdf1.parse(date3);

			// date타입으로 바뀐 각 문자열에 내가 원하는 형식 덮어씌우기
			date1=sdf2.format(formatDate1);
			date2=sdf2.format(formatDate2);
			date3=sdf2.format(formatDate3);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		while(true) {
			System.out.println("1. 출석 \n2. 점심\n3. 퇴실");
			System.out.print(">");
			int act = sc.nextInt();
			if(act==1) {
				System.out.println(date1+"출석했습니다.");
			}else if(act==2) {
				System.out.println(date2+"오늘맛있는거 먹으러갑니다!~~ (❁´◡`❁)\r\n" + 
						"");
			}else if(act==3) {
				System.out.println(date3+"집집");
			}else {
				System.out.println("?");
			}
		}

	}
}

 

2) 강사풀이

: 테이블 생성 후 메인에서 테이블에 접근하여 원하는바 대로 출력

 

① TableDB 생성

create table test3(
	act int primary key,
	content varchar(50),
	ptime date
);
insert into test3 values(1,'출석했습니다.',to_date('09:05','HH24:MI'));
insert into test3 values(2,'오늘 점심은 (❁´◡`❁)',to_date('11:50','HH24:MI'));
insert into test3 values(3,'집집',to_date('17:50','HH24:MI'));
select * from test3;
drop table test3;

 

② Utill & VO & main생성하여 출력

: utill클래스의 내용은 생략하였다.

package test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date; // util을 상속받는 sql. 시분초까지 출력원할때에는 util을 사용한다!
import java.util.Scanner;

class VO{
	private int num;
	private String content;
	private Date pdate;
	SimpleDateFormat sdf=new SimpleDateFormat("HH:mm");
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public Date getPdate() {
		return pdate;
	}
	public void setPdate(Date pdate) {
		this.pdate = pdate;
	}
	@Override
	public String toString() {
		return content+" | "+sdf.format(pdate);
	}
}
public class Test01 {

	public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		System.out.print(">>> ");
		int act=sc.nextInt();
		
		// [3] 풀이
		Connection conn=JDBCUtil.connect();
		PreparedStatement pstmt=null;
		final String sql="select * from test3 where act=?";
		VO vo=null;
		try {
			pstmt=conn.prepareStatement(sql);
			pstmt.setInt(1, act);
			ResultSet rs=pstmt.executeQuery();
			if(rs.next()) {
				vo=new VO();
				vo.setContent(rs.getString("content"));
				vo.setPdate(rs.getTimestamp("ptime")); // .getDate() -> 시분초 데이터를 못받아오므로 사용xxx
			}
			rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			JDBCUtil.disconnect(pstmt, conn);
		}
	
		if(vo==null) {
			System.out.println("act 입력범위를 확인하세요.");
			return;
		}
		System.out.println(vo);
		
	}

}

 

 


 

 

4. 마스킹_개인정보

: 아래의 member 테이블에서 0000에 해당하는 멤버의 name을 *로 출력하세요.

 ex) 1234 -> 티** | 9292 -> 모** | 5678 -> 아**

create table member(
   name varchar(30),
   phone varchar(20)
);

insert into member values('아무무','010-1234-5678');
insert into member values('티모','010-1222-1234');
insert into member values('아리','010-4321-4321');
insert into member values('모르가나','010-5050-9292');
insert into member values('릴리아','010-9890-8888');

select * from member;
drop table member;

 

 

1) 본인풀이

--이름의 자리수에 맞게 *출력 & 핸드폰 중간자리 출력--
select substr(name, 1, 1) || lpad('*',length(name)-1,'*') "firstName" ,substr (phone, instr(phone, '-')+1, (instr(phone, '-',-1)-1)-instr(phone, '-')) "midPhone"from test4;

 

2) 강사풀이

--이름의 자리수를 맞추지 않고, 공통되게 **로 지정 & 핸드폰 뒷자리 출력--
select (concat(substr(name,1,1),'**')) from member where substr(phone,instr(phone,'-',-1)+1) = '1234';
select (concat(substr(name,1,1),'**')) from member where substr(phone,instr(phone,'-',-1)+1) = '9292';
select (concat(substr(name,1,1),'**')) from member where substr(phone,instr(phone,'-',-1)+1) = '8888';

 

 


 

 

5. 그룹화_검색

: Null널한 코딩 팀에서 사용한 테이블을 가지고, 그룹화를 진행합니다. 그 후 각각의 그룹에서 전투력이 가장 높은 캐릭터의 정보를 출력해주세요.

 

create table heroes(
	cnum int primary key,
	cname varchar(40) not null,
	comics varchar(80) not null,
	power int default 0,
	reg date default sysdate
);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'드래곤볼','손오공',100);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'원피스','루피',90);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'나루토','나루토',90);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'근육맨','근육맨',95);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'북두의권','켄시로',85);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'실존인물','살라모하메드',66);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'드래곤볼','베지터',99);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'원피스','조로',85);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'나루토','사스케',85);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'근육맨','로빈마스크',85);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'북두의권','라오우',90);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'실존인물','려쉬티레츠벨',65);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'드래곤볼','피콜로',85);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'드래곤볼','트랭크스',90);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'원피스','상디',80);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'근육맨','테리맨',80);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'근육맨','라면맨',90);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'북두의권','토키',89);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'실존인물','주세페메아차',64);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'원피스','나미',60);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'나루토','사쿠라',70);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'실존인물','세바스티앙켈',63);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'원피스','우솝',65);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'근육맨','워즈맨',88);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'근육맨','버팔로맨',96);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'북두의권','쟈기',65);
insert into heroes (cnum,comics,cname,power) values((select nvl(max(cnum),0)+1 from heroes),'실존인물','요한크루이프',62);
select * from heroes;
drop table heroes;

 

1) 본인풀이

select a.cnum,a.comics,a.cname,a.power
from heroes a
inner join(
   select comics,max(power) power
   from heroes
   group by comics
) b on a.comics=b.comics and a.power=b.power;

 

2) 강사풀이

--풀이 1--
select a.cnum,a.comics,a.cname,a.power
from heroes a
inner join(
	select comics,max(power) power
	from heroes
	group by comics
) b on a.comics=b.comics and a.power=b.power;

--풀이 2--
select comics,max(power) from heroes group by comics;
select * from heroes
where comics='드래곤볼'
and power=(select max(power) from heroes group by comics having comics='드래곤볼');

 

 

 


 

반응형