국비

[ 31일차 ] SQL 시작 초기

코딩하는냥이 2025. 5. 28. 15:51
반응형

📌 예제 코드

1. Student 클래스 정의 및 Comparable 구현

public class Student implements Comparable<Student>{
	private String name;
	private int score;

	public Student(String name, int score) {
		this.name = name;
		this.score = score;
	}

	public String getName() {
		return name;
	}

	public int getScore() {
		return score;
	}

	public String toString() {
		return name + " (" + score + "점)";
	}

	@Override
	public int compareTo(Student o) {
		return Integer.compare(o.score, score); // 내림차순 정렬
	}
}

 

2. 스트림을 활용한 다양한 기능 구현

import java.util.*;
import java.util.stream.Collectors;

public class Example {
	public static void main(String[] args) {
		List<Student> studentList = new ArrayList<>();
		studentList.add(new Student("이명희", 92));
		studentList.add(new Student("장보고", 65));
		studentList.add(new Student("박민수", 78));
		studentList.add(new Student("김철수", 85));
		studentList.add(new Student("최지우", 92));

		// 1. 80점 이상인 학생 출력
		List<String> highScores = studentList.stream()
			.filter(s -> s.getScore() >= 80)
			.map(Student::getName)
			.collect(Collectors.toList());
		System.out.println("80점 이상 학생: " + highScores);

		// 2. 평균 점수 계산
		OptionalDouble optionalAve = studentList.stream()
			.mapToInt(Student::getScore)
			.average();
		System.out.println("평균 점수 : " 
			+ (optionalAve.isPresent() ? String.format("%.2f", optionalAve.getAsDouble()) : "Null"));

		// 3. 점수 기준 내림차순 정렬
		List<Student> sortedStudents = studentList.stream()
			.sorted(Comparator.comparingInt(Student::getScore).reversed())
			.collect(Collectors.toList());
		System.out.println("점수 내림차순 정렬 : ");
		sortedStudents.forEach(System.out::println);

		// 4. 최고 점수를 받은 학생 출력 (동점자 포함)
		int maxScore = studentList.stream()
			.mapToInt(Student::getScore)
			.max().getAsInt();
		studentList.stream()
			.filter(s -> s.getScore() == maxScore)
			.forEach(s -> System.out.println("최고 점수 학생: " + s.getName()));
	}
}

💻 실행 결과

80점 이상 학생: [이명희, 김철수, 최지우]
평균 점수 : 82.40
점수 내림차순 정렬 : 
이명희 (92점)
최지우 (92점)
김철수 (85점)
박민수 (78점)
장보고 (65점)
최고 점수 학생: 이명희
최고 점수 학생: 최지우

 

  • Comparable 구현으로 기본 정렬 기준 설정 가능
  • mapToInt().average()는 OptionalDouble로 반환되므로 null 처리 필요
  • Collectors.toList()로 스트림 결과를 리스트로 수집 가능
  • max(), filter() 조합으로 조건에 맞는 요소 추출

3. SQL 문법 분류

  • DDL: 테이블 등 구조를 정의 → CREATE, ALTER, DROP, TRUNCATE
  • DML: 테이블의 데이터를 조작 → SELECT, INSERT, UPDATE, DELETE
  • DCL: 접근 권한 제어 → GRANT, REVOKE
             트랜잭션 상태 관리 → COMMIT, ROLLBACK, SAVEPOINT

📌 정리하자면, 31일차에는 Student 클래스를 활용한 스트림 실습을 통해 필터링, 매핑, 정렬, 최고값 추출 등을 연습했습니다. 실습에서 다양한 방식의 평균 계산 및 정렬 처리 방법을 직접 구현해보고, 교수님이 작성한 예시 코드와 비교하며 학습의 깊이를 더했습니다. 또한 SQL 수업도 본격적으로 시작되어 DDL, DML, DCL 등 SQL 문법에 대한 이론 공부가 병행되었습니다.