rootblysub
All videos YouTube Subtitle Translation

SQL Full Course for Beginners (30 Hours) – From Zero to Hero

0:00
안녕하세요, SQL을 마스터하기 위한 이 독특한 과정에 오신 것을 환영합니다.
Hello and welcome to this unique course to master SQL.
0:03
제 이름은 바라 잘키니이며, 메르세데스-벤츠에서 10년 이상의 SQL, 데이터 엔지니어링, 데이터 웨어하우스 구축 및 데이터 분석 경험을 가지고 있습니다.
My name is Barra Zalkini and I lead big data projects at Mercedes-Benz over a decade of experience in SQL, data engineering, building data warehouses and data analytics.
0:12
물론, 첫 번째 질문은 이 과정이 왜 특별한가 하는 것입니다.
Now, of course, the first question is what makes this course so special?
0:16
SQL 코드를 작성하는 방법을 배우는 것뿐만 아니라, SQL이 어떻게 작동하는지에 대해서도 배우게 됩니다.
Well, not only you will learn how to write SQL codes, but more important than that, you will learn how exactly SQL works behind the scenes.
0:24
그래서 저는 수백 개의 애니메이션 비주얼을 사용하여 SQL의 복잡한 개념을 설명할 것입니다.
So I'm going to break complex concept in SQL using hundreds of animated visuals.
0:29
이렇게 하면 SQL을 이해하는 것이 훨씬 쉬워지고, 단순히 화면을 공유하고 코드를 보여주는 것보다 더 재미있습니다.
This makes it really easier to understand SQL and as well it is more fun than just sharing my screen and I just show you code right?
0:36
두 번째 이유는 이 과정이 저에 의해 진행된다는 것입니다.
The second reason is this course is taught by me.
0:39
저는 산업 경험이 있으며, SQL에 대해 제가 아는 모든 것과 실제 프로젝트에서 어떻게 사용하는지를 공유할 것입니다.
I have industrial experience and I will be sharing with you everything that I know about SQL and how I use it in my real projects.
0:46
그래서 저는 수백 가지의 모범 사례, 팁과 요령을 공유하고 SQL에서의 의사 결정 과정을 보여드릴 것입니다.
So I will be sharing with you hundreds of best practices, tips and tricks and I'm gonna show you my decision making process in SQL.
0:53
이 과정이 끝날 무렵에는 SQL을 사용하여 복잡한 작업을 해결할 준비가 되어 있을 것입니다.
So by the end of this course you will be ready to solve any complex task like I do using SQL.
0:59
그래서 이제 이 과정을 기본부터 시작하도록 설계했습니다.
So now I designed this course to cover the basics like
1:02
첫 번째 SQL 쿼리를 작성하는 방법을 배우고, 그 후에는 계속 발전할 것입니다.
writing your first SQL query and then we're gonna keep progressing
1:05
이 과정에서는 윈도우 함수, 저장 프로시저, 인덱스와 같은 고급 기술을 다룰 것입니다.
in the course by covering advanced techniques in SQL like the window functions, stored procedures, indexes and even at the end we're gonna build a data warehouse using SQL.
1:15
이 과정은 누구에게나 적합합니다. 데이터 엔지니어, 데이터 분석가, 데이터 과학자, 학생들 모두에게요.
And this course is suitable for anyone. Data engineers, data analysts, data scientists and even for students.
1:21
그리고 좋은 소식은 모든 것이 무료라는 것입니다. 처음부터 끝까지요.
And by the way the good news everything is for free. From the start until the ends.
1:26
저는 많은 자료, 코드, 프레젠테이션 및 애니메이션을 공유할 것입니다.
I will be sharing with you as well a lot of materials, code, presentations, and animations,
1:31
숨겨진 비용이 없으므로 아무것도 지불할 필요가 없습니다. 하지만 친구들, 대신에 채널이 성장할 수 있도록 지원해 주시면 정말 감사하겠습니다.
and there are no hidden costs, so you don't have to pay for anything. But my friends, in return, I really appreciate it if you support that channel in order to grow.
1:38
좋아요, 친구들, 정말 기대됩니다. 여러분은 어떠신가요? 동기부여가 되셨다면 저와 함께 SQL을 배우세요. 정말 멋질 것입니다.
All right, my friends, I'm really excited about it. I don't know about you. If you are motivated, join me learning SQL. This is going to be amazing.
1:45
자, 시작해봅시다. 모든
So let's go. All
1:51
좋아요, 이제 SQL에 대해 모든 것을 배우기 위한 로드맵을 보여드리겠습니다.
right, now I'm going to show you the roadmap in order to learn everything about SQL,
1:54
기본부터 시작하여 고급 단계로
starting from very basics and then advanced step by
1:57
진행하여 매우 고급 주제까지 도달할 것입니다.
step until we have very advanced topics so now at the
2:01
먼저 SQL이 무엇인지, 왜 배우는지, 데이터베이스와 그 유형에 대해 이해해야 합니다.
start we have to understand few stuff like what is sql why
2:04
이론을 배우고 나면, 여러분의 PC를 준비할 것입니다.
to learn it what are databases and the types of
2:07
데이터와 소프트웨어를 가지고, 모든 것을 갖추게 되면 우리는
databases and after the theory we're gonna prepare your pc with
2:10
데이터와 소프트웨어를 준비합니다.
data and the softwares now once we have everything then we
2:13
이제 모든 것이 준비되면 다음 장으로 넘어갈 수 있습니다.
can go to the next chapter this is the basics how to query data using sql and here we're gonna cover the basic components in each sql query like select from
2:23
기본 사항을 이해하면
where those basics now once you understand how to
2:26
데이터를 쿼리하는 방법과 데이터베이스에서 데이터를 가져오는 방법을 배웁니다.
query the data how to get the data out of the database the
2:29
다음 단계는 데이터베이스의 구조를 정의하는 방법을 배우는 것입니다.
next step we're gonna go and learn how to define the
2:32
새 테이블을 만들고 새 열을 추가하며 열을 제거하는 방법을 배웁니다.
structure of the database how to create a new table add
2:35
테이블을 삭제하는 방법도 포함됩니다.
a new column remove column and as well how to drop
2:38
이제 데이터 조작에 대해 배워야 합니다.
a table so with that you are defining new stuff in the database
2:42
테이블 안으로 들어가서 새 데이터를 삽입하는 방법, 데이터를 업데이트하는 방법, 데이터베이스에서 몇 개의 행을 삭제하는 방법을 배웁니다.
and then the next chapter you have to learn about the data manipulation this time we're gonna go inside the table and we're gonna learn how to insert a new data, how to update the data and as well delete few rows from our database.
2:54
이제 데이터 쿼리, 테이블 구조 정의 및 데이터 조작의 기본 사항을 배웠습니다.
So with that you have the basics, how to query data, how to define the structure of your tables and how to manipulate your data.
3:00
이제 SQL의 기본 사항을 다루었습니다.
And I can say with that you cover the basics about SQL.
3:03
이제 중급 단계로 넘어가 데이터 필터링 방법을 깊이 있게 배웁니다.
Now after that we start with the intermediate phase where we're gonna deep dive into topics like how to filter your data.
3:09
비교 연산자, 논리 연산자, BETWEEN 및 LIKE에 대해 배웁니다.
Here we're gonna learn about the comparison operators, logical operators, between end like.
3:15
조건을 구축하기 위해 사용할 수 있는 모든 연산자에 대해 배웁니다.
So all the operators that you can use in order to build a condition in
3:18
이후에는 이들을 결합하는 방법을 배워야 합니다.
order to filter your data then after that it's going to be very
3:21
조인 또는 집합 연산자를 사용하는 두 가지 방법이 있습니다.
interesting topic you have to learn how to combine them and here we
3:25
데이터 조인에 대해 배우는 것은 매우 흥미로운 주제입니다.
have two mechanism either using the join or using
3:28
여기서는 많은 내용을 다룰 것입니다.
the set operators and oh my god joining data it's
3:31
기본 조인부터 시작하여
going to be very interesting topic here we're going to cover like a lot of stuff
3:34
고급 조인으로 넘어갑니다.
like we can start with the basic joins and then we go to
3:37
올바른 조인을 선택하는 방법을 배워야 합니다.
advanced and then you have to learn how to choose the right join
3:40
여기에서 집합 연산자에 대해 배우고 여러 방법을 배웁니다.
and after that you have to learn about the set operators and here you have like four methods union union all except intersects so that you
3:48
여러 테이블을 결합하는 방법을 배웁니다.
learn how to combine multiple tables by combining
3:51
테이블의 열이나 행을 결합하는 것이 중요합니다.
the columns or the rows of your tables so this
3:54
이제 SQL을 사용하여 많은 작업을 수행할 수 있습니다.
is very important now moving on in our course now
3:57
SQL을 사용하면 데이터를 정리하는 많은 작업을 할 수 있습니다.
using sql you can do a lot of stuff cleaning up the data a
4:01
데이터 준비 작업이 많고, 마지막에는 많은 분석을 할 수 있습니다.
lot of data preparations and at the end you can do a lot
4:04
분석과 집계의 두 가지 가족처럼 보입니다.
of analytics and aggregations so they are like two families
4:07
함수의 첫 번째는 행 수준 함수입니다.
of functions the first one is the row level functions and
4:10
여기에는 문자열 값, 숫자, 날짜 및 시간 변환과 SQL에서 null을 처리하는 방법이 포함됩니다.
here we have a lot of stuff you can transform your string values the numbers date and time and how to handle the nulls in SQL and at the end the amazing case statements.
4:20
이 모든 것은 단일 값에 대한 변환입니다. 우리는 이를 행 수준 함수라고 부릅니다.
So all those stuffs are transformation for only one single value. We call it row level functions.
4:25
데이터 변환을 배우고 나면 SQL 함수를 사용하여 데이터 분석 및 집계를 수행하는 방법을 배워야 합니다.
And after you learn how to do data transformations, then you have to learn about how to do data analytics and aggregations using SQL functions.
4:33
우리는 집계 함수와 같은 기본부터 시작한 후, 윈도우 함수와 분석 함수로 깊이 들어갈 것입니다.
So we're going to start with very basics like the aggregate functions and then we're going to deep dive into the window functions, analytical functions.
4:40
여기에는 집계, 순위 및 값 함수가 있습니다.
And here we have like aggregates, ranking and value functions.
4:43
이들은 SQL에서 분석 작업을 수행하는 데이터 분석가나 데이터 과학자에게 매우 중요한 도구입니다.
Those are very important tool for any data analyst or data scientist doing analytics tasks in SQL.
4:49
행 수준 함수는 데이터 엔지니어를 위한 것이고, 분석 함수는 데이터 분석가를 위한 것입니다.
So I can say the raw level functions is for data engineers and the analytical functions are for data analysts.
4:55
8장에서는 이제 중급 수준을 다루었고, 마지막 4장은 SQL의 고급 내용이 될 것입니다.
So at the chapter eight, we can say you have covered now the intermediate level and the last four chapters, they will be the advanced stuff in SQL.
5:04
여기에는 SQL에 대해 배워야 할 많은 기술이 있습니다.
So here there are a lot of techniques that you have to learn about SQL.
5:07
첫 번째는 서브 쿼리로, 다른 쿼리 안에 있는 쿼리와 매우 유명한 CTE, 공통 테이블 표현입니다.
So the first one is the sub query, query inside another query and the very famous CTE, common table expression.
5:14
많은 개발자들이 이 기술을 좋아합니다. 그리고 나서 데이터베이스에서 뷰를 만드는 방법을 배울 것입니다.
A lot of developers like this one. And then you will learn about how to create views in the database.
5:19
이 기술을 배우면 SQL에서 정말 전문가가 될 것입니다. 그런 다음 선택을 사용하여 테이블을 만드는 방법을 배울 것입니다.
This technique, if you learn it, you're going to be really professional in SQL. Then we're going to learn how to create tables using select, the temporal tables.
5:27
그런 다음 세 번째 절차에 대해 배우고 SQL에서 프로그램을 작성하는 방법을 배울 것입니다.
And then we're going to learn about the third procedures, how to write a program in SQL. And after that, of course, comes the triggers.
5:33
이것들은 SQL에서 고급 프로젝트를 수행하기 위해 배워야 할 고급 기술입니다.
So those are the advanced techniques that you have to learn in SQL in order to do advanced projects using SQL.
5:40
모든 개념을 배우고 많은 SQL 코드를 작성하기 시작하면 일부 쿼리가 매우 느려질 것입니다.
So now once you learn all those concepts and you start writing a lot of SQL codes, you will notice that some query is going to be really slow.
5:47
그에 따라 쿼리 성능을 최적화하는 방법을 배워야 합니다.
And for that, you have to learn how to optimize the performance of your queries. And here there are a lot of techniques.
5:53
가장 유명한 방법은 데이터베이스에 인덱스를 생성하거나 파티션을 만드는 것입니다.
The most famous one is to create an index in the database or create a partition.
5:58
마지막으로, 쿼리 성능을 최적화하는 방법에 대해 제가 프로젝트에서 배운 10가지 최고의 모범 사례를 공유할 것입니다.
And at the end, I will be sharing with you the top 10 best practices that I have learned in my projects on how to optimize the performance of your queries.
6:06
이것은 매우 중요합니다. 그리고 나서 매우 흥미로운 주제로 넘어갈 것입니다.
So this is very important. And then we're going to move to a very interesting one.
6:10
AI인 Shadgbt나 Copilot을 SQL을 사용할 때 어떻게 사용하는지 공유할 것입니다.
I will be sharing with you how I use AI like Shadgbt or Copilot as I'm using SQL
6:16
프로젝트에서 올바른 프롬프트를 작성하여 AI의 도움을 받는 방법을 배워야 합니다.
in my projects so you have to learn how to write correct
6:19
AI로 도움을 받기 위해 올바른 프롬프트를 작성하는 방법을 배워야 합니다.
prompts to get assistance from ai as you are
6:22
SQL 프로젝트에 관한 것이며, 친구들, 여기서 해야 할 일은
using sql and finally and my favorite one it
6:25
SQL에 대해 배운 모든 것을 가져오는 것입니다.
will be about sql projects so my friends here you have to
6:28
실제 프로젝트와 함께 실습 프로젝트를 진행하며 도전 과제를 받게 됩니다.
bring everything that you have learned about sql in
6:32
그리고 어려움이 있을 것이며, 여기서 마법과 진정한 학습이 일어납니다.
hand-on projects with real projects you will get challenges
6:35
여기에는 세 가지 유형의 프로젝트가 있습니다. 첫 번째는
and struggle and here gonna happen the magic and the real
6:38
데이터 재배치 프로젝트로, 데이터 엔지니어링에 중점을 둡니다.
learning and here there are three types of projects the first
6:41
실제 데이터 웨어하우스를 구축하는 방법을 배우게 될 프로젝트입니다.
one is data rehousing project this is very data engineering focus
6:45
원시 형식의 데이터를 가져와 처리하는 방법을 배우게 될 것입니다.
project where you're going to learn how to build a real data warehouse
6:48
구축한 후에는 여러 레이어에서 데이터를 처리하게 됩니다.
where you're going to take the data from the raw formats and then process
6:51
그 후에는 데이터를 탐색하고 비즈니스에 대한 첫 통찰을 얻기 시작합니다.
it in different layers once you build it then you jump to another
6:54
마지막 프로젝트는 고급 데이터 분석 프로젝트입니다.
project you're going to start exploring the data and start getting
6:58
이것은 SQL 프로젝트를 수행하는 매우 중요한 섹션입니다.
the first insights about the business and the last project
7:01
SQL을 배우는 방법에 대한 로드맵입니다.
that you can do is the advanced data analytics project so this is very important section where you do sql projects so my friends
7:08
기본부터 중급까지 단계별로 진행됩니다.
this is the roadmap on how to learn sql so
7:11
그리고 고급 주제를 배우게 될 것입니다.
as you can see it takes you step by step from basics to intermediates
7:15
SQL에 대해 모든 것을 배우게 될 것입니다. 자, 이제 시작해 봅시다.
and you will end up having advanced topics and with that i can
7:18
첫 번째 장, SQL 소개입니다. 여기서 다룰 내용은
tell you you will learn everything about sql okay so now let's start with
7:21
몇 가지 주제입니다. 먼저 SQL이 정확히 무엇인지 이해해야 합니다.
the first chapter the introduction to sql and here we're gonna cover
7:24
왜 배워야 하는지, 데이터베이스가 무엇인지, SQL에서 사용하는 다양한 SQL 명령어에 대해 알아보겠습니다.
few topics so we have to understand first what is exactly sql
7:28
SQL에 대한 기본 이론입니다. SQL이 정확히 무엇인지 알아봅시다.
why we have to learn it what are databases and the different sql commands that we have in sql so it is the basics the theory about sql so what is exactly sql let's go
7:43
SQL이란 모든 것이 데이터를 생성한다는 것입니다.
so what is exactly sql everything generate data and
7:46
데이터는 어디에나 있습니다. 당신의 이름도 데이터입니다.
data is everywhere your first name is data your mobile
7:49
모바일 기기 안의 모든 것도 데이터입니다. 자동차도 많은 데이터를 생성합니다.
and everything inside the mobile is data car is as well generating a lot of data bank your finance statements everything is data and now of course the question is where do we store our data.
7:59
개인적으로 우리는 많은 데이터를 엑셀, 스프레드시트, 텍스트 파일에 저장합니다.
Personally, we store a lot of our data in like excels, spreadsheets in a text file.
8:04
그래서 당신은 많은 데이터를 다양한 파일에 저장합니다. 그렇다면 회사들은 어떨까요? 그들은 많은 데이터를 생성하는 많은 것들이 있습니다.
So you store a lot of your data in different files. Now, how about companies? They have a lot of things that generate a lot of data.
8:11
그들이 생산하는 제품과 고객들 또한 많은 데이터와 판매 정보를 생성하고 많은 것들이 있습니다.
That the products that they produce, their customers as well generating a lot of data and sales informations and a lot of things.
8:18
그래서 회사들은 방대한 양의 데이터를 생성합니다. 이제 큰 질문은 그들이 데이터를 어떻게 처리하고 저장하는가입니다.
So companies generate massive amount of data. So now the big question is how they handle the data, how they store it.
8:24
물론, 그들은 간단한 파일을 사용할 수 없습니다. 그들은 더 크고, 강력하며, 스마트한 것이 필요합니다. 그리고 여기서 데이터베이스가 등장합니다.
Of course, they cannot go and use like simple files, they need something bigger, stronger, and smarter. And here's where the database comes in.
8:31
그러니 데이터베이스에 대해 생각해 보세요. 데이터 저장을 위한 용기와 같습니다.
So think about the database. It's like a container for storing data.
8:35
하지만 단순히 파일을 폴더에 덤핑하는 대신, 데이터베이스는 데이터를 정리하여 접근하고 관리하며 검색하기 쉽게 만듭니다.
But instead of just dumping files into folders, the database organized the data so it is easy to access, to manage, and to search.
8:43
그래서 데이터베이스는 간단히 말해 데이터를 저장하는 용기입니다. 이제 왜 우리가 데이터베이스를 사용하는지 물어볼 수 있습니다.
So a database simply, it is a container that stores data. So now you might ask why we are using database.
8:49
우리가 개인적으로 사용하는 것처럼 파일을 사용할 수는 없나요? 자, 왜 우리가 데이터베이스를 사용하는지 말씀드리겠습니다.
Can't we just use files like I do it personally? Well, let me tell you why we use databases.
8:54
누군가가 다음 질문을 했다고 상상해 보세요. 당신의 데이터에서 총 지출을 찾아보세요.
Imagine that someone asked the following question, go and find the total spending in your data.
8:59
그래서 마이크가 총 지출과 비용을 찾기 위해 각 파일을 하나씩 열고, 비용을 검색하고, 데이터를 결합하려고 하면 매우 길고 혼란스러운 과정이 될 것입니다.
So now in order for Mike to find the total spending and the costs, he will be opening each of those files one by one, searching for the costs, trying to combine the data, and it's going to be very long and messy process.
9:11
하지만 반면에, 데이터가 데이터베이스에 있다면 질문을 하는 것이 매우 쉬울 것입니다.
But now in the other side, if your data in database and you want to ask a question, it's going to be very easy.
9:17
당신이 해야 할 모든 것은 데이터베이스에 질문을 하는 것입니다. 그러면 데이터베이스가 당신의 질문에 답할 수 있습니다.
So all what you have to do is to talk to the database to ask a question and the database can answer your
9:22
질문에 대한 결과와 함께 이제 데이터베이스와 어떻게 대화하는지에 대한 질문이 생깁니다. 우리는
question with a result and now comes of course the question how do we talk to a database well we use
9:28
sql을 사용합니다. sql은 당신이
sql sql is the language that you
9:31
데이터베이스와 대화하기 위해 사용하는 언어입니다. 그것은
use in order to talk to the database it stands for
9:34
구조적 쿼리 언어 sql입니다.
structured query language sql
9:38
여기에는 나처럼 sql이라고 부르는 사람들과 sql이라고 부르는 사람들이 있습니다. 옳고 그름은 없지만, 내가 이 과정을 따라가면 당신은 SQL이라고 부르기 시작할 것입니다.
and here you have people that call it sql like me and others that call it sql there is no right and wrong but if you follow me through the course i think you will start saying SQL.
9:48
SQL을 사용하면 데이터베이스에 질문할 수 있고, 데이터를 요청할 수 있으며, 데이터베이스는 결과를 보내어 질문에 답할 수 있습니다.
So by using SQL, you can ask the database, you can ask your data and the database can answer your question by sending you a result.
9:56
이 과정은 매우 쉽고 간단하며 빠릅니다. 그리고 이것은 데이터를 다양한 파일에 저장하는 것보다 훨씬 낫습니다.
So this process is very easy, simple and fast. And this is way better than having your data stored in different files.
10:02
우리가 데이터베이스를 사용하는 또 다른 이유는 그들이 정말 방대한 양의 데이터를 처리할 수 있기 때문입니다.
Another reason why we use databases is that they can handle really huge amount of data.
10:07
때때로 우리는 데이터베이스 안에 수백만 개의 데이터를 가지고 있습니다.
So sometimes we have like millions of data inside our database.
10:11
하지만 반면에, 당신이 스프레드시트 안에 데이터를 저장하고 방대한 양의 데이터를 가지고 있다면, 어떤 일이 발생할 수 있을까요?
But on the other side, if you are storing your data inside spreadsheets and you have like massive amount of data, what can happen?
10:17
당신의 스프레드시트는 그냥 망가질 수 있습니다. 그들은 큰 데이터를 처리할 수 없습니다.
Your spreadsheets can just break. They simply can't handle big data.
10:21
그리고 우리가 데이터베이스를 사용하는 또 다른 이유는 그것이 안전하다는 것입니다.
And another reason why we use databases is that it is just secure.
10:24
중요하고 중요한 데이터를 스프레드시트나 파일에 저장하는 것보다 데이터베이스에 저장하는 것이 더 안전합니다.
It is safer to store important and critical data inside a database than just storing it in spreadsheets and files.
10:31
그래서 데이터베이스는 안전하고 누가 무엇에 접근하는지 제어할 수 있습니다.
So the databases are secure and you can control who is accessing what.
10:35
그래서 데이터를 데이터베이스에 저장하는 것이 더 전문적입니다.
So it is just more professional to store the data inside a database.
10:39
자, 친구들, 지금까지 우리가 배운 것은 대부분의 회사가 데이터를 데이터베이스라는 컨테이너에 저장한다는 것입니다.
All right, my friends, so far what we have learned, most of the companies stores their data inside a container called a database.
10:46
그리고 여러분이 질문을 하고 데이터베이스와 대화하려면 SQL 언어를 사용해야 합니다.
And for you in order to ask questions and to talk to your database you have to speak the language of sql
10:56
이제 회사에서 일반적으로 어떻게 보이는지 보여드리겠습니다.
now i'm going to show you how it looks like usually in companies so we have
10:59
우리의 데이터는 데이터베이스 안에 있고 여러 사람이 있습니다.
our data inside the database and then you will have multiple people
11:03
여러 역할을 가진 사람들이 다양한 SQL을 작성하고 있습니다.
with multiple roles that are just writing different sqls
11:06
이제 직원과 사람들이 데이터베이스와 상호작용하는 것뿐만 아니라 웹사이트나 애플리케이션을 구축할 수도 있습니다.
in order to talk to the data but now not only employees and people interact with the database you could build a website or an application that as well interacts with the database by sending different SQLs.
11:18
물론, 애플리케이션과 웹사이트와 상호작용하는 사람 수에 따라 데이터베이스에 보내는 SQL의 양이 매우 많아질 수 있습니다.
And of course, depends on how many people are interacting with the application and the website, it might generate really massive amount of SQLs that sends to the database.
11:26
또한 데이터 시각화를 위한 도구가 있을 수 있습니다.
And not only that, you might have as well tools in order to do data visualizations, where you have like a dashboard or a report, maybe created using Power BI or Tableau.
11:36
이 도구는 이해관계자와 관리자들이 결정을 내리는 데 사용됩니다.
And it is used by stack holders and managers in order to make decisions.
11:40
이 도구들은 데이터베이스에 연결되어 SQL을 생성합니다.
And as well, those tools will be connected to the database and creating SQLs.
11:45
이제 여러분이 볼 수 있듯이 사람들, 애플리케이션, 도구와 함께 데이터베이스와 많은 상호작용이 있습니다.
So now as you can see we have a lot of interactions with the database from people, applications, tools.
11:51
많은 것들이 SQL을 생성하고 데이터베이스와 상호작용하고 있습니다.
A lot of things are generating SQLs and interacting with the database. But the database is just a container and storage right?
11:58
그래서 우리는 모든 요청을 관리하는 소프트웨어가 필요합니다.
So we need something, a software that manage all those requests.
12:02
그래서 데이터베이스 관리 시스템(DBMS)이라는 것이 있습니다.
And that's why we have something called database management system dbms.
12:06
이 소프트웨어는 다양한 요청을 관리할 수 있습니다.
So it is a software that can manage all those different
12:10
우리 데이터베이스에 대한 요청을 관리하고 우선순위를 정합니다.
request to our database and it gonna make the priority
12:13
어떤 SQL이 먼저 실행되어야 하는지를 관리할 수 있습니다.
which sql must be executed first this software can
12:16
SQL이 처음에 실행될 수 있는지 보안도 관리합니다.
as well manage the security whether the sql is
12:19
그래서 친구들, DBMS는 데이터베이스를 관리할 수 있는 소프트웨어입니다.
allowed to be executed in the first place so my friends the
12:22
DBMS는 데이터베이스를 관리할 수 있는 소프트웨어입니다.
dbms is the software that can manage the database
12:26
우리 데이터와 소프트웨어가 있지만 여기서 부족한 것은 하드웨어입니다.
and now we are not done yet there is something missing so we have
12:29
실제 회사에서는 PC에서 실행할 수 없습니다.
our data we have the software what is missing here is the hardware so in real companies we cannot run that on our pc because first our pc is weak and as well
12:37
오프라인으로 전환되기 때문에 서버가 필요합니다.
it goes offline that's why we need a server server
12:41
이것은 매우 강력한 PC와 같고 24시간 운영됩니다.
it is like a very powerful pc and as well it lives 24
12:44
그래서 항상 사용할 수 있으며, 여기서 우리는 회사 내부에 서버를 두거나 클라우드를 사용할지 결정할 수 있습니다.
7 so it is always available and here we can decide whether
12:47
서비스를 통해 데이터베이스를 운영할 수 있습니다.
we can have a server inside the company or we can use cloud
12:51
친구들, 지금까지 우리가 배운 것은 데이터베이스가 데이터를 저장하는 컨테이너라는 것입니다.
services in order to run our database so
12:54
SQL은 데이터베이스와 대화하기 위한 언어이며, DBMS는 데이터베이스를 관리하는 관리자입니다. 서버는 데이터베이스가 존재하는 물리적 기계입니다.
my friends so far what we have learned the database it is container to
12:57
이것이 어떻게 생겼는지 보십시오. 그리고 이제 친구들, 다양한 유형의 데이터베이스가 있습니다.
store the data the sql it is the language in order to talk to the database the dbms it is the manager it manages the database and the server it is the physical machine where the database lives.
13:09
그럼 우리가 가진 것을 살펴보겠습니다. 첫 번째이자 가장 유명한 것은 관계형 데이터베이스입니다. 매우 간단합니다.
So this is how it looks like. And now my friends, there are different types of databases.
13:17
스프레드시트와 같으며, 테이블이라고 부르며 열과 행이 있습니다.
So let's see what we have. The first and the most famous one, it is the relational database. It is very simple.
13:23
그런 다음 이러한 테이블 간의 관계가 있어 서로 어떻게 연결되는지를 설명합니다. 그래서 우리는 이를 관계형 데이터베이스라고 부릅니다.
It is like spreadsheets, call them table where we have columns and rows.
13:27
사람들이 데이터베이스를 들으면 이것을 생각할 것입니다.
And then there is like a relationship between those tables to describe how they relate to each other. And that's why we call it relational database.
13:34
이제 우리는 키-값이라고 불리는 또 다른 유형의 데이터베이스가 있습니다.
So if people here a database they're gonna think about this
13:37
이번에는 데이터가 완전히 다르게 구성됩니다.
one now we have another type of databases called key value
13:40
키와 값의 쌍을 갖습니다. 생각해 보세요.
this time the data is organized completely different where you
13:43
큰 사전과 같으며, 단어와 그 정의가 있습니다.
have pairs of keys and values think about it
13:46
키와 단어의 정의가 있으며, 이것이 값입니다. 이제 다음으로 넘어가겠습니다. 이것은 중요한 열 기반 데이터베이스입니다.
it's like a big dictionary where you have a word like the
13:50
이제 데이터를 행으로 그룹화하는 대신 이 유형의 데이터베이스는 데이터를 열로 그룹화합니다.
key and the definition of the word this is the value and now moving on to the next one this is as well important column based so now instead of grouping the data by the rows this type of databases group the data into columns.
14:02
그래서 이를 열 기반이라고 부릅니다. 이는 방대한 양의 데이터를 처리하기 위해 매우 고급 데이터베이스입니다.
That's why it's called column paste. And this is very advanced database in order to handle a huge amount of data where the main purpose is to search for data.
14:10
이제 그래프 데이터베이스라고 불리는 다른 데이터베이스로 넘어가겠습니다. 여기서 주요 초점은 객체 간의 관계입니다.
Moving on to another database called graph database. The main focus here is the relationship between objects.
14:16
여기서 주요 아이디어는 데이터 포인트를 연결하는 방법입니다. 이제 마지막으로 문서 데이터베이스가 있습니다.
So the main idea here is how to connect my data points. And now finally, we have the document database.
14:22
데이터는 전체 문서로 저장되며, 데이터의 구조는 그리 중요하지 않습니다.
The data is stored as entire documents where the structure of the data is not that
14:26
더 중요한 것은 모든 것을 한 페이지에 맞추는 것입니다.
important what is more important is to fit everything in one page
14:30
하나의 문서에 모든 것을 맞추고, 이제 이 다섯 가지 유형을 보면 우리는
in one document and now if you look to those five types we can
14:33
문서, 그래프, 열 기반, 키-값을 그룹화할 수 있습니다.
group the document graph column based key value all
14:36
이 데이터베이스들은 NoSQL 데이터베이스라고 불립니다.
those databases called no sql databases
14:39
그리고 관계형 데이터베이스 SQL 데이터베이스입니다.
and the relational database sql database
14:42
그리고 이 과정에서는 관계형 데이터베이스에 초점을 맞출 것입니다.
and in this course we will be focusing of course on the relational
14:45
관계형 데이터베이스와 관련하여 마이크로소프트 SQL 서버, MySQL, PostgreSQL과 같은 데이터베이스에 대해 들어보셨을 것입니다.
database and i'm sure you have heard about like the microsoft sql server the mysql the postgres sql all those databases they are sql
14:54
키-값 데이터베이스로는 Amazon DynamoDB가 있으며,
relational database and for the key value you have the radius the amazon dynamo db and we have for
15:00
열 기반 데이터베이스로는 Cassandra와 Redshift가 있습니다.
the column paste we have the cassandra and the redshift for the
15:03
그래프 데이터베이스로는 Neo4j와 매우 유명한
graph database we have the neo 4g and the very famous
15:06
MongoDB가 문서 데이터베이스로 존재합니다.
database the mongodb as a document database now
15:10
친구들, 이번 과정에서는 SQL에 집중할 것입니다.
my friends for this course we're going to be focusing on the sql
15:13
관계형 데이터베이스는 가장 유명하고 기업에서 가장 많이 사용되는 데이터베이스입니다.
relational databases because it is the most famous one and the most used one in companies and i will be focusing on the microsoft sql server so those are the different types of databases.
15:24
이제 데이터베이스는 매우 구조화되고 조직화되어 있습니다.
Now the databases are very structured and organized.
15:31
다음과 같은 계층 구조를 가지고 있습니다. 시작점은 서버입니다.
It has the following hierarchy. The starting point is the server.
15:34
우리가 배운 바와 같이, 서버는 강력한 PC이며 데이터베이스가 존재하는 곳입니다.
As we learned it is powerful pc and it is where the database lives and inside it we can have multiple databases.
15:41
따라서 판매를 위한 데이터베이스와 인사 관리를 위한 데이터베이스가 있을 수 있습니다.
So maybe you have a database for the sales and another one for the hr.
15:45
서버는 여러 데이터베이스를 호스팅할 수 있으며, 데이터베이스는 데이터의 컨테이너입니다.
So the server can host multiple databases and as we learned a database is a container of your data.
15:51
이제 각 데이터베이스에서 여러 스키마를 가질 수 있는 다음 단계로 넘어가겠습니다.
Now moving on to the next level in each database we can have multiple schemas.
15:55
스키마는 카테고리와 같으며, 관련 객체를 그룹화하는 데 사용할 수 있는 논리적 컨테이너입니다.
A schema it is like category or you can call it a logical container that we can use it in order to group up related objects.
16:02
예를 들어, 수백 개의 테이블이 있다면 주문과 관련된 모든 테이블을 하나의 스키마로 나누고 고객과 관련된 테이블을 다른 스키마로 나눌 수 있습니다.
Like let's say you have hundreds of tables so you can split all the tables that has to do with the orders in one schema and then another group of tables with the schema customers and so on.
16:12
따라서 테이블과 객체를 데이터베이스에서 조직하는 데 도움이 됩니다.
So it helps you to organize your tables and your objects in
16:15
이제 스키마 안으로 들어가면 여러 개의
the database and now if you go inside schema you can have multiple
16:18
객체가 있습니다. 테이블과 같은데, 이제 질문은 무엇인지입니다.
objects like tables so now of course the question is what
16:21
테이블은 스프레드시트와 같으며 데이터를 정리합니다.
is a table it is like spreadsheet it organize your
16:24
데이터는 열로 나뉘며, 열은 저장되는 데이터의 유형을 정의합니다.
data into columns the column define the data that
16:27
고객에 대한 열, 이름, 점수에 대한 열이 있습니다.
you store inside it so you have one column about the customer
16:31
생일에 대한 열이 있습니다. 각 열은 하나의 데이터 유형에 관한 것이며, 때때로 열을 필드라고 부릅니다.
id another column about the names the scores the
16:34
테이블에는 행이 있으며, 때때로 이를 레코드라고 부릅니다. 데이터가 실제로 저장되는 곳입니다.
birthday so each column is about one type of data and sometimes we call the columns as fields now the other thing that you have in tables is
16:41
이 예제에서 각 레코드는
the rows or sometimes we call it records it is where
16:44
실제로 데이터가 저장되는 곳은 이 예에서 각 레코드
actually the data is stored now in this example each record
16:48
하나의 고객, 하나의 사람을 나타내므로 우리는 하나
represent one customer one person so we have one
16:51
마리아 존의 레코드를 가지고 있으며, 이를 우리는
record from maria john and better those we call
16:54
행이라고 부릅니다. 이제 각 테이블에는 매우 중요한
them rows now in each table there is like one very important
16:57
기둥이 하나 있습니다. 이를 기본 키라고 하며, 항상
column called the primary key it is always very
17:00
고유 식별자가 필요합니다.
important to have like one unique identifier for
17:03
각 고객마다 각 행에 대해 우리는 이를 다양한 목적으로 사용합니다.
each customer for each row and we use it for different purposes in order to combine it with another table in order
17:09
하나의 고객을 빠르게 식별하기 위해서입니다. 그래서 그것은 고유합니다.
to identify quickly one customer so it is unique it's
17:13
지문과 같으며, 두 고객이 같은 ID를 가질 수 없습니다.
like fingerprint and there is no two customers having the
17:16
이제 열과 행의 겹침이 있습니다. 우리는
same id now the overlapping between the columns and the rows we
17:19
단일 값, 즉 셀을 가지고 있으며, 각 값은 각 열
have a single value a cell and each value each column
17:22
특정 데이터 유형을 저장합니다. 데이터 유형은
stores specific data type a data type it
17:25
우리가 저장하는 데이터의 종류입니다. 예를 들어 정수
is like what kind of data we are storing like an integer
17:29
1, 2, 30 또는 소수점이 있는 경우입니다.
1 2 30 or a decimal where you have a decimal
17:32
소수점 3.14를 저장하고 싶다면
point 3.14 now if you want to store characters
17:35
우리는 이를 위해 다양한 데이터 유형을 가지고 있습니다.
we have different data types for that like you want to store the
17:38
이름이나 설명을 저장하고 싶다면, 여기서 우리는
name or the description so here we can use the
17:41
char 또는 varchar를 사용할 수 있습니다. 그 안에
char or the varchar so you store inside them like the
17:44
마리아와 같은 이름을 저장합니다. 이제 char 또는
first name maria or something now you might ask what is a char or
17:47
varchar가 무엇인지 물어볼 수 있습니다.
varchar so the char always a fixed one so if
17:50
char는 항상 고정된 길이입니다. 만약
you define it like five characters always it's gonna go and reserve
17:54
5자로 정의하면 항상 5자를 예약합니다.
five characters from the space but if you want things more dynamic
17:57
공간에서 다이나믹한 것을 원한다면
then you go with the varchar and now moving on we have another data types called the date and time so if you want to store a date like the birth dates
18:05
varchar를 사용하고, 이제 우리는 날짜와 시간이라는 다른 데이터 유형이 있습니다.
and if you want to store the time information you can use the time
18:08
시간 정보를 저장하고 싶다면 시간 데이터 유형을 사용할 수 있습니다.
data type so we call those stuff int decimal char date
18:11
시간은 데이터 유형입니다. 그래서 친구들이 여러분이 할 수 있는 것처럼
time they are data types so my friends as you can
18:14
SQL 데이터베이스는 매우 조직적이고 구조화되어 있습니다.
see sql databases are very organized and structured okay
18:21
이제 SQL 자체에 대해 더 집중해 보겠습니다. SQL에는 다양한
so now let's focus more about the sql itself we have in sql different
18:25
명령 유형이 있습니다. 데이터베이스가 있고 이
type of commands so let's say that we have a database and this
18:28
데이터베이스는 비어 있습니다. 그래서 내부에 아무것도 없습니다. 이제 물론 여러분이 해야 할 첫 번째 작업은 SQL을 작성하는 것입니다. 'CREATE' 명령어를 사용하여 데이터베이스에 새로운 테이블을 생성하는 것입니다.
database is empty so we have nothing inside it now of course the first thing that you have to do is to write an sql with the command create in order to create a brand new table in the database.
18:39
이 명령어를 실행하면 데이터베이스가 하나를 생성합니다. 하지만 이 테이블은 비어 있습니다. 그래서 내부에 아무것도 없습니다.
So once you execute it, the database is going to go and build one. But this table is empty. So we have nothing inside it.
18:45
이제 여러분이 여기서 한 일은 새로운 것을 정의한 것입니다, 맞죠? 우리는 이러한 유형의 명령어를 데이터 정의 언어, 즉 DDL이라고 부릅니다.
So now what you have done here is you have defined something new, right? And we call this type of commands the data definition language, the DDL.
18:53
우리는 새로운 것을 생성하기 위해 'CREATE'를 사용하고, 이미 존재하는 것을 수정하기 위해 'ALTER'를 사용합니다.
We have create to create something new, alter in order to
18:56
그리고 무언가를 삭제하기 위해 'DROP'을 사용합니다. 예를 들어 테이블을 삭제하는 것입니다. 그래서 이것이
edit something that already exists, and drop in order to
18:59
첫 번째 명령어 집합입니다. 이제 테이블을 보면 비어 있습니다. 우리는 무엇이 필요합니까?
delete something, to drop, for example a table so this is
19:02
우리는 데이터가 필요합니다. 예를 들어 웹사이트나
the first family of commands now if you look at our table it is empty what
19:06
애플리케이션이 있다고 가정해 보겠습니다. 이제 이 애플리케이션은 많은 데이터를 생성하고 있습니다.
do we need we need data so let's say that we have a website or
19:09
이 애플리케이션이 데이터를 내부로 이동시키기 위해
an application now this application is generating a lot of data
19:12
우리의 새로운 테이블에 SQL 명령어 'INSERT'를 사용해야 합니다.
now in order for this application to move the data inside
19:15
따라서 'INSERT'를 실행하면 테이블에 새로운 데이터를 추가할 수 있습니다. 이러한 유형의 명령어를 데이터 조작 언어라고 부르며, 여기에는
our new table it must use the sql command insert
19:19
새로운 데이터를 삽입하기 위한 'INSERT', 이미 존재하는 데이터를 업데이트하기 위한 'UPDATE', 데이터를 삭제하기 위한 'DELETE'가 있습니다.
so if you execute inserts you can add new data inside your table this type of commands we call it data manipulation language and here we
19:27
데이터를 업데이트하고 삭제하기 위해, 테이블에서 데이터를 삭제하는 것입니다. 그래서 우리는 이를
have three commands insert in order to insert a new data update
19:30
데이터 조작 언어라고 부릅니다. 왜냐하면 여러분이 데이터를 조작하고 있기 때문입니다.
in order to update and already existing data and delete in
19:33
그래서 우리는 지금 무엇을 가지고 있습니까? 우리는 테이블이 있고, 내부에 데이터가 있습니다.
order to go and delete data from your table and that's why we call
19:37
이제 우리는 질문을 시작할 수 있습니다. 예를 들어 데이터에 대한 분석 질문이 있다고 가정해 보겠습니다. 이제 여러분이 해야 할 모든 것은
it data manipulation language because you are manipulating your
19:40
무언가를 작성하는 것입니다. 'SQL 쿼리'라고 부릅니다. 그 안에서 'SELECT' 명령어를 사용합니다. 하지만 전체를 쿼리라고 부릅니다.
data so what do we have now we have table we have data inside
19:43
그래서 데이터베이스에 쿼리를 보내면 질문이 있습니다. 데이터베이스는 결과를 반환할 수 있습니다.
the table now what we can do we can start asking questions so let's say that you have analytical question about your data now all what you have to do is to write something called
19:51
질문과 데이터베이스는 여러분의 쿼리에 대한 답변으로 데이터를 반환할 수 있습니다.
SQL query and inside it you use the command select but the whole thing we call it a query so you send a query to the database you have a
20:00
여러분의 질문에 대한 데이터를 반환하는 것입니다.
question and the database can return for you the result
20:03
우리는 SQL을 사용하여 이러한 활동을 데이터라고 부릅니다.
the data answering your query your question and
20:06
우리는 이러한 활동을 SQL을 사용하여 데이터라고 부릅니다.
we call this type of activities using sql the data
20:09
쿼리 언어이며 여기에는 하나만 있습니다.
query language and here we have only one and it is
20:12
매우 유명한 SELECT가 있으며 이를 사용하여
very famous we have the select we can use it in
20:15
데이터를 쿼리합니다. SQL에는 세 가지 명령이 있으며, 모든 것을 배울 것이지만, 올바른 답변을 위한 올바른 쿼리를 작성하는 데 대부분의 시간을 보낼 것입니다.
order to query our data so those are the three different commands in sql and of course we're gonna learn all of them but we will spend most of our time learning how to write the correct query for the correct answer.
20:32
이제 여러분은 저에게 물어볼 수 있습니다. 바라, 왜 SQL을 배워야 합니까? 시간이 돌아간다면 다시 SQL을 배울 건가요?
And now you might ask me, Bara, why we have to learn SQL? And if the time goes back, are you going to learn SQL again?
20:38
물론입니다. 제가 가진 세 가지 주요 이유가 있습니다. 첫 번째, 데이터를 다루기 위해 배워야 합니다.
Well, for sure, of course. And here are the top three reasons that I have. The first one, you have to learn it in order to talk to the data.
20:45
대부분의 기업은 데이터를 데이터베이스에 저장합니다. 이것이 표준 방법입니다. 그들이 이렇게 합니다.
You know, most of the companies stores their data in databases. And this is a standard way. This This is how they do it.
20:50
데이터 분야에서 일하고 싶고 그들의 데이터와 소통하고 싶다면 SQL을 사용해야 합니다.
And if you want to work on the company in the data field and you want to talk to their data, then you have to use SQL.
20:56
다른 언어를 사용하는 나라로 이사하고 오랫동안 살고 싶다면 그들의 언어를 말해야 합니다. 여기서도 마찬가지입니다.
It's like you move to another country where they speak another language and you want to live there for a long time. You have to speak their language. The same thing here.
21:04
데이터와 함께 일하고 싶다면 데이터베이스와 소통하기 위해 언어를 배워야 합니다, SQL을.
If you want to work with data, you have to learn the language in order to speak to the database, the SQL.
21:09
이것이 제가 생각하는 SQL을 배워야 하는 가장 중요한 이유입니다. SQL은 높은 수요가 있습니다.
So this is for me the most important reason why we have to learn SQL. And SQL, it is in high demand.
21:14
지금 소프트웨어 개발자의 직무 설명을 확인해 보세요.
if you go now and check the job description of the software developer
21:17
데이터 분석가, 데이터 엔지니어, 데이터 과학자, 약속합니다.
data analyst data engineer data scientist i promise
21:20
거기서 SQL을 요구할 것이라는 것을 알게 될 것입니다.
you you will find there that they're gonna demand for sql
21:23
거의 모든 직무 설명에서 SQL 기술을 요구할 것입니다.
so you will find they're gonna ask for sql skills almost
21:26
데이터 관련 직업을 확인하면 SQL 기술을 요구할 것입니다.
in each job description so if you check for any data related
21:30
또 다른 이유는 산업 표준이라는 것입니다.
jobs you will find that they're gonna ask for sql skills
21:33
여러 현대 데이터 플랫폼을 확인해 보세요.
now another reason that i have is it is industry standard
21:36
Power BI, Tableau, Kafka, Spark와 같은 도구들입니다.
so if you go and check multiple modern data platforms
21:39
Synapse를 통해 항상 SQL 코드를 입력해야 하는 섹션이 있을 것입니다.
and tools like power bi tableau kafka spark
21:43
대부분의 공급업체는 SQL을 채택합니다. 왜냐하면 그것이 표준이기 때문입니다.
synapse you will understand that there will be always a
21:46
그들의 도구가 쉽게 사용될 수 있도록 SQL을 채택합니다.
section where you have to enter sql code so most of
21:49
광범위하게 사용되며, 그들의 도구의 판매 포인트와 같습니다.
those vendors adapt sql because it is the standard it is
21:53
그래서 이것이 제가 생각하는 SQL을 배워야 하는 세 가지 주요 이유입니다.
widely used it is like selling points that their tools
21:56
SQL이 여전히 관련이 있고 왜 배워야 하는지에 대한 이유입니다.
are easy so those are my top three reasons why
21:59
SQL이 여전히 중요하고 배워야 하는 이유입니다.
sql still relevant and why you have to learn it okay my
22:02
친구들, 이제 SQL이 무엇인지, 왜 필요한지, 데이터베이스와 그 종류에 대한 명확한 이해가 생겼습니다.
friends so with that we have now clear understanding what is an sql why we need it what are databases and their different types
22:08
왜 DPMS 서버가 필요한지에 대해 이야기해 보겠습니다.
why do we have dpms servers and as well
22:12
이제 여러분은 데이터베이스 내부에서 사물이 어떻게 매우 잘 조직되어 있는지 이해하게 되었습니다.
now you have understanding how things are very organized and
22:15
데이터베이스 내부에서 구조화된 내용입니다. 이것이 SQL입니다.
structured inside the databases so that's all this
22:18
SQL과 데이터베이스에 대한 기본 사항을 다루었습니다. 이제 다음 단계로 넘어가서 환경을 설정할 것입니다.
is sql all right so with that we have covered the basics about
22:21
이제 설명의 링크로 가면 여러분은 제 사이트에 도착할 것입니다.
what is sql and databases now in the next step we're gonna go and set up our environment so that means we're gonna prepare your pc with the data with the databases and all the tools that you need in order to learn sql
22:37
뉴스레터 웹사이트에 도착하게 되며, 주간 소식을 원하시면 구독할 수 있습니다.
okay so now go to the link in the description and you will land here in my
22:40
내 콘텐츠에 대한 소식을 받을 수 있습니다.
newsletter website and you can subscribe if you want to get weekly
22:43
데이터와 다른 프로젝트에 대한 게시물도 있습니다.
news about my contents i make as well
22:46
그렇게 하면 이제 다운로드로 가겠습니다.
post about data and many other projects so once
22:50
여기에서 다양한 과정의 모든 자료를 찾을 수 있으며, 우리가 원하는 것은 SQL 궁극적 과정입니다.
you do that what we're gonna do now we're gonna go to the downloads over here
22:53
여기에서 모든 중요한 링크를 나열한 페이지에 도착하게 됩니다.
and you will find here all the materials of different courses and the one that we want is SQL Ultimate Course let's go over here now once you do that you will land to this
23:01
첫 번째이자 가장 중요한 것은 과정 자료를 다운로드하는 것입니다.
page where i have listed all the important links so the
23:04
여기에서 모든 코드, 슬라이드, 프레젠테이션을 찾을 수 있습니다.
first one and the most important one is to go and download the course materials
23:07
전체 과정 자료를 찾을 수 있으며, 원하지 않으시면 제 Git 저장소로 가실 수 있습니다.
here you can find everything code the slides the presentations the
23:11
거기에서 동일한 자료를 찾을 수 있습니다. 이제 다운로드하러 가겠습니다.
whole course or if you don't want that you can go to my get repository and
23:15
모든 것을 다운로드한 후, 다운로드한 폴더를 안전한 곳에 두세요.
there you will find exactly the same materials so let's go and download
23:18
이제 그 안으로 들어가서 세 가지를 찾을 수 있습니다.
everything okay so now go and put the downloaded folder somewhere
23:21
안전하고 들어가서 당신이 할 수 있습니다.
safe and let's go inside it and you can
23:24
세 가지를 찾을 수 있습니다. 첫 번째는 데이터 세트입니다. 안으로 들어가면 과정에 사용할 데이터베이스의 데이터를 찾을 수 있습니다.
find three things the first one is the data sets here if you go inside it you will find the data for the course the database that we will be using in order to practice SQL.
23:34
모든 것이 여기에서 제공됩니다. 이제 두 번째 폴더에는 모든 문서가 있습니다.
So everything is available here. Now the second folder you can find all the documentations.
23:39
즉, 모든 시각 자료, 프레젠테이션, 슬라이드, 제가 과정 중에 발표하는 모든 것이 여기에서 문서 노트로 제공됩니다.
So that means all the visuals, the presentation, slides, everything that I present during the course, it is available here as a documentation notes for you.
23:47
이제 세 번째로 넘어가면, 우리는 스크립트가 있습니다. 과정 중에 많은 SQL 코드를 작성할 것이며, 모든 코드가 여기에서 제공됩니다.
Now moving on to the third one, we have the scripts. So during the course we will be writing a lot of SQL codes and all those codes are here available.
23:55
즉, 그것들은 과정에서 사용되는 모든 코드입니다.
So that means those are all the codes that is used in the course
23:58
좋아요, 이제 모든 강의 자료를 갖추게 되었습니다.
okay so with that you have now all the course materials all right
24:01
이제 다음 단계로 가서 SQL Server Express를 다운로드해야 합니다.
so now in the next step that we have to go and download the sql server express and
24:05
여기에서 링크를 찾을 수 있으니 가보겠습니다.
you can find the link as well over here so let's go there
24:08
SQL Server Express에 도착했습니다.
sql server express and now we're gonna land on the microsoft
24:11
여기에서 Microsoft의 다양한 제공 사항을 볼 수 있습니다.
page where we can see the different offering from microsoft for
24:14
Azure에서 사용할 수도 있고 다운로드할 수도 있습니다.
sql server so either we have it on the azure or we can download
24:17
온프레미스에서 사용할 수 있지만, 그런 것들은 원하지 않으니 두 가지 옵션을 확인해 보세요.
it on the on-premises but we don't want those stuff just scroll down to see those two options so the first option on the left side we have the developer
24:25
왼쪽의 첫 번째 옵션은 개발자 에디션입니다.
edition you will get all the features and services that
24:28
모든 기능과 서비스를 제공받을 수 있습니다.
microsoft offers with the sql server it is as well
24:32
무료이지만 설치가 조금 복잡합니다.
free but the installation here is a little bit complicated
24:35
오른쪽의 두 번째 옵션은 익스프레스입니다.
but in the second option on the right side we have the express
24:38
여기 설치는 정말 빠르고 매우 쉽습니다.
edition installation here gonna be really fast and very easy
24:41
SQL 연습에 필요한 모든 것을 받을 수 있습니다.
you will get as well all the stuff that you need for practicing sql
24:45
그리고 SQL을 배우게 됩니다. 두 옵션 모두 무료입니다.
and learn sql so both of the options are free it's just a matter of the installation we will go now for the express So go and click download now.
24:53
지금 익스프레스를 선택하겠습니다. 지금 다운로드를 클릭하세요.
And it's very small file. So let's go and start it. And now the installation gonna start.
24:57
기본, 사용자 지정 및 다운로드가 있습니다.
So we have basic custom and download
25:00
미디어 다운로드는 지금 다운로드를 의미합니다.
media so download media means download now and later we're gonna do
25:03
설치는 사용자 지정으로 더 많은 제어를 할 수 있습니다.
the installation custom means we have more control on how
25:06
기본은 가장 쉽고 빠른 방법입니다.
to download and install the stuff the basic is the easiest
25:09
기본으로 진행하고 클릭해 보겠습니다.
one and the quickest one so let's go with the basics and click on
25:12
이제 설치를 클릭하고 애플리케이션 드라이버를 설치하겠습니다.
that and let's go and accept all those stuff and now let's click on install so now we're gonna install the applications drivers and so on it may take a little bit time
25:25
그렇게 하려면 SSMS 설치를 클릭해야 합니다.
so in order to do that let's go and click on install ssms
25:29
그 링크를 클릭해 보겠습니다.
so let's click on that and as well we can find a
25:32
SQL Server Management Studio로 가보겠습니다.
link over here so let's go to sql server management studio
25:35
그 링크를 클릭하면 제가 수집한 다른 링크도 찾을 수 있습니다.
so let's click on that you can find of course this link as well with
25:39
내가 수집한 다른 링크와 함께 이 링크를 찾을 수 있습니다.
the other links that i have collected so now we are again at microsoft page
25:42
스크롤을 내려보면 다음을 볼 수 있습니다.
let's go scroll down and now we will see the following
25:45
SQL Server Management Studio(SSMS) 무료 다운로드 링크입니다.
link free download for sql server management studio ssms so let's go and click on that and then it's going to go and
25:52
다운로드를 시작하겠습니다. 첫 번째로
download it let's go and start it so the first thing that
25:56
위치를 정의해야 합니다. 기본 설정으로 진행하겠습니다.
we have to define the location i will go with the default stuff so let's
25:59
설치를 클릭하세요. 알겠습니다.
click on install okay
26:03
설치가 완료되었습니다. SMS를 설치했습니다.
setup completed we just installed sms
26:06
SMS를 닫겠습니다.
sms so let's go and close it so
26:10
이제 시작해 보겠습니다. 메뉴로 가면
now let's go and start it if you go to your menu over here
26:13
SQL Server를 검색하면 SQL Server Management Studio를 찾을 수 있습니다.
search for sql server and you will find it here sql server management studio let's go and start it okay
26:19
이제 서버에 연결하기 위한 창이 열릴 것입니다.
so now we're going to get this window in order to connect to our server so
26:23
우리의 서버는 우리가 설치한 것입니다.
again what is our server it is the one we have installed at
26:26
첫 번째 단계는 SQL Server Express입니다.
the first step sql server express and that's
26:29
서버 이름에 PC 이름이 표시됩니다.
why you're going to see in the server name your pc name of
26:32
여기서 SQL Express라는 것이 있습니다.
course like it's not going to be my pc name but here we
26:35
데이터베이스 엔진으로 두고 SQL Express처럼 해야 합니다.
have something called sql express this is the server we just installed so in the first option we have database engines we have reporting services those are different stuff from microsoft
26:45
다음과 같은 방법이 있습니다. Windows 인증 또는 SQL Server 인증을 사용할 수 있습니다.
We're going to leave it as a database engine and it should be like this SQL Express. Now, how to access this database?
26:52
Windows 인증을 사용하고 사용자 이름은 PC 이름으로 하겠습니다.
We have the following stuff. We can do that using the window authentications or a scale server authentications.
26:57
정보가 없다면 CMD를 검색하세요.
I'm going to say that let's stick with the window authentication and the username going to be the PC name and as well that window user.
27:04
여기서 'who am I?'를 입력하면 PC 이름과 현재 로그인한 사용자를 알 수 있습니다.
If you don't have it for some reason, those informations, you can go to your search, search for CMD.
27:11
이것이 제가 여기서 보고 있는 것입니다. 데이터베이스 연결에 문제가 있다면 암호화를 확인하세요.
And then here you can say, who am I? And with that, you will get the PC name and as well the user that you are currently logged in.
27:20
암호화는 필수이며 서버 인증서를 신뢰하도록 클릭해야 합니다.
And this is exactly what I'm seeing over here. One more thing, if you're having issue connecting to your database, make sure to check the encryption.
27:26
이제 서버와 클라이언트가 준비되었습니다. 마지막 단계로 데이터베이스를 생성해야 합니다.
It should be mandatory and to click on the trust server certificates. So once you do that, you will be able to connect.
27:33
데이터를 삽입하고 싶습니다. 객체 탐색기를 열어보면 데이터베이스가 없습니다.
OK, so with that, we have the server, we have the client. And now the last step, we have to go and create the database.
27:39
이제 이에 대해 조치를 취해 보겠습니다.
We want to insert our data. So now if you look to the object explorer and open the databases, you can see that we don't have any database.
27:45
이제 뭔가 해봅시다. 강의 자료로 돌아가세요. 데이터셋 안에 다음이 있습니다.
So now let's do something about it. Go back to the course materials. Inside the datasets, you will find the following.
27:51
여기 세 개의 폴더, MySQL, Postgres, SQL Server가 있습니다.
You will find we have here three folders, MySQL, Postgres, and SQL Server.
27:56
MySQL과 Postgres와 같은 다른 데이터베이스를 사용하여 이 과정을 따르려면, 사용 중인 데이터베이스에 대한 동일한 데이터를 찾을 수 있습니다.
So if you want to follow this course using different databases like MySQL and Postgres, you can find the exact same data for the database that you are using.
28:04
이번 과정에서는 SQL Server를 사용합니다. 따라서 SQL Server 폴더 안으로 들어가면 다양한 확장자를 가진 네 개의 파일을 찾을 수 있습니다.
But now in this course, we are using the SQL Server. So if you follow me with that, go inside the SQL server folder and you will find four files with different extensions.
28:14
여기서 무슨 일이 일어나고 있나요? 이번 과정에서는 두 개의 데이터베이스가 있습니다. 하나는 매우 간단한 my database이고, 두 번째는 더 많은 테이블이 있는 sales DB입니다.
So what is going on here? Now for this course, we have two databases. One that is very simple called my database and second one that has more tables called sales DB.
28:24
SQL Server에서는 데이터베이스를 만드는 여러 방법이 있습니다. 데이터베이스를 만드는 두 가지 방법을 보여드리겠습니다.
And now in SQL server, there are multiple ways on how to create databases. I will show you now two methods on how to create the database.
28:31
첫 번째 옵션은 스크립트에서 데이터베이스를 만드는 것입니다. 이 파일들을 보면 .sql 확장자를 가진 두 개의 파일이 있습니다.
Now the first option, we want to create the database from scripts. And if you look to those files, we have here two files with the extension .sql.
28:39
이 파일들은 SQL 코드가 포함된 파일입니다. 첫 번째 파일인 init.sql server.mydatabase.sql부터 시작하겠습니다.
Those are files with SQL code. So let's start with the first one, the init.sql server.mydatabase.sql.
28:45
그 안으로 들어가세요. 이제 여기 SQL 코드가 있습니다. 모든 것을 복사하세요. 이제 스튜디오로 돌아갑시다.
Go inside it. And now here we have the SQL code. Copy everything. And now let's go back to our studio.
28:51
메뉴로 가서 새 쿼리를 클릭하세요. 가운데에 코드를 붙여넣을 수 있습니다. 이제 첫 번째 데이터베이스의 코드가 있습니다.
And then go to the menu and click on new query. And here in the middle, you can paste the code. So now we have the code for the first database.
28:58
이제 해야 할 일은 실행하는 것입니다. 실행하면 오류가 발생하지 않을 것입니다.
And all what you have to do is to go and execute it. So once we execute it, you will see you will not get any error.
29:04
왼쪽에서 데이터베이스가 보이지 않으므로 새로 고쳐야 합니다. 데이터베이스를 마우스 오른쪽 버튼으로 클릭하고 새로 고침을 클릭하세요.
And now on the left side, we don't see yet our database because we have to refresh. So right click on the databases and click refresh.
29:11
이제 my database를 볼 수 있습니다. 내용을 확인하려면 확장하고 테이블도 확장하세요.
And now you can see it, my database. So now let's see the content, go extend it and then go extend the tables.
29:17
이제 고객과 주문이라는 두 개의 테이블이 보입니다. 이 테이블 안에서 데이터를 찾을 수 있습니다.
And now you see here our two tables, customers and orders. Inside those tables, we can find our data.
29:21
데이터를 보려면, 예를 들어 고객을 마우스 오른쪽 버튼으로 클릭하세요. 그리고 '상위 1000개 행 선택' 옵션을 선택합니다.
In order to see the data, right click, for example, the customers. And let's go with the option, select top 1000 rows.
29:28
그렇게 하면 결과에서 다섯 명의 고객이 보입니다. 이것이 고객 테이블 안의 데이터입니다.
Once you do that, you can see now in the results, we have here five customers. This is our data inside the table customers.
29:35
여기서 인터페이스에 대해 다시 설명하겠습니다. 왼쪽에는 객체 탐색기가 있습니다. 데이터베이스의 전체 구조를 볼 수 있습니다.
So here again about the interface. On the left side we have the object explorer. Where you can see the whole structure of the database.
29:41
서버에서 데이터베이스, 테이블까지 전체 구조를 볼 수 있습니다. 상단에는 많은 아이콘이 있는 메뉴가 있습니다.
From server to databases to tables. So you can see the whole structure. On the top we have a menu with a lot of icons.
29:48
그리고 가운데에는 SQL 편집기라고 부르는 공간이 있습니다. 여기에서 SQL 코드를 작성할 것입니다.
And then in the middle. This place here we call it the SQL editor. We gonna go and write there SQL codes.
29:54
그리고 실행하면 아래에서 결과와 메시지를 받을 수 있습니다.
And then once you execute it at the bottom. You will get the result and messages.
29:59
SQL 편집기 아래에는 출력이 있습니다. 여기에서 예를 들어 볼 수 있습니다.
And below the SQL editor we have the output so here you can see for example
30:02
데이터, 결과 또는 다양한 메시지입니다.
the data the results or different messages from the
30:05
인터페이스는 매우 간단합니다. 이제 두 번째 데이터베이스를 가져와야 합니다.
database so the interface is very simple now we have to go and
30:08
파일로 돌아가면 두 번째 SQL 파일, init sql을 찾을 수 있습니다.
get our second database so if you go back to our files
30:11
server salesdb.sql을 열고 그 다음에 진행하세요.
you can find a second sql file the init sql
30:15
서버 salesdb.sql을 열고
server salesdb.sql open that and
30:18
여기서 모든 것을 복사하고 다시
let's go and copy everything here and let's go back to our
30:21
스튜디오로 가서 새로운 쿼리를 생성해야 합니다
studio same thing you have to go and and create a new query
30:24
그런 다음 전체 코드를 붙여넣고 이 데이터베이스는
then paste the whole code and this database is
30:27
판매 데이터베이스에 관한 것이므로 실행해 봅시다
about the sales db so let's go and execute it and
30:30
그렇게 하면 오류가 발생하지 않으며 이제 왼쪽으로 갑니다
with that we will not get any errors and now we go to the left side
30:33
같은 작업을 반복하고 새로 고침하면 두 번째
and we do the same thing refresh and we can see the second
30:37
데이터베이스 판매 db를 볼 수 있습니다. 이제 탐색해 보세요
database sales db now you can go and explore it so
30:40
확장하고 테이블로 가면 여기에서 다섯 개의 테이블을 볼 수 있습니다
extend it go to the tables and here you can see five tables
30:43
고객, 직원, 주문, 제품. 여기에서 이것은 우리 과정의 중간 데이터베이스입니다. 이제 데이터를 확인해 봅시다
customers employees orders products so here this is the intermediate database for our course so now let's go and check our data for
30:50
예를 들어, 주문으로 가서 마우스 오른쪽 버튼을 클릭하고 상위
example let's go to the orders right click on it and select top
30:53
1000을 선택하면 이것이 우리 데이터베이스의 주문입니다
1000 and those are the orders of our database
30:56
완벽합니다. 모든 것이 작동하고 있습니다. 이것이 주요
perfect so everything is working so those are the main
30:59
두 개의 데이터베이스입니다. 우리는 전체 과정에서 작업할 것입니다
two databases that we will be working through the whole course
31:03
물론 다른 데이터베이스를 사용하여 연습하고 싶다면
and of course if you want to go and practice using another database it's
31:06
전혀 괜찮습니다. 예를 들어, Microsoft에는 데이터베이스가 있습니다
totally fine for example in microsoft there are a database
31:09
모험 작업이라고 불리며 정말 놀랍습니다. 이제 가져오는 방법을 보여드리겠습니다. 여기로 가면
called adventure works it is really amazing and i'm gonna show you now how to import it we can go over here the adventure
31:15
작업이 있습니다. 이 링크를 클릭합시다. 이제 다시
works so let's click on this link so now we are again in
31:18
Microsoft 페이지에 있습니다. 아래로 스크롤하면 세 가지 다른
microsoft page if you scroll down you can see here three different
31:22
데이터베이스 유형을 볼 수 있습니다. 오래된 tb 데이터 웨어하우스
types of databases the old tb data warehouse
31:25
그리고 경량입니다. 서로 다른 데이터베이스처럼 보입니다.
and lightweight so they are like different databases the
31:28
오래된 tp는 가장 복잡한 것으로 많은
old tp is the most like complicated one a lot of
31:31
테이블과 트랜잭션이 있으며 데이터 웨어하우스는
tables and transactions and so on the data warehouse it
31:34
데이터 분석 및 기타 작업을 수행하기에 정말 좋은 것입니다. 경량은 가장 간단한 것입니다. 예를 들어 데이터 웨어하우스를 가져가 봅시다. 클릭하세요
is like really nice one in order to do data analyzes and stuff the lightweight is is the simplest one so let's go for example and get the data warehouse so click
31:43
그것을 클릭하면 이제 이 파일의 확장자가 보입니다.
on that and now as you can see the extension of this file is
31:46
점 bak이고 이제 두 번째 방법을 보여드리겠습니다.
dot bak and now i'm going to show you the second way
31:50
SQL Server에서 데이터베이스를 만드는 방법입니다. 이제
on how to create databases in sql server so now
31:53
다음 경로로 가면 됩니다. 설치한 위치에 따라 다릅니다.
all what you have to do is to go to the following path it really depends where
31:56
SQL Server를 설치했으므로 저는
you have installed the sql server so for me i've installed
31:59
프로그램 파일 Microsoft SQL Server MS에 설치했습니다.
it in the program files microsoft sql server ms
32:02
SQL SQL Express, 그런 다음 MS SQL 백업으로 가야 합니다. 여기에서 할 수 있는 것은 .bak 확장자를 가진 모든 파일을 배치하는 것입니다. 예를 들어, 방금 설치한 Adventure Works입니다.
sql sql express then ms sql backup you have to go there so here what you can do you can place all the files with the extension bak for For example, the adventure works that we just installed.
32:14
이것은 데이터베이스의 백업 파일이며, 우리는 이를 복원하고 싶습니다. 이를 통해 데이터베이스를 생성하게 됩니다.
This is a backup file for the database and we want to go and restore it. And with that, you are creating like a database.
32:21
그래서 이것은 SQL Server에서 데이터베이스를 복원하여 만드는 두 번째 방법입니다.
So this is the second method on how to create databases in SQL Server by restoring the database.
32:27
어떤 이유로 스크립트가 작동하지 않았다면, 이제 빠르게 방법을 보여드리겠습니다. 스튜디오로 돌아가서 데이터베이스를 마우스 오른쪽 버튼으로 클릭합니다.
If for some reason the script didn't work for you. Now let me show you quickly how we can do that. Let's go back to our studio. Right click on the database.
32:35
그리고 여기에서 데이터베이스 복원이라는 옵션이 있습니다. 클릭하세요.
And then here we have an option called restore database. Click on that.
32:38
그리고 이제 소스 데이터베이스 아래에 두 가지 옵션이 있습니다.
and now here we have two options under the source database and
32:42
기본값은 데이터베이스가 되지만 장치로 전환해야 합니다.
device the default gonna be database but we have to switch to
32:45
파일에서 가져오고 싶기 때문입니다.
a device because we want to import it from files and
32:48
그런 다음 세 개의 점으로 가서 클릭합니다. 이제
then we go to the three dots click on that and now
32:51
추가 옵션으로 가야 하며, 이제 SQL Server가 백업을 생성하는 위치로 안내할 것입니다.
we have to go to the option add and now it's gonna take you to the place
32:54
여기에서 파일을 찾을 수 있으며, 우리가 만들고자 하는 것은 Adventure Works입니다.
where the sql server creates backups so here we can find
32:57
그것을 선택한 다음 확인을 클릭합니다. 한 번 더 확인하고
our files and what we want you to create is the adventure works
33:01
마지막 확인을 클릭합니다. 이제 데이터베이스가 복원됩니다.
select that then okay one more okay and
33:04
성공적으로 복원되었습니다. 이제 왼쪽에서 세 번째 데이터베이스를 볼 수 있습니다.
one final okay so now the database will be restored and
33:08
보이지 않으면 새로 고침하세요. 여기에서 찾을 수 있습니다.
it is successfully so now on the left side we can see our third database
33:11
Adventure Works에 많은 테이블이 있으며, 평소처럼
if you don't see it go and refresh of course and here you will find
33:14
상위 천 개의 행을 선택하여 데이터를 탐색할 수 있습니다.
a lot of tables in the adventure works and as usual you
33:17
상위 천 개 행을 선택하여 데이터를 탐색할 수 있습니다.
can go and explore the data by selecting top thousand rows so
33:21
친구들, 이제 여러분은 세 개의 데이터베이스를 가지고 있습니다. 물론 우리의 초점은 우리가 만든 첫 번째 두 개의 데이터베이스인 제 데이터베이스와 판매 데이터베이스에만 있습니다. 이를 통해 데이터베이스를 가져오는 두 가지 방법을 배웠습니다.
my friends now you have three databases of course our focus is only the first two that we have done my database and sales db and with that i have learned two ways on how to import databases
33:31
SQL Server로. 그래서 친구들, 우리는 모든 것을 준비했습니다. 여러분의 로컬 PC에서 SQL Server Express가 실행되고 있습니다.
into SQL Server. So with that my friends we have prepared everything. We have the SQL Server Express running on your local PC.
33:38
우리는 스튜디오와 클라이언트가 있습니다. 이를 통해 데이터베이스와 상호작용할 것입니다.
We have the studio, the clients, where we're going to use it in order to interact with the database.
33:43
우리는 SQL 연습을 위해 사용할 두 개의 데이터베이스를 만들었습니다. 이제 준비가 되었습니다.
And we have created our two databases that we will be using in order to practice SQL. So we are ready.
33:49
좋습니다, 이제 우리는 SQL의 첫 번째 항목을 배우기 시작할 것입니다. 그것은 데이터를 쿼리하는 방법입니다.
Alright my friends, so with that we are done with the first chapter. We have our introduction to SQL and now we're going to start learning the first thing in SQL and that is how to query our data.
33:59
그럼 시작해 보겠습니다. 이제 SQL 쿼리가 무엇인지 정확히 이해할 수 있습니다.
So let's go and start with that. Okay, so now we can understand exactly what is an SQL query.
34:08
일반적으로 데이터는 테이블 안에 있고, 테이블은 데이터베이스 안에 있습니다.
Now, normally your data is inside the table and your table is inside the database.
34:12
이제 비즈니스에서 질문이 있을 수 있습니다. 예를 들어, 총 매출은 얼마인가요? 총 고객 수는 얼마인가요?
And now you might have a question from the business, like what is the total sales? What is the total number of customers?
34:19
당신이 마음속에 가지고 있는 질문이 있다면, 데이터를 요청하고 데이터베이스에서 데이터를 검색하고 싶습니다.
So any question that you have in your mind and you want to go and ask your data, you want to go and retrieve data from the database.
34:25
이를 위해 데이터베이스와 대화해야 하며, 그 언어가 SQL입니다.
And in order to do that, you have to talk to the database using its language, the SQL.
34:31
이를 위해 쿼리를 작성해야 하며, 쿼리 안에 선택문을 작성합니다.
So in order to do that, you're going to go and write a query where you write inside the query something called select statements.
34:38
이렇게 하면 데이터베이스에 데이터를 요청하는 것입니다. 쿼리를 실행하면 데이터베이스가 데이터를 가져오고 결과를 준비합니다.
And with that, you are asking the database for data. So once you execute your query, the database is going to go and fetch your data and then it prepares the results to be sent back to you.
34:48
이렇게 하면 데이터베이스에 질문을 하고, 데이터베이스는 쿼리를 처리하여 데이터를 반환합니다.
So with that, you are asking the database a question by writing a query and the database is going to process your query and answer your question by sending back data.
34:57
이렇게 하면 우리는 데이터베이스에서 데이터를 읽고 있습니다.
And with that, we are like reading our data from the database
35:00
쿼리는 아무것도 수정하지 않습니다.
and the queries will not modify anything will
35:03
테이블 안의 데이터를 변경하거나 데이터베이스의 구조를 변경하지 않습니다.
not change the data inside your tables or even change
35:06
그래서 선택문을 사용하여 데이터베이스에서 무언가를 읽고 싶습니다. 데이터베이스에서 데이터를 검색하고 싶습니다.
the structure of the database so you use select statement only in order to read something from the database you just want to retrieve data from the database so this is what we mean with a query.
35:18
이제 각 SQL 쿼리는 일반적으로 서로 다른 섹션과 구성 요소가 있으며, 이를 절이라고 부릅니다.
And now my friends, each SQL query has usually different sections, different components, we call them clauses.
35:28
놀라운 점은 데이터에 대한 질문에 맞는 쿼리를 작성할 수 있는 충분한 도구가 있다는 것입니다.
And this is amazing because you can have enough tools to write a query that matches any question that you have about your data.
35:35
우리는 필요한 쿼리를 작성하기 위해 모든 절을 단계별로 다룰 것입니다.
So what we're gonna do, we're gonna cover all those clauses step by step in order to write any query that you need.
35:41
이제 가장 간단한 두 개의 절부터 시작하겠습니다.
So now we're gonna start with two clauses that makes the simplest
35:44
SQL에서 가장 간단한 쿼리인 선택과 FROM입니다.
query in sql the select and from so
35:47
그럼 시작해 보겠습니다.
let's start with that all
35:51
지금은 SQL이 코드와 쿼리와 함께 어떻게 작동하는지 이해하는 것이 정말 중요합니다.
right so now it's really important for me that you understand
35:55
이제 오른쪽에서 SQL 쿼리의 구문을 보여주고 왼쪽에서 단계별로 보여주겠습니다.
how sql works with the code with the queries so
35:58
SQL이 쿼리를 실행하는 방법을 보여주겠습니다.
now what i'm gonna do i'm gonna show you on the right side the syntax of the query in sql and then on the left side i'm gonna show you exactly step by step
36:06
이제 데이터베이스 안에 고객 테이블이 있으며, 시작하겠습니다.
how sql gonna go and execute your query so now we have the
36:09
우리 데이터베이스에 고객 테이블이 있고 이제
table customers inside our database and we will start with the
36:12
가장 쉬운 형태로 모든 것을 선택할 것입니다.
easiest form where we're gonna select everything select
36:15
별표를 선택하면 모든 열을 가져옵니다.
the star so the select star is gonna go and retrieve
36:19
모든 열을 가져오고 SQL에 어디서
all the columns from your table so everything
36:22
데이터를 찾을지 알려줍니다. 선택으로 열을 선택합니다.
and the from clause is gonna tell sql where to
36:25
원하는 열을 선택하고, FROM에서 데이터가 오는 테이블을 지정합니다.
find your data so with the select we select the columns
36:28
각 쿼리는 항상 SELECT로 시작하고 이제
that we want and the from you specify the table where your data come from so the syntax can be very simple
36:34
모든 열을 원하므로 별표를 작성할 것입니다.
in each query we start always with the select and now
36:37
모든 것을 보고 싶다는 것을 이해할 것입니다. 그 후에
since we want all the columns we're gonna write star and with
36:40
FROM 키워드가 오고 이제 SQL에 어디서
that is going to understand i want to see everything and then after that
36:43
데이터가 오는지 알려줘야 합니다.
comes the keyword from and now we want to tell sql where the
36:46
이게 전부입니다. 실행하면
data come from so we have to specify the table name and
36:49
무슨 일이 일어날지, 먼저 FROM을 실행합니다.
that's it this is all what you need to do so once you execute it what's
36:53
절이 실행되어 모든 데이터를 가져옵니다.
gonna happen is going to go and execute first the from
36:56
데이터베이스에서 결과로 가져오고 다음 단계는
clause so it's gonna go and retrieve all the data from the
36:59
SELECT 문을 확인하는 것입니다. 어떤 열을
database to the results and then in the next step is going
37:02
결과에 유지할지 결정합니다. 별표를 사용하므로
to go and check the select statement so which columns we have
37:05
SQL은 모든 열을 유지하고 그렇게 되면
to keep in the results since you are saying star then the
37:08
결과에서 모든 열과 모든
sql gonna keep everything all the columns and with that you will see
37:11
행을 볼 수 있습니다. 이게 전부입니다.
in the result everything all the columns and all the
37:14
이렇게 작동합니다. 이제 다시 돌아가서
rows so that's it this is how it works now let's go back to
37:17
데이터베이스에서 몇 가지 데이터를 선택합니다.
scale in order to select few data from our database okay so
37:20
스튜디오로 돌아가서 새 쿼리를 시작하고
back to our studio let's go and start a new query and let's go and find our database just to expand it and our tables now it is very important to make make sure that you are connected to the correct database.
37:31
데이터베이스를 찾아 확장합니다. 올바른 데이터베이스에 연결되어 있는지 확인하는 것이 중요합니다.
So go to the top left in the menu over here and make sure to select your database.
37:35
왼쪽 상단 메뉴로 가서 데이터베이스를 선택하세요.
So my database like this or we have a command for that called use and then just write a database name like this.
37:42
그래서 SQL에게 이렇게 내 데이터베이스를 사용하라고 말하고 있습니다. 그렇게 하면 SQL이 내 데이터베이스로 전환할 수 있습니다.
So I'm telling SQL just use my database like this. And with that, SQL can switch to your database.
37:48
이제 새로운 프로그래밍 언어를 배우고 있다면 주석에 대해 이해하는 것이 매우 중요합니다.
Now, if you are learning any new programming language, it is very important to understand about that comments.
37:52
주석은 코드에 추가하여 무슨 일이 일어나고 있는지 이해하기 위한 메모와 같습니다.
So comments are like notes that you add to your code in order to understand what is going on.
37:58
데이터베이스 엔진은 이를 실행하지 않고 무시할 것입니다.
engine the database will not go and execute it it's gonna go
38:01
그 안의 모든 것을 무시하고 이를 수행하는 두 가지 방법이 있습니다.
and ignore everything inside it and there is like two ways on
38:04
인라인 주석을 만들려면 이렇게 두 개의 대시를 입력하면 됩니다.
how to do that either you make inline comments by typing
38:08
이렇게 두 개의 대시를 입력한 후 아무것이나 작성하면 됩니다.
two dashes like this and then you write anything this is
38:11
이것은 주석입니다. 이제 SQL에서 이를 보면
a comment so now in sql if you see it
38:14
녹색으로 표시되면 주석이라는 의미입니다. 이제 다른 유형의
is green that means it is a comments now the other type
38:17
여러 줄 주석을 가질 수 있으며, 이를 위해 슬래시와 별표를 입력한 후 아무것이나 작성할 수 있습니다.
you can have multiple line comments and in order to do that what you can do you can write slash and then star and then you can write anything
38:24
이것을 입력한 후 새 줄을 시작하면 주석입니다.
this and then start a new line is a comment
38:28
슬래시 뒤의 모든 줄을 보면
so as you can see all the lines after the slash
38:31
별표가 녹색으로 변하면 주석이라는 의미입니다.
star it is getting green that means it is a comment and
38:34
이제 끝에 있다고 가정해 보겠습니다. 닫으려면
now let's say that you are at the end so in order to close it you write
38:37
다시 별표와 슬래시를 입력하면 SQL에게 주석이 끝났다고 말하는 것입니다.
again star and then slash and with that you are telling SQL I'm
38:40
SQL에서 주석을 작성하는 두 가지 유형입니다. 이제 쿼리로 돌아가서
done with my comments so those are the two types of writing
38:44
모든 고객 데이터를 검색하는 작업이 있다고 가정해 보겠습니다.
comments in SQL now back to our query let's say that we have the following task says retrieve all customer data so I would like to see in the results
38:51
내 고객의 모든 데이터, 모든 행과
all the data of my customers everything all the rows
38:54
모든 열을 보고 싶습니다. 현재 데이터는
and all the columns so currently our data is stored inside
38:57
고객이라는 테이블에 저장되어 있으며, 모든 데이터를 보기 위해
the table called customer and i need to see all the data in the
39:00
쿼리를 작성할 것입니다. 모든 쿼리는 항상 SELECT로 시작합니다.
output in order to do that we're gonna write a query and
39:03
모든 열을 보려면 별표를 입력한 후 새 줄을 작성합니다.
all our queries start always with the select and since i need everything
39:07
SQL에게 데이터를 가져올 위치를 지정해야 합니다.
all the columns we write star and then a new line let's
39:10
테이블 이름은 데이터베이스에 있는 것과 정확히 같아야 합니다.
go and specify for sql from where it's gonna go and get the data so it's gonna be from and then we're gonna write the name of the
39:17
고객이라고 불리며, 여기서도 고객으로 작성해야 합니다.
table it must be exactly like it is in the database so
39:21
고객이라고 불리며 여기에 고객으로 있어야 합니다.
it's called customers and you have to have it here as a customers so
39:24
그게 다입니다. 이제 실행해 보겠습니다. 이제 결과를 보면
that's it let's go and execute it and now if you look to
39:27
결과를 보면 네 개의 열과 다섯 개의
the results you can see we have four columns and five
39:30
행이 있습니다. 이를 통해 테이블 내부의 모든 것을 볼 수 있습니다.
rows so with that you are seeing everything inside the table
39:34
고객을 볼 수 있으며, 다섯 명의 고객이 있습니다. 모든
customers you can see we have five customers and you can see all
39:37
고객에 대한 열이 있습니다. 이것은 매우 간단합니다. SQL 쿼리를 사용하여 데이터베이스에 질문을 했고, 데이터베이스는 결과로 데이터를 반환하여 우리의 질문에 답했습니다.
the columns about their customers so this is very simple we have ask question for the database using sql query and And the database did answer our question by returning our data in the results.
39:47
좋습니다. 이제 다른 작업으로 넘어갑니다. 새로운 쿼리를 만들 것이며, 이번에는 모든 주문 데이터를 검색할 것입니다.
All right. So now let's move to another task. I'm going to go and create a new query, and this time we're going to retrieve all the order data.
39:53
즉, 주문 내부의 모든 데이터를 보고 싶습니다. 매우 간단한 쿼리를 작성해 보겠습니다. 평소처럼 시작합니다.
So that means I would like to see all the data inside the orders. So let's go and write a very simple query. We start as usual.
40:00
선택으로 시작하며, 모든 것을 원하므로 선택 별표입니다.
with select and since we want everything so it is select star
40:03
우리의 주문 테이블에서
from our table orders so
40:06
그게 다입니다. 이제 실행해 보겠습니다. 출력에서 볼 수 있습니다.
that's it let's go and execute and with that you can see in the output
40:09
다시 네 개의 열이 있지만 이번에는
we have again four columns but this time we have only
40:12
네 개의 행만 있습니다. 즉, 이 테이블에는 네 개의 주문이 있습니다.
four rows so that means in this table we have four orders
40:15
이 테이블 내부의 모든 데이터를 볼 수 있습니다.
and we can see all the data inside this table so
40:18
그것으로 우리는 내부에 다섯 명의 고객이 있다는 것을 이해할 수 있습니다.
with that we can understand we have five customers inside
40:21
우리의 데이터베이스와 이 고객들은 네 개의 주문을 생성했습니다. 보시다시피 우리는 이제 데이터베이스와 대화하고 있으며, 이것이 SQL에서 가장 간단한 쿼리 형태입니다.
our database and these customers did generate four orders so as you can see we are now talking to our database and this is the simplest form of query in SQL.
40:34
좋습니다. 이제 쿼리의 다음 단계로 넘어가겠습니다. 여기서 나는 데이터베이스의 모든 열을 보고 싶지 않다고 말합니다.
Alright so now let's move to the next step in our query where you say you know what I don't want to see all the columns from the database.
40:41
나는 더 구체적이고 싶으므로 내가 필요한 열만 정확히 선택하고 싶습니다.
I want to be more specific so I would like to select exactly the columns that I need.
40:47
그래서 이제 우리는 데이터베이스에서 필요한 열만 선택하고 모든 것을 선택하는 대신 몇 개의 열을 선택하고자 합니다.
So now we want to select few columns from the database where we select only the columns that we need instead of everything.
40:53
이제 구문에 대해 조금 변경할 것입니다. 별표 대신 우리가 출력에서 보고 싶은 열 목록을 만들 것입니다.
Now about the syntax we're going to go and change a little thing. So instead of using star, we're going to go and make a list of columns that we want to see in the output.
41:02
그래서 우리는 첫 번째 열, 두 번째 열을 선택하고 쉼표로 구분할 것입니다.
So we're going to select column one, column two, and we're going to separate them using a comma.
41:06
우리는 선택 바로 뒤에 열 목록을 작성하고 있습니다. 그리고 from은 그대로 유지됩니다. 그러니까 테이블에서.
So we are just writing a list of columns exactly after the select. And for the from, it's going to stay as it is. So from a table.
41:13
이제 이것을 실행하면 어떤 일이 발생할까요? 일반적으로 SQL은 from으로 시작합니다. 그래서 데이터베이스에서 데이터를 가져옵니다.
Now, if you execute this, what can happen? As usual, SQL is going to start with the from. So it's going to go and get the data from the database.
41:20
그 다음 단계는 select를 확인하는 것입니다. 그래서 발생할 수 있는 일은 두 개의 열만 유지하는 것입니다.
And then the next step is going to go and check the select. So what can happen is going to go and keep only two columns.
41:26
예를 들어 이름과 국가와 같은 모든 것들입니다.
like for example the name and the country and all the
41:29
선택 문에 언급되지 않은 열은
columns that are not mentioned in the select statements will
41:32
제외되므로 SQL은 결과에서 제거합니다.
be excluded so SQL gonna go I remove it from the results
41:35
우리가 언급한 열만 유지합니다.
and keeps only the columns that we mentioned in our
41:38
이번에는 출력에서 두 개만 가질 수 있습니다.
query so this time instead of having four columns in the output we
41:42
그렇게 하면 열을 필터링하는 것입니다.
can have only two so with that you are like filtering the columns
41:45
필요한 것만 선택하고 SQL로 돌아가서 연습해봅시다.
and you are selecting exactly what you need so now let's go back to SQL in order to practice this all right so now we have
41:52
다음 작업은 각 고객의
following task and it says retrieve each customer's
41:55
이름, 국가 및 점수를 가져오는 것입니다.
name country and score so that means i
41:58
고객 테이블의 모든 내용을 보고 싶지 않습니다.
don't want to see everything from the table customers i need only
42:01
세 개의 열만 보려면 어떻게 해야 할까요?
to see the three columns so let's see how we can do that as
42:04
먼저 고객 테이블의 전체를 보려면
usual we start with select and i'm gonna go with the star in order
42:07
이전과 정확히 같습니다. 실행해보면 고객 테이블의 모든 내용을 볼 수 있습니다.
to see the whole table first from the table customers so
42:10
하지만 작업에서는 세 개의 열만 필요하다고 합니다.
it's exactly like before let's go and execute it and now i can see everything inside the table customers but the task says i need only three columns so now So now what we're going to do instead of the star, we're going to make a list of columns.
42:21
그래서 새로운 줄을 시작하고 첫 번째 열의 이름을 씁니다.
So we start a new line and then we write the name of the first column.
42:26
첫 번째 이름과 두 번째 열인 국가를 위한 새로운 줄입니다.
So the first name and a new line for the second column for the country. And then again a comma and then we write a score.
42:33
그렇게 하면 세 개의 열이 생깁니다.
So with that, we have the three columns. Now what I usually do, I go and select them and give it then a push using a tab.
42:40
이렇게 하면 선택과 열 목록 사이에 있습니다.
This just looks nicer and easier to read. So with that, we have now between the select and from list of columns.
42:45
마지막 열 뒤에 쉼표를 입력하는 실수가 자주 발생합니다.
Now there is like mistake that happens a lot where we go and type a comma after the last column.
42:50
그렇게 하면 오류가 발생합니다.
So if you do that and execute it you will get an error because SQL gonna expect from you a column after the comma.
42:56
이제 그것을 제거하고 실행해보겠습니다.
And since there is no column and immediately you have a from you will get an error. So there is no need for a comma after the last column.
43:03
출력에서 네 개의 열이 아닌 세 개만 있습니다.
Now let's remove it and execute. And now that you can see in the output we don't have four columns we have only three.
43:09
첫 번째 이름, 국가 및 점수입니다.
The first name the country and the score. and by the way they
43:12
선택한 대로 정확히 정렬되어 있습니다.
are ordered exactly like you selected in
43:15
첫 번째 이름, 그 다음에 국가입니다.
your query so first we have the first name and then the country
43:18
마지막으로 점수입니다.
and then the last one the score so that means if i go and now
43:21
순서를 변경하므로 국가를 가져옵니다.
change the order so let's get the country
43:25
마지막에 실행하면 국가를 볼 수 있습니다.
at the end and execute you will see the country at
43:28
마지막에 실행하면 국가를 볼 수 있습니다.
the end but i'm gonna go and put it back in between to
43:31
작업과 정확히 일치하도록 마지막 쉼표를 제거합니다.
match exactly like the task and remove the last comma so
43:34
다시 실행하고, 그로 인해 몇 개의 열을 선택했습니다.
execute again and with that we have selected few columns from
43:38
우리가 필요한 것에 더 구체적입니다. 이제 선택할 내용을 다루었으니, 다음으로 데이터 필터링에 사용할 수 있는 WHERE 절에 대해 이야기하겠습니다.
our table so we are more specific to what we need okay so with that we have covered the to select and from next we're going to talk about the where clause that you can use in order to filter your data so let's go
43:54
정확히 무엇인지, 우리는 WHERE를 사용하여
so what is exactly where we use where in order to
43:57
조건에 따라 데이터를 필터링하고 조건을 충족하는 데이터는 결과에 남고, 조건을 충족하지 않는 데이터는 결과에서 필터링됩니다.
filter our data based on a condition and any data that fulfill the condition can stay in the output in the results and the data that don't meet the condition will be filtered out of the results.
44:09
조건은 무엇이든 될 수 있습니다. 예를 들어, 점수가 500보다 높아야 한다고 말할 수 있습니다.
Condition could be anything. Like for example, we say the score must be higher than 500 or you can say the country must be equal to Germany.
44:16
질문에 있는 모든 조건입니다. 이제 SQL의 구문을 살펴보겠습니다. 일반적으로 SELECT로 시작합니다.
So any condition that you have in your question. Now let's see the syntax in SQL. As usual, we start with a select.
44:22
우리가 필요한 열을 선택합니다. 그런 다음 데이터가 어디에서 오는지 작성합니다. 그리고 FROM 다음에 WHERE를 작성합니다.
We select the columns that we need. Then we write from where the data come from. And then after the from, we're going to write the where.
44:29
그 후에 조건을 지정합니다. 이제 SQL이 이를 실행하는 방법을 살펴보겠습니다. SQL은 일반적으로 FROM에서 시작합니다.
And exactly after that, you specify your condition. So now let's see how SQL can execute this. First, SQL starts as usual from the from.
44:36
데이터베이스에서 데이터를 가져올 수 있습니다. 그 후 SQL은 WHERE 절을 실행합니다.
So it can go and get your data from the database. And after that, SQL gonna go and execute the where clause.
44:43
조건이 500보다 높아야 한다고 가정해 보겠습니다.
So let's say that the condition should be higher than 500.
44:46
이제 무슨 일이 일어날 수 있는지 확인해 보겠습니다. 각 행이 이 조건을 충족하는지 확인합니다.
And now what can happen is we're gonna check each row whether it meets this condition or not.
44:51
예를 들어, 마리아는 점수 350이 500보다 높지 않기 때문에 조건을 충족하지 않습니다.
So for example, for Maria, she doesn't fulfill the condition because her score, the 350 is not higher than 500.
44:58
따라서 그녀는 조건을 충족하지 않으며 SQL은
So she doesn't fulfill the condition and SQL
45:01
이 행을 완전히 제거합니다.
gonna go and remove completely this row this
45:04
결과에서 두 번째 레코드로 이동합니다.
record from the results now is gonna go to the second record so
45:08
존은 조건을 충족하므로 결과에 남습니다.
John is fulfilling the condition so he gonna stay in
45:11
조지에게도 같은 일이 발생합니다. 이제 네 번째로 넘어갑니다.
the result the same thing for George now moving on to the fourth
45:14
마르틴은 이 조건을 충족하지 않으므로 SQL은 결과에서 제거합니다.
one Martin so this customer is not fulfilling the condition and SQL gonna go and remove it from the results the same things happened for the last customer the score is zero and not fulfilling the condition.
45:25
따라서 이 필터를 적용하면 SQL은 5명 중 2명만 반환합니다.
So that means if we apply this filter, SQL going to return only two customers out of five.
45:31
이제 조건에 따라 행을 필터링하고 있습니다.
So with that, we are filtering the rows based on condition using the where clause.
45:36
결과에서 모든 열을 얻고 있습니다. 그러나 쿼리에서 두 개의 열만 지정하면 SQL은 결과의 열도 제거하기 시작합니다.
Now as you can see in the results, we are getting all the columns. But if you specify in the query, like for example, only two columns, like the name and the country, then SQL going to start removing as well the columns of the results.
45:48
출력에서는 두 개의 열과 두 개의 행만 얻습니다.
And this means in the output, we will get only two columns and two rows.
45:53
이렇게 하면 결과의 열과 행을 필터링하게 됩니다. 이제 연습을 위해 스케일로 돌아가 보겠습니다.
So with that, you are filtering the columns and the rows of your results. So now let's go back to scale in order to practice this.
45:59
좋습니다. 다음 작업을 해봅시다. 고객을 점수가 0이 아닌 고객으로 가져오라고 합니다.
All right, so let's have the following task. And it says retrieve customers with a score not equal to zero.
46:05
작업을 보면 조건이 있습니다. 조건은 점수가 0이 아니어야 한다고 합니다.
So now if you are looking to our task, you see we have like here a condition. The condition says the score must not be equal to zero.
46:12
모든 고객을 보고 싶지 않습니다. 이 조건을 충족하는 고객만 보고 싶습니다.
So I don't want to see all the customers. I want to see only the customers that fulfill this condition.
46:17
데이터를 필터링해야 하니, 해결해 봅시다.
so it's like we have to filter the data so let's go and solve the
46:20
작업을 시작합시다. 일반적으로 별표를 선택합니다. 사양은 없습니다.
task let's start as usual select star there's no specifications
46:24
고객 테이블의 열에 대해 말하고 있습니다.
about the columns from our table customers okay
46:27
이제 시작하겠습니다. 실행해 보겠습니다. 결과를 보면
so i'm gonna start with this let's go and execute it now if you look
46:30
거의 모든 고객이 조건을 충족하고 있습니다.
to the result you can see like almost all the customers are fulfilling
46:34
단 한 명, 마지막 고객의 점수는 0입니다.
their condition their scores are not equal to zero
46:37
이 고객은 우리의 조건을 충족하지 않습니다. 이제
only one the last customer his score is zero
46:40
그에 대한 필터를 만들어 보겠습니다. 그래서 우리는 'where'를 사용할 것입니다.
so this customer does not fulfill our condition now let's go
46:43
조건을 만드는 방법에만 집중하는 섹션이 있을 것입니다.
and build filter for that so we're going to say where and now there
46:46
SQL에서 필터링하는 방법이니 구문에 대해 너무 걱정하지 마세요.
will be a section that is only focusing on how to build conditions
46:50
조건에 대해 나중에 다룰 것입니다. 하지만 매우 간단합니다.
and filtering in sql so don't worry a lot about the syntax
46:53
조건을 위해 열이 필요합니다. 어떤 열에서
of the conditions we're going to cover that later of course but it is
46:56
조건이 기반하는지, 점수에 기반할 것입니다.
very simple now for the condition we need a column so in which column
46:59
여기에 점수를 작성할 것이고, 우리는 같지 않다고 말하고 있습니다.
is our condition based on it's going to be on the score so we're
47:02
SQL에서 'not equal'이라는 연산자가 있습니다. 그 다음에 값을 작성해야 합니다.
going to write here score and since we are saying not equal
47:05
조건은 이렇습니다. 점수는 같지 않아야 합니다.
there is like an operator in sql called not equal then we have to write a value after that so it's going to be a zero so again the
47:11
0과 같지 않아야 합니다. 매우 간단하죠. 그리고 우리는 조건이 있습니다.
condition is like this the score must not be equal to
47:15
데이터를 필터링하기 위해 'where'를 사용하고 있습니다.
zero it's very simple right and with that we have our condition
47:18
이제 실행해 보겠습니다. SQL이
and we are using the where in order to filter the data
47:21
마지막 고객을 제거한 것을 볼 수 있습니다. 그는 조건을 충족하지 않기 때문입니다.
so let's go and execute it and now as you can see sql did
47:24
마지막 고객을 제거하세요. 그는 조건을 충족하지 않기 때문입니다.
remove the last customer because he is not fulfilling
47:27
이 조건을 충족하는 행만 남았습니다.
this condition and we have now only the rows that
47:30
우리의 조건을 충족하는 행만 남았습니다. 데이터를 필터링하는 것은 매우 간단합니다. 해야 할 일은 from 다음에 where 절을 작성하는 것입니다.
fulfill our condition so as you can see it is very simple how to filter the data all what you have to do is to write where clause after the from
47:38
그 다음 조건을 작성하세요. 이제 다른 작업을 해봅시다.
and then write a condition after that now let's have another task
47:41
예를 들어, 고객을 독일에서 검색하라고 합니다.
like for example it says retrieve customers from
47:44
그래서 저는 다른 나라의 모든 고객을 보고 싶지 않습니다.
germany so i don't want to see all customers from different countries
47:47
저는 독일에서 온 고객만 보고 싶습니다. 즉,
i just want to see the customers that come from germany so
47:50
고객의 국가에 대한 조건이 있습니다.
that means we have a condition here country of the customer
47:53
독일과 같아야 합니다. 그러니 현재 조건을 제거합시다.
must be equal to germany so let's go and remove the
47:56
현재 조건은 우리가 필요로 하는 것이 아닙니다. 결과를 보면 독일에서 온 두 명의 고객이 있습니다.
current condition it is not the one that we need and excuse if you are looking to the results we have two customers that come from
48:03
그래서 이 두 고객만 보여주고 싶습니다.
germany and we are interested only to show those two customers
48:06
그것을 위해 필터를 만들겠습니다. where 절을 작성할 것입니다.
so let's go and make a filter for that we're gonna write
48:09
그 후에 열이 필요합니다. 열은 국가가 될 것입니다.
where clause and after that we need a column the column gonna
48:13
그래서 여기에서 국가를 작성할 것이고, 이번에는
be the country so we're gonna write here country and this
48:16
국가가 독일과 같아야 합니다.
time the country must be equal to germany
48:19
같은 값을 작성할 것입니다. 하지만 지금 보시다시피 오류가 발생하고 있습니다.
so we're gonna write an equal operator so we're gonna write germany
48:22
SQL에서 문자를 포함하는 값을 작성하려면
like this exactly like the value inside our data but now as you can see we are getting like an error here and that's because in sql if
48:29
두 개의 작은 따옴표 사이에 넣어야 합니다. 시작할 때
want to write a value that contains characters then
48:33
작은 따옴표를 넣고 끝에도 넣어야 합니다. 이제 보시면
you have to put it between two single quotes so at the start you
48:36
빨간 선이 사라지고 값이 빨간색으로 변했습니다.
put a single quote and as well at the end and now as you can
48:39
그것은 문자열 값이기 때문입니다. 값입니다.
see the red line is away and the value now is red and
48:42
문자를 포함하고 있으며, 그렇게 하면 오류가 발생하지 않습니다.
that's because it is a string value it is a value
48:45
열에 숫자만 포함되어 있다면 쓸 수 있습니다.
that contains characters and with that you will not get an error
48:48
작은 따옴표 없이. 하지만 값에 문자가 포함되어 있다면
so if your columns contains only numbers you can write it
48:51
두 개의 작은 따옴표 사이에 써야 합니다. 알겠죠?
without single quotes but if your values contains characters
48:55
그럼 이제 조건으로 돌아가서 국가가 독일과 같아야 합니다.
then you have to write it between two single quotes okay so now
48:58
이제 조건으로 돌아가서 국가가 독일과 같아야 합니다.
back to our condition the country must be equal to germany
49:01
이제 출력에서 조건을 충족하는 고객만 보고 있습니다.
let's go and execute it and it is working so as you can see
49:04
이제 출력에서 조건을 충족하는 고객만 보고 있습니다.
now we are seeing in the output only the customers that's fulfill
49:07
국가가 독일과 같다는 제 조건입니다.
my condition where the country is equal to germany so
49:10
이것이 바로 where 절을 사용하는 방법입니다.
this is exactly how we work with the where clause in
49:14
우리 데이터를 필터링하기 위해서입니다.
order to filter our data so my friends this is how you filter your rows
49:17
이제 행을 필터링하고 싶다고 가정해 보겠습니다.
and now let's say that i would like to filter the rows together with
49:20
열을 함께 필터링하고 싶습니다.
the columns so i just want to keep the first name and the country
49:23
첫 번째 이름과 국가만 유지하고 싶습니다.
and not interested to see the scores and the ids so in
49:26
점수와 ID는 보고 싶지 않습니다.
order to do that we're gonna go to the select and list the columns
49:29
그렇게 하려면 select로 가서 열을 나열해야 합니다.
that we want to see so the first name and after that a
49:32
우리가 보고 싶은 것들입니다.
comma then the country and that's it so
49:36
첫 번째 이름 다음에 쉼표를 넣고 국가를 적습니다.
let's go and give it a push and execute it so we have
49:39
그게 전부입니다.
two rows and two columns so guys as you can see sql
49:42
두 개의 행과 두 개의 열이 있습니다.
is very simple all right so with that you have learned how to filter your data using the where clause next we're we're going to talk about how to sort your data using the order by.
49:52
SQL은 매우 간단합니다.
So let's go. Okay, so what is exactly order by?
49:58
이제 where 절을 사용하여 데이터를 필터링하는 방법을 배웠습니다.
You can use this type of clause in order to sort your data. And of course, in order to sort your data, you have to decide on two mechanism.
50:06
다음으로는 order by를 사용하여 데이터를 정렬하는 방법에 대해 이야기할 것입니다.
Either you want to sort your data ascending from the lowest value to the highest value, or exactly the opposite way using descending from the highest value to the lowest.
50:15
자, 그럼 시작해 보겠습니다.
And the syntax can now looks like this. So as usual, we start with a select and then from and after the from, you can specify order by.
50:23
order by는 정확히 무엇인가요?
and with that you are telling sql we have to sort the data and you
50:26
이 유형의 절을 사용하여 데이터를 정렬할 수 있습니다.
have to specify two things first you have to specify for sql
50:29
데이터를 정렬하기 위해 두 가지 메커니즘을 결정해야 합니다.
the column that should be used in order to sort the
50:32
데이터를 오름차순으로 정렬할지, 내림차순으로 정렬할지 선택해야 합니다.
results so for example you can say score and after the
50:36
구문은 다음과 같이 보일 수 있습니다.
column name you have to specify the mechanism so for example you say
50:39
가장 낮은 것에서 가장 높은 것으로, SQL에서는
ascending from the lowest to the highest and in sql if
50:42
메커니즘을 지정하지 않으면 기본값은
you don't specify the mechanism the default gonna be
50:45
오름차순이므로 아무것도 지정하지 않아도 오류가 발생하지 않습니다.
ascending so you will not get an error if you don't specify anything
50:49
열 이름 뒤에 항상
after the column name but my advice here is always
50:52
무언가를 지정하는 것이 더 쉽습니다.
to specify something after the column easier
50:55
그것은 간단하고 이해하기 쉬우므로
because it's just straightforward and easier to understand and
50:58
누군가 읽으면 즉시 오름차순임을 이해할 수 있습니다.
if someone reads it can understand immediately it's going to be ascending
51:01
모두가 기본값이 무엇인지 알지 못할 수 있으므로
because maybe not everyone knows what is the default in
51:05
값을 항상 지정하세요, 비록
sql so always specify a value even if it's
51:08
건너뛰는 것이 더 쉬워도, 데이터 저장을 원하면
like easier to skip it and if you want to store the data from the
51:11
가장 높은 것에서 가장 낮은 것으로, 내림차순을 지정할 수 있습니다.
highest to the lowest then you can specify descending so
51:14
SQL은 일반적으로 시작하여 데이터를 가져옵니다.
as usual sql gonna go and start from the from it's gonna go and grab
51:17
데이터베이스에서 데이터를 가져온 후 두 번째 단계는
your data from database then the second step is going to
51:20
결과를 정렬하는 것이며, ORDER BY가 실행됩니다.
go and sort the results so the order by gonna be executed
51:23
정렬할 것이며, 점수로 정렬할 것입니다.
and it's gonna see okay i'm gonna sort it by the score and
51:27
내림차순 메커니즘을 사용하여 시작합니다.
using descending mechanism and it's gonna go and start
51:30
첫 번째 행은 가장 높은 점수를 가진 고객이 될 것입니다.
like moving around your rows where the first row gonna
51:33
이 예에서 존이 가장 높은 점수인 900을 가지고 있으므로
be the customer with the highest score and in this example
51:36
존이 결과의 첫 번째 행으로 나타날 수 있습니다.
john has the highest score the 900 so john can appear as a first row at the results and that's because
51:43
그의 점수 이후 두 번째로 높은 점수는 조지가 될 것입니다.
his score and after that the second highest is going to be George
51:46
750점으로 계속 정렬할 것입니다.
with 750 and it's going to go and keep sorting
51:49
데이터를 정렬하고, 그 다음 500, 350이 있습니다.
the data and then we have 500 then 350
51:53
마지막 행은 가장 낮은 점수를 가진 고객이 될 것입니다.
and the last row going to be the customer with the lowest score
51:56
제로가 될 것이며, 이것이 SQL이 주문을 실행하는 방법입니다.
the zero so this is how SQL executes your order
51:59
이제 SQL로 돌아가서 연습해 봅시다.
by now let's go back to SQL in order to practice all right so
52:02
이제 다음 작업이 있습니다. 모든 고객을 검색하고 결과를 가장 높은 점수 순으로 정렬하라고 합니다.
now we have the following task and it says retrieve all customers and sort the result by the highest score first so now by looking to the task we need all the
52:11
고객이므로 조건이 없습니다.
customers so there is like no conditions or anything to
52:14
필터링할 필요는 없지만 결과를 정렬해야 합니다.
filter but we have to sort the results so let's go and
52:17
그럼 시작해 보겠습니다. 모든 열을 선택합니다.
do that we're gonna start as usual by selecting all
52:20
고객 테이블의 열을 선택합니다. 이제 실행하면
the columns from the table customers so now if you go and
52:23
모든 고객을 얻을 수 있으며 데이터베이스에 저장된 그대로 볼 수 있습니다.
execute it you will get all your customers and you are now seeing
52:26
결과가 점수에 따라 정렬되지 않았습니다. 낮은 점수, 높은 점수, 낮은 점수 순입니다.
the data exactly like stored in the database and you can
52:29
작업에서 결과를 정렬해야 하므로 order by를 사용해야 합니다.
see the result is not sorted by the scores so we have here a low score then high score then low and so on now the task says we have to sort the
52:38
어떤 열에서 정렬할지 이해해야 합니다.
results so we have to go and use the order by
52:41
작업에서 가져올 수 있습니다. 점수로 정렬해야 한다고 합니다.
and now you have to understand from which column and we can get that
52:44
그럼 점수를 정의하겠습니다. 마지막으로
from the task so it says it should be sorted by the
52:47
정의해야 할 것은 내림차순 또는 오름차순입니다.
score so we're going to go and define the score here and the final
52:50
작업에서 가져올 수 있습니다. 가장 높은 점수로 데이터를 정렬해야 하므로
thing that you have to define is the mechanism descending or ascending
52:54
가장 높은 점수부터 낮은 점수까지 정렬해야 합니다. 그럼 실행해 보겠습니다.
and you can get it as well from the task so we have to sort the data by the highest score first so the highest first and then the lowest so that means we're going to go and use that
53:03
이제 결과에서 첫 번째 고객이 가장 높은 점수를 가지고 있습니다.
assembling so that's all let's go and execute it
53:06
그 다음으로 두 번째 고객이 두 번째로 높은 점수를 가지고 있습니다.
now as you can see in the results the first customer has the highest
53:09
마지막 고객은 가장 낮은 점수를 가지고 있습니다. 이렇게
score then we have the second one with the second highest
53:12
데이터를 정렬하는 방법입니다. 이제 작업을 수행해 보겠습니다.
until the last one with the lowest score that's it this
53:15
정확히 반대로 하겠습니다. 결과를 정렬하고 싶습니다.
is how you sort your data and with that we have so the task now let's
53:18
가장 낮은 점수 순으로 정렬하고 싶습니다.
do exactly the opposite so we want to sort the results
53:21
가장 낮은 점수를 가진 고객을 먼저 보고 싶습니다.
by the lowest score first so that means we want to
53:24
예를 들어, ID 번호 5가 첫 번째로 보여야 합니다.
see first the customers with the lowest score like here in this
53:27
그가 가장 낮은 점수인 0을 가지고 있기 때문입니다. 이를 위해
example we should see the id number five as the first
53:31
기구를 전환해야 합니다. 내림차순 대신
because he has the lowest score the zero now in order to do that all
53:34
오름차순을 사용할 수 있습니다. 실행해 보겠습니다.
what you have to do is to switch the mechanism instead of descending
53:37
내려가는 대신 메커니즘을 전환해야 합니다.
when you can use ascending let's go and excuse it and
53:40
이제 가장 낮은 점수를 보유하고 있습니다.
that's it as you can see now we have the lowest score then the
53:43
두 번째로 낮은 점수는 마지막 행까지 이어지며, 가장 높은 점수를 가진 고객이 있습니다.
second lowest score until the last row it's gonna be the customer with the highest score so the lowest score comes first so it is very simple this is how you sort your data using sql
53:57
이제 정렬하는 방법을 보여드리겠습니다.
and now i'm going to show you one more thing that you can do with the order by you can
54:00
여러 열을 사용하여 데이터를 정렬할 수 있습니다.
sort your data using multiple columns and we call
54:03
국가를 기준으로 데이터를 정렬하고자 합니다.
it nested sorting so now let's take this very simple example where
54:07
국가 열을 기준으로 정렬하겠습니다.
you want to sort your data using country so we
54:10
오름차순으로 정렬할 것입니다.
are saying order by the column country and the mechanism
54:13
독일의 두 고객이 알파벳 순으로 정렬됩니다.
going to be ascending so from the lowest to the highest now if you do that is going to go and sort the data this time based on the country so we're going to have like the first
54:21
영국과 마지막 두 고객은 미국에서 올 것입니다.
two customers from germany is sorting it alphabetically then
54:25
최종 결과를 확인하면 뭔가 잘못된 것 같다고 말할 수 있습니다.
we have the uk and the last two gonna be from usa now
54:28
데이터가 완전히 정렬되지 않았습니다.
if you are checking the final results you might say you know what there
54:31
정확하게 정렬되지 않았습니다.
is like something wrong the data is not completely sorted
54:34
독일에서 온 첫 두 고객의 점수를 확인할 수 있습니다.
correctly so if you are looking to the first two customers that
54:37
점수가 오름차순으로 정렬되어 있습니다.
come from country germany you can see the scores are sorted
54:41
이제 미국 고객을 보면 반대로 정렬되어 있습니다.
in ascending way from the lowest to the highest so first we have 350 then 500 then uk it's fine because we have only
54:48
내림차순으로 정렬되어 있습니다.
Now if you look to the customers from USA, you see that it is like sorted the way around.
54:53
데이터가 정렬되는 방법이 깔끔하지 않습니다.
It is sorted descending from the highest to the lowest. So first we have the score 900 then 0.
54:59
결과가 깔끔하지 않으며, 이 문제는 보통 발생합니다.
So there is like no clean way on how the data is sorted
55:02
열을 기준으로 데이터를 정렬할 때 발생합니다.
and the result is not really clean and this issue happens usually
55:06
여기서 국가가 두 번 나타납니다.
if you are sorting your data based in a column that has
55:09
정렬을 개선하기 위해
repetition like here the country we have twice germany and twice
55:12
정확하게 만들기 위해 다른 열을 포함할 수 있습니다.
usa so now in order to refine the sorting and
55:15
예를 들어 점수를 포함할 수 있습니다.
make it more correct we can include in the sorting another
55:19
정렬할 열 목록을 만들 수 있습니다.
column in this scenario for example the score so we can make a
55:22
열 목록을 정렬하여 분리할 수 있습니다.
list of columns in the order by and we can separate them
55:25
쉼표를 사용하고 각기 다른 메커니즘을 가질 수 있습니다.
using the comma and of course you can have different mechanism for each
55:28
국가에 대해 오름차순으로 정렬하고 있지만
column like for the country we are saying it is ascending but for
55:32
점수에 대해서는 내림차순으로 정렬하겠습니다.
the score we say you know what let's make a descending it will not
55:35
모든 열에 대해 하나만 있을 수는 없습니다.
be only one for all columns so now what can happen is
55:38
각 섹션에 대한 데이터를 정렬하기 시작할 것입니다.
going to start sorting the data for each section so for
55:41
독일의 두 고객에 대해 가장 높은 점수부터 정렬할 것입니다.
the two customers from germany the sorting gonna be from the highest
55:44
가장 낮은 점수까지 정렬할 것이며, 두 고객을 교환할 것입니다.
to the lowest so it's gonna go and switch the two customers so
55:48
마르틴이 먼저 올 것입니다. 그는 마리아보다 점수가 높습니다.
martin gonna be first because he has higher score than maria
55:51
이로 인해 동일한 값에 따라 점수를 조정하고 있습니다.
and with that we are refining the scores based on the same value
55:54
영국의 경우 아무 일도 일어나지 않을 것입니다.
of course the country now for the uk nothing gonna happen because
55:57
우리는 하나의 값만 가지고 있으며, 미국도 마찬가지입니다.
we have only one value and for the usa as well nothing gonna
56:01
이미 올바르게 정렬되어 있기 때문입니다.
happen because it is already sorted in the correct
56:04
가장 높은 점수에서 가장 낮은 점수까지 정렬되어 있습니다.
way from the highest to the lowest so as you can see if you are including
56:07
두 번째 열을 포함하면 정렬을 조정할 수 있습니다.
a second column you are refining your sorting
56:10
친구들, 순서가 매우 중요합니다.
and as well my friends the order is very important so
56:13
SQL에서 중첩 정렬을 수행하는 방법입니다.
this is how you can do nested sorting in sql
56:16
이제 SQL로 돌아가서 연습을 시작합시다.
let's go back to our sql and start practicing all right so
56:20
이제 다음 작업이 있으며, 모든 고객을 검색하라고 합니다.
now we have the following task and it says retrieve all customers and
56:23
결과를 국가별로 정렬하고
sort the results by the country and then
56:26
가장 높은 점수로 정렬합니다.
by the highest score so again we need all customers so
56:30
고객 테이블에서 모든 것을 선택합니다.
select everything from customers table and
56:33
결과를 국가별로 정렬해야 합니다.
now the task says we have to sort the result by the country so we're going to start with the order by and since it says by the country we're going to go with the
56:40
국가를 알파벳순으로 정렬합니다.
country and we're going to sort it alphabetically so it can be ascending
56:44
이제 실행해 보겠습니다. 데이터를 정렬할 수 있습니다.
so let's go execute it now you can see the data is sorted
56:47
완전히 다르게 그 나라에 따라 먼저 독일이 있습니다.
completely differently by that country so we have first germany
56:50
영국과 그 다음 미국이지만 그게 전부가 아닙니다.
uk and then usa but that's not all and
56:53
최고 점수에 따라 정렬해야 하므로
says then by the highest score so we
56:56
정렬에 또 다른 열을 포함해야 합니다.
have to go and include another column in the sorting and we can
56:59
최고 점수가 먼저 와야 하므로 이제 우리는
go and add that by adding a comma and then mention another column the score and now we have to specify the mechanism it says by the highest
57:07
내림차순을 사용하고 있습니다. 현재 상황은
score so the highest must come first and with that we are
57:10
예를 들어 두 고객의 결과를 보면
using descending now what is the current situation in that if
57:13
350과 500이 있습니다. 즉,
you look to the results for example for those two customers we
57:16
점수가 오름차순으로 정렬됩니다. 같은 것입니다.
have 350 and then 500 so that means the
57:19
미국의 경우도 마찬가지입니다. 즉, 가장 낮은 점수부터 가장 높은 점수까지입니다.
scores are sorted ascending right the same thing
57:22
이렇게 하면 어떤 일이 발생할 수 있는지 보겠습니다.
for usa so from the lowest to the highest now if
57:25
이렇게 하면 독일의 경우 먼저
you go and do it like this what can happen it's gonna go and
57:28
가장 높은 500이 오고 그 다음 350이 옵니다.
switch it so you can see over here now for germany first
57:32
미국의 경우도 바뀌어 가장 높은 점수가
comes the highest the 500 and then the 350 and
57:35
그 다음 가장 낮은 점수가 됩니다. 이제 우리는
for usa as well they switched so we have the highest and
57:38
이 열의 순서가 매우 중요합니다. 점수가
then the lowest and with that we have sold the task now again the order
57:41
국가 뒤에 오기 때문에 가장 높은 점수를 먼저 얻지 못합니다.
of those columns are very important so since the scores comes
57:45
결과로서 900을 얻지 못할 것입니다.
after the country we will not get the highest scores first
57:48
첫 번째 행으로서 점수는 정렬되어야 하므로
as the results so we will not get the 900 as
57:51
국가 뒤에 점수가 있어야 하므로 국가가 더 우선합니다.
a first row and that's because the scores must be sorted
57:55
그것을 뒤집으면 여기로 가서 말해봅시다.
after the country so the country has more priority now
57:58
먼저 점수를 정렬하고 그 다음 국가를 정렬합시다.
if you go and flip that so let's go over here and say
58:01
실행해야 합니다. 학교는 먼저 점수를 정렬해야 합니다.
sort first the score and then the country so let's
58:04
그래야 900을 먼저 얻을 수 있습니다.
go and execute it school has first to sort the scores
58:07
그 다음 국가가 오고 중복이 없기 때문에.
so that you will get the 900 first right
58:10
그리고 그 다음에 국가들이 있으며 중복이 없습니다.
and then the countries and since there is like no duplicates
58:13
점수에서 이것은 전혀 말이 되지 않으므로 넘어갈 수 있습니다.
in the scores this makes no sense at all so you can go and
58:17
중첩 정렬은 반복이 있을 때만 의미가 있습니다.
skip it so nested sorting only makes sense if you have repetition
58:20
결과에서 사용할 수 있습니다.
in your results and you can use the
58:23
두 번째 열의 도움으로 정렬을 완벽하게 만들 수 있습니다.
help of a second column in order to make the sorting perfect so that's it and with that of course we have solved the task all right so with With that, you have learned how to sort your data using order by.
58:34
이제 다음 단계에서는 데이터를 집계하고 그룹화하는 방법에 대해 이야기할 것입니다.
Now, in the next step, we're going to talk about how to aggregate and group up your data using group by.
58:40
우리는 그것을 where와 order by 사이에 넣을 것입니다.
And we're going to put it between the where and the order by.
58:42
쿼리의 순서에서 group by는 where와 order by 사이에 옵니다.
Because in the order of the query, the group by comes between the where and the order by. So let's go.
58:53
그렇다면 group by는 정확히 무엇인가요? 같은 값을 가진 행을 결합합니다.
Okay, so what is exactly group by? It's going to go and combine the rows with the same value.
58:57
그렇다면 행을 결합하고 압축하여 집계합니다.
So it's going to go and combine and smash press your rows to make it aggregated and more combined.
59:03
group by가 하는 모든 것은 한 열을 다른 열로 집계하는 것입니다.
So all what group by does, it aggregates a column by another column.
59:08
예를 들어, 국가별 총 점수를 찾고 싶다면.
Like for example, if you want to find the total score by country.
59:12
한 국가의 모든 점수 값을 집계합니다. 이러한 작업이 있다면 group by를 사용할 수 있습니다.
So you aggregate all the scores value for one country. If you have this kind of tasks, then you can use the group by.
59:18
그 구문을 살펴보겠습니다. 평소처럼 select로 시작하겠습니다.
Let's see the syntax of that. We will start as usual with the select. And now what we want to see in the result is two columns.
59:25
결과에서 보고 싶은 것은 두 개의 열입니다.
So we have to specify like a category, like the country. This is the value that you want to group the data by.
59:31
카테고리처럼 국가를 지정해야 합니다.
And another one where you are doing the aggregations. So for example, you are saying I would like to see the total score.
59:36
그리고 집계를 수행하는 또 다른 열이 필요합니다.
So we use the function sum in order to summarize the values of the score.
59:40
예를 들어, 총 점수를 보고 싶다고 말할 수 있습니다.
After that, as usual, we use the from in order to select the data from specific table. And now comes the magic.
59:46
값을 요약하기 위해 sum 함수를 사용합니다.
We use after the from group by. Now it understands, okay, I have now to combine the data.
59:51
그 후, 평소처럼 from을 사용하여 특정 테이블에서 데이터를 선택합니다.
I have to group up the data by something. And this time we are saying you have to group up the data by the country.
59:56
이제 마법이 시작됩니다.
So that means each value of the country must be presented
1:00:00
group by를 사용합니다. 이제 데이터 결합을 이해합니다.
in the output only once and for each
1:00:03
데이터를 어떤 것으로 그룹화해야 합니다.
country we want to see the aggregation and that is
1:00:06
이번에는 국가별로 그룹화해야 한다고 말합니다.
the total score so let's see how is going to execute it so it's
1:00:09
각 국가의 값은 출력에 한 번만 표시되어야 합니다.
gonna first start with the from it's gonna go and get the data from the database and
1:00:12
그럼 이제 데이터베이스에서 데이터를 가져올 거예요.
then it's gonna execute the group by and now scale understand okay i
1:00:15
이제 국가별로 데이터를 그룹화해야 해요.
have to group up now the data by the country and it understands
1:00:19
그것을 위해 점수를 집계해야 해요. 예를 들어, 독일에 대한 두 개의 행이 있어요.
it has to aggregate the scores for that so it's gonna go and identify the rows that are sharing the same value Like for example, here we have two rows for Germany and it's going to bring it to the results.
1:00:30
이제 같은 국가에 대해 두 개의 행이 있어요. SQL은 이들을 하나의 행으로 결합하려고 할 거예요.
So now we have two rows for the same country. But since we are saying group by country, SQL is going to try and combine them, smash them together in only one row.
1:00:39
각 국가의 값은 최대 한 번만 존재해야 해요. 이렇게 두면 안 돼요.
So each value of the country must exist at maximum once. We cannot leave it like this. So now what we're going to do with the scores? We have two scores.
1:00:47
이제 SQL이 집계 함수를 확인할 거예요. 이건 요약이에요.
Now SQL is going to check the aggregate function. It is the summarization. So and it's going to go and add those values. 350 plus 500.
1:00:54
그럼 이제 총 점수 850을 얻을 수 있어요.
and with that we're gonna get the total score of 850
1:00:57
그렇게 되면 두 개의 행이 하나로 결합될 거예요.
and with that as you can see scale is combining those two
1:01:00
그래서 독일은 하나만 존재할 거예요.
rows into one so in the outward germany will exist
1:01:03
점수에 대해서도 총 점수를 얻을 수 있어요.
only one and about the scores we will get the total
1:01:06
미국에 대해서도 같은 일이 발생할 수 있어요.
score and the same thing can happen for the next value in the country
1:01:10
미국이 두 번 있으니 두 개의 행을 얻을 거예요.
we have the usa we have it twice so we're gonna get two
1:01:13
미국은 한 번만 존재해야 하므로 두 개의 행을 하나로 결합할 거예요.
rows and scale gonna combine those two rows in
1:01:16
그렇게 해서 900을 얻을 수 있어요.
one because usa must exist only once and with the scores we will have the total scores so 900 plus zero we
1:01:23
그렇게 해서 두 개의 행을 하나로 변환했어요.
get 900 and with that skill converted those two
1:01:26
영국은 그대로 유지될 거예요.
rows into one and for the last value in the countries
1:01:29
결합할 필요가 없어요. 이미 하나의 값이니까요.
we have the uk it's gonna stay as it is there is no need
1:01:32
출력을 보면 원래 데이터를 국가별로 그룹화했음을 알 수 있어요.
to smash and combine anything because it's already one value
1:01:35
그것은 각 값에 대해 하나의 행을 얻는다는 의미예요.
so my friends if you are looking to the output you can see we
1:01:38
국가 열에 대해 하나의 행을 얻을 거예요.
grouped the original data by the country and
1:01:42
원래 데이터는 이렇게 다섯 개의 행이 있어요.
that means we're gonna get one row for each value inside
1:01:45
이렇게 그룹화하면 출력에서 다섯 개의 행을 얻을 수 있어요.
the country column so my friends the original data you have
1:01:48
하지만 세 개의 행만 얻을 거예요.
five rows in the output if you are using group by like this
1:01:51
이게 바로 그룹화가 작동하는 방식이에요.
you will get only three rows so this is exactly how
1:01:54
그룹화가 작동하는 방식을 연습해 볼 거예요.
the group by works let's go back to scale and practice
1:01:58
좋아요, 다음 작업이 있습니다. 그리고 그것은 찾으라고 합니다.
okay so we have the following task and it says find the
1:02:01
각 국가의 총 점수를. 그래서 이것을 읽으면서
total score for each country so from reading this you
1:02:04
우리가 집계를 해야 하고 데이터를 결합해야 한다는 것을 이해할 수 있습니다.
can understand we have to do aggregations and we have to combine
1:02:07
열로 데이터를 결합해야 하므로, 보통 이렇게 시작합니다.
the data by a column so now usually i start like this i
1:02:10
해결하기 위해 필요한 열을 선택하기 시작합니다.
start selecting the columns that i need in order to solve
1:02:13
이 작업을 위해 우리는 국가와
this task so what do we need we need the country and
1:02:16
고객 테이블의 점수가 필요합니다.
score from our table customers so
1:02:19
이제 이렇게 시작합시다. 이제 우리는 국가와 점수를 볼 수 있습니다.
let's start like this now you can see we have the countries and the scores
1:02:23
작업은 데이터를 국가별로 그룹화해야 한다고 말합니다.
and the task says we have to group up the data by the country
1:02:26
즉, 이것이 우리가 그룹화를 수행할 열입니다.
so that means this is the column where we're going to do the group by
1:02:29
총 점수는 집계될 것이므로, 당신이 해야 할 일은
and the total scores will be aggregated so what you have to
1:02:32
각 국가에 대해 그룹화를 사용할 수 있습니다.
do we can use the group by since it says for each country
1:02:35
여기에서 그룹화를 사용할 수 있으며, 이제 우리는
we can use it over here group by country and now we have
1:02:38
점수를 집계하러 가야 합니다. 이렇게 두면 안 됩니다.
to go and aggregate the scores you cannot leave it like this
1:02:42
점수의 합계를 말할 것이므로, 이제
so we're gonna say the sum of the score so let's
1:02:45
실행하러 가고, 그렇게 하면 보시다시피 우리는
go and execute it and with that as you can see we are getting
1:02:48
각 국가의 총 점수를 얻고 있습니다.
the total scores for each country so
1:02:51
이제 고객이 다섯 명 대신 세 명만 있습니다.
now instead of having five customers we have only three
1:02:54
행이 이제 세 개입니다. 이는 국가가 세 개의 행을 가지고 있기 때문입니다.
rows now and that's because the countries has three rows
1:02:58
이제 결과를 확인하면 뭔가 이상한 것을 볼 수 있습니다. '없음'이라고 나옵니다.
and now if you check the result you can see something weird it says no
1:03:01
열 이름이 없고, 이는 우리가 점수를 변경했기 때문입니다.
column name and that's because we have changed the scores
1:03:04
더 이상 원래 점수가 아닙니다. 우리는 그 값을 요약했습니다.
it's not anymore the original score it is it is the total scores we have summarized those values so sql don't know
1:03:12
SQL이 그것을 어떻게 호출할지 모르기 때문에, 그 값은
how we're gonna call it so those values doesn't come
1:03:15
데이터베이스에서 직접 오지 않습니다. 이것은 당신이
directly from the database it's this manipulation that you
1:03:18
여기에서 수행한 조작입니다.
have done here now in order to give a nice name for that we
1:03:21
별칭을 추가할 수 있습니다.
can go and add aliases and alias it is only like
1:03:24
쿼리 내에 존재하는 이름입니다.
a name that lives inside your query so we can do it
1:03:27
예를 들어 총 점수와 같은 이름을 지정할 수 있습니다.
like this us and you can specify any name you want like
1:03:31
이것이 이 열의 이름입니다.
for example total score and now scale can understand okay this
1:03:34
실행하면 결과에 새 이름이 표시됩니다.
is the name for this column and if you go and execute it
1:03:37
이 이름은 이 쿼리 내에서만 존재합니다.
you will see the new name in the results but you have to understand this
1:03:41
데이터베이스 내에서 사용할 수 없습니다.
name exists only in this query you are not renaming anything
1:03:44
쿼리 내에서만 알려진 것입니다.
inside your database and you cannot use it in any other
1:03:47
결과에만 해당하며 이름을 바꿀 수 있습니다.
queries it is just something that is known inside this
1:03:51
예를 들어 여기서 이라고 말할 수 있습니다.
query and only for your results and of course you can rename
1:03:54
고객 국가입니다.
anything any column like for example here you can say this
1:03:57
출력에서 열의 이름을 바꾸는 것입니다.
is the customer country and if you excuse
1:04:00
SQL에서 정말 멋집니다.
it you are just renaming the column in the output so this
1:04:03
그룹화에 대한 한 가지 더 있습니다.
is really nice in sql okay so now there is like one one
1:04:06
선택에서 추가하는 열은 언급되어야 합니다.
more thing about the group by the non-aggregated columns that
1:04:10
그룹화에 있어야 합니다.
you are adding in the select must be as well mentioned in
1:04:13
이제 국가와 총 점수를 보고 싶습니다.
the group by so now for example let's say that's okay i'm seeing
1:04:16
이름을 가져오고 싶습니다.
now the countries the total scores i would like to see as well
1:04:19
국가, 이름, 총 점수를 가져옵니다.
the first name so you go over here and say you know what let's
1:04:23
오류가 발생할 것입니다.
get the first name so country first name the total scores and
1:04:26
데이터를 그룹화할 열만 필요합니다.
excuse you will get an error because it's gonna tell you i
1:04:29
첫 번째 이름은 집계되지 않았습니다.
need only the columns that you want to group the data pie
1:04:32
그룹에 사용되지 않았습니다.
or should be aggregated so now the first name it
1:04:35
SQL을 혼란스럽게 합니다.
is not aggregated and as well not used for the group
1:04:39
작동하지 않을 것입니다.
pie so it is just here to confuse sql and
1:04:42
작동하지 않을 것이므로 열을 가져오면
it will not work so if you bring a column either it
1:04:45
집계에 있어야 하거나 그룹의 일부여야 합니다.
should be in the aggregation or it should be part of the group
1:04:48
이 문제를 해결하기 위해 첫 번째
pie so in order to fix this and you really want to see the first
1:04:51
이름을 추가하고 실행해 보세요. 이번에는 작동할 것입니다.
name you can go over here and say you know what let's add it to the group pie and execute this time it's gonna work because all the columns that are mentioned
1:05:00
여기 또한 그룹의 일부입니다.
And here is as well part of the group by so now
1:05:03
보시다시피 국가, 이름 및 총 점수가 있습니다.
as you can see we have the countries the first name and the total scores and
1:05:06
다시 보시면 다섯 개의 행이 있습니다.
you can see again we have five rows we don't have three rows
1:05:09
이제 데이터가 국가별로 결합되고 있습니다.
and that's because now you are combining the data by the country
1:05:13
이제 출력에서 다섯 개의 행을 얻고 있습니다.
and as well the first name and now you can see in the output we are
1:05:16
더 이상 세 개의 행을 얻고 있지 않습니다.
getting five rows we are not getting anymore the three
1:05:19
세 개의 국가가 있으며, 이는 SQL이 이제
rows there are three countries and that's because sql now
1:05:22
두 개의 열로 데이터를 그룹화하고 있기 때문입니다.
grouping the data by two columns the combination of
1:05:25
국가와 이름의 조합이 다섯 개를 제공합니다.
the country and the first name and those two columns gives five
1:05:28
조합이 다섯 개가 되므로
combinations and that means you will get five rows so that
1:05:32
그룹에서 정의하는 것에 매우 주의해야 합니다.
means you have to be really careful what you are defining in the group
1:05:35
고유 값의 수가 출력 결과를 정의합니다.
by and the number of the unique values that those
1:05:38
결과를 정의합니다. 첫 번째 이름을 제거하면
columns are generating gonna define the output
1:05:41
여기서도 하나의 열로만 그룹화하고 있습니다.
the results so if you go and remove the first name and
1:05:44
이 열은 세 개의 값만 가지고 있습니다.
from here as well you are grouping by only one column and
1:05:47
따라서 세 개의 행을 얻고 있습니다.
this column has only three values and that's why you are getting three
1:05:51
작업을 해결했으므로 이제 확장해 보겠습니다.
rows and with that of course we have solved the task and now let's extend
1:05:54
작업을 수행하고 각 국가의 총 점수와
the task and say find the total score and total
1:05:57
고객 수를 찾으라고 하겠습니다.
number of customers for each country so that means
1:06:00
따라서 두 개의 집계가 필요합니다.
we need two aggregations we have the total score and
1:06:03
고객 수의 총합이 필요합니다.
as well we need the total number of customers so from
1:06:07
이것을 읽으면 우리는 여전히 데이터를 국가별로 그룹화하고 싶다는 것을 이해할 수 있지만, 이번에는 두 가지 유형의 집계가 필요합니다. 우리는 총
reading this you can understand we still want to group up the data by the country but this time we need two type of aggregations we need the total
1:06:14
고객 수와 총 점수가 필요합니다. 그래서 우리는 거의 모든 것을 가지고 있지만, 지금 필요한 것은 두 번째 집계입니다.
number of customers and the total scores so we have almost
1:06:17
지금 필요한 것은 두 번째 집계입니다. 이제 여기로 가서 또 다른 집계 함수를 추가할 수 있습니다.
everything but what is missing is the second aggregation now
1:06:21
여기로 가서 또 다른 집계 함수를 추가할 수 있습니다. 그 함수는 카운트입니다. 우리가 세고 싶은 것은 고객 수입니다.
what you can do you can go over here and add another aggregate function called
1:06:25
세고 싶은 것은 고객 수입니다. 그래서 우리는 여기에서 ID를 추가하고 그것을
the count and what we want to count is the number of customers
1:06:28
여기에서 ID를 추가하고 그것을 총 고객 수라고 부를 수 있습니다. 그래서 이제 물론 SQL은
so we can go and add the id over here and call it
1:06:31
총 고객 수, 이제 물론 SQL이 할 것입니다.
total customers so now of course sql gonna
1:06:34
이제 실행하면 국가별 총 고객 수를 얻을 수 있으며, SQL은 문제가 없습니다.
so now if you go and execute it you will get as well the total customers by the country and now as you can see sql has no problem
1:06:41
ID와 함께, 이는 ID를 집계하고 있기 때문입니다.
with the id and that's because you are aggregating the id so
1:06:44
SQL은 그것을 어떻게 처리하고 결합할지 알고 있습니다.
sql know what to do with it and how to combine it so
1:06:47
즉, 국가에서 ID를 언급할 필요가 없습니다. 왜냐하면
that means you don't have to mention the id in the country because
1:06:50
당신이 그것을 집계하고 있기 때문입니다. 그래서 우리는 그것으로 모든 것을 해결했습니다.
you are aggregating it so that's all with that we have solved
1:06:54
또한 작업을 완료했습니다. 알겠습니다. 그래서 이를 통해 데이터를 그룹화하는 방법을 배웠습니다. 다음에는 having 절을 사용하여 데이터를 필터링하는 또 다른 기술에 대해 이야기할 것입니다. 자, 시작해 봅시다.
as well the task all right so with that you have learned how to group up your data using the group i next we're going to talk about another technique on how to filter your data but this time using the having clause so let's go
1:07:10
좋습니다. 그럼 halving이 정확히 무엇인가요? 집계 후에 데이터를 필터링하는 데 사용할 수 있습니다.
All right, so what is exactly halving? You can use it in order to filter your data, but after the aggregation.
1:07:16
즉, 그룹화 후에만 halving을 사용할 수 있습니다. 그 구문을 살펴보겠습니다.
So that means we can use the halving only after using the group by. So let's see the syntax of that.
1:07:22
다시 말해, 이전 예제처럼 우리는 국가별 총 점수를 찾고 있습니다. 그래서 우리는 선택하고 그룹화합니다.
So again, like the previous example, we are finding the total score by country. So we have our select from group by.
1:07:29
이제 당신은 말합니다. 결과를 필터링하고 싶습니다.
And now you say, you know what? I would like to filter the end results.
1:07:33
이를 위해 우리는 그룹화 후에 having을 사용합니다. 그리고 이제 where 절처럼 조건을 지정해야 합니다.
And in order to do that, we use the having after the group by. And now like the where clause, you have to specify a condition.
1:07:40
그래서 우리는 결과를 보고 싶어하는 다음 조건이 있습니다.
So we have the following condition where we want to see the results.
1:07:43
총 점수가 800보다 높은 국가만. 이것이 우리의 조건이 될 것입니다.
Only the countries if their total score is higher than 800. So this is going to be our condition.
1:07:50
이제 당신은 무언가를 알아차릴 수 있습니다. 그룹화에서는 데이터를 그 값으로 그룹화하는 국가 열을 사용하고 있습니다.
So now you might noticing something. With the group by, we are using the country, the column where we are grouping the data by its value.
1:07:56
하지만 having에서는 집계된 열, 점수의 합계를 사용하고 있습니다.
But with the having, we are using the aggregated column, the sum of the score.
1:08:01
이것이 구문이 작동하는 방식입니다. 이제 SQL이 이를 실행하는 방법을 살펴보겠습니다. 항상처럼 SQL은 from으로 시작합니다. 우리는 데이터를 가져오고 있습니다.
So this is how the syntax works. And now let's see how SQL can execute it. So as usual, SQL start with the from. We are getting our data.
1:08:08
그리고 두 번째 단계에서 SQL은 국가별로 데이터를 집계할 것입니다.
And then the second step, SQL gonna go and aggregate the data by the country.
1:08:13
이전과 같이, SQL은 같은 국가 값을 가진 행을 그룹화할 것입니다. 그래서 각 국가에 대해 하나의 행을 가질 수 있습니다.
So it's like before, SQL gonna group the rows with the same value of the country. So we can have one row for each country.
1:08:20
그렇다면 이전과 같이 SQL은 같은 국가 값을 가진 행을 그룹화합니다. 그래서 각 국가에 대해 하나의 행을 가질 수 있습니다.
And this is what's gonna happen if you use group by. And with that, we have now aggregated values, right?
1:08:25
그것이 그룹화 사용 시 발생할 일입니다. 이제 집계된 값이 생겼습니다, 맞죠?
And after the group by, SQL gonna go and execute the having. So having, it is like a filter. Now we have a nice condition.
1:08:32
총 판매량은 800 이상이어야 합니다. SQL은 집계 후 새로운 결과를 확인할 것입니다.
The total sale must be higher than 800. And SQL gonna go and check the new results after the aggregation.
1:08:38
독일의 총 판매량은 850입니다. 조건을 충족하므로 결과에 남게 됩니다. 미국도 마찬가지입니다.
So in Germany, we have the total sales of 850. So it meets the condition and it gonna stay in the results. The same thing for USA.
1:08:45
900보다도 높습니다. 하지만 영국은 750으로 조건을 충족하지 않습니다. 800보다 높지 않습니다.
It is higher as well than 900. But for UK, it is not meeting the condition 750. It is not higher than 800.
1:08:53
SQL은 이 행을 필터링할 것입니다. 그러므로 반올림을 적용한 후 두 개의 국가만 남게 됩니다.
And SQL gonna go and filter out this row. So that means after applying the halving, we will get only two countries.
1:08:59
조건을 충족하는 값이 있기 때문입니다.
because they have values that is fulfilling the condition and that's
1:09:03
이것이 having을 사용할 때 발생할 수 있는 일입니다. 단순히
it this is what can happen if you are using having it is simply
1:09:06
데이터를 필터링하는 것입니다. 하지만 이제 혼란스러울 수 있습니다. 당신은 말하죠,
filtering the data but now you might be confused you say you
1:09:09
우리는 데이터를 필터링하기 위해 where 절을 사용했으니 왜
know what we have used the where clause to filter the data so why
1:09:12
SQL에는 데이터를 필터링할 다른 절이 있는지 알겠죠?
we have in sql another clause to filter my data can't
1:09:15
우리는 단순히 where를 사용합니다. SQL에는 다양한 방법이 있습니다.
we just use the where well in sql there are like different
1:09:19
시나리오에 따라 데이터를 필터링하는 방법
ways on how to filter your data based on the scenario so
1:09:22
이제 쿼리에 두 개의 필터를 추가해 보겠습니다. 우리는 이미 그룹 피 후에 having을 사용하고 있으며, 이제 where를 추가해 보겠습니다. 일반적으로 where는 from과 group by 사이에 위치합니다.
now let's go and add both of the filters in my query we are already using the having after the group pi and now let's go and add the where Usually the where comes between the from and the group by.
1:09:32
그래서 from 바로 뒤에 위치합니다. 여기서 우리는 점수가 400보다 높아야 한다고 말하고 있습니다. 이제 우리는 점수를 기준으로 두 번 필터링하고 있는 거죠?
So directly after the from. And here we are saying the score must be higher than 400. So now we are filtering based on the scores twice, right?
1:09:40
한 번은 점수가 400보다 높다고 말하고, having을 통해 점수의 합이 800보다 높아야 한다고 말하고 있습니다.
Once we are saying the score higher than 400. And by having, we are saying the sum of score must be higher than 800.
1:09:46
그렇다면 큰 차이는 무엇인가요? 필터가 발생하는 시점입니다.
So what is the big difference? It is when the filter is happening.
1:09:50
집계 전에 데이터를 필터링하고 싶다면 원본 데이터를 필터링하고 싶다면 where 절을 사용할 수 있습니다.
If you want to filter the data before the aggregation, you want to filter the original data, then you can go and use the where clause.
1:09:58
하지만 집계 후에 데이터를 필터링하고 싶다면
but if you want to filter the data after the aggregations after
1:10:01
group by 이후에 having을 사용할 수 있습니다.
the group by then you can go and use having so
1:10:04
결국 필터가 발생하는 시점에 관한 것입니다. 그래서
it's really all about when the filter is happening so let's
1:10:07
SQL이 이를 어떻게 실행할 수 있는지 살펴보겠습니다. 먼저 from이
see how sql can execute this so as usual first the from
1:10:10
실행되어 데이터를 가져온 다음, 그 후 두 번째
can be executed to get the data then after that the second
1:10:13
단계인 where가 실행됩니다. 이것이 우리의 첫 번째
step the where gonna be executed this is our first
1:10:17
필터입니다. SQL은 집계를 수행하기 전에 where를 사용하여 데이터를 필터링하고, 우리의 조건에 따라 첫 번째 고객은 점수가 400보다 낮기 때문에 필터링됩니다.
filter so sql gonna filter the data using where before doing any aggregations and And based on our condition, the first customer will be filtered out because score is less than 400.
1:10:28
마지막 고객에 대해서도 같은 일이 발생합니다. 이제 where 절을 적용한 후, 우리는 단지 세 개의 행, 세 명의 고객만 얻을 것입니다.
And the same thing for the last customer. Now, after applying the where clouds, we will get only three rows, only three customers.
1:10:35
이제 다음으로 SQL은 group by를 실행할 것입니다. SQL은 데이터를 국가별로 그룹화할 것입니다. 이제 결합할 데이터가 줄어들었습니다.
And now next, SQL is going to go and execute the group by. So SQL is going to go and group the data by the country. So now we have fewer data to be combined.
1:10:42
값은 각 국가에 대해 단 하나의 행만 있기 때문에 요약되지 않습니다.
So the values will not be summarized because we have only one row for each country.
1:10:46
이제 데이터가 group by로 집계된 후
now after the data is aggregated by the group by then
1:10:49
SQL은 having을 실행할 두 번째 필터를 활성화할 수 있습니다.
sql can activate the second filter having
1:10:52
다음 단계는 having을 실행하는 것이며, 여기서
so the next step is going to execute the having and here is going
1:10:56
새로운 결과를 총 점수에 따라 필터링할 것입니다.
to filter the new results based on the total scores and
1:10:59
하나씩 확인할 것이며, 미국은 조건을 충족합니다.
it's going to check one by one so usa is meeting the condition
1:11:02
영국은 800보다 높지 않기 때문에 필터링됩니다.
uk gonna be filtered out because it is not higher than 800
1:11:05
이번에는 독일도 필터링될 것입니다.
and this time germany as well will be filtered out because
1:11:09
이번에는 이전 조건을 충족하지 않기 때문입니다.
this time it is not fulfilling the condition in the previous
1:11:12
이전 조건을 충족하지 않기 때문에
example without the where we had more scores for Germany
1:11:15
이유는 우리가 독일에 대해 더 많은 점수를 가졌기 때문입니다.
that's why it passed the test but this time since we filtered a
1:11:19
많은 고객을 필터링했기 때문에 독일은 충분한 점수를 얻지 못할 것입니다.
lot of customers using the where Germany will not have enough
1:11:22
두 번째 필터를 통과하는 점수는 없을 것이며, 따라서
scores pass the second filter so with that in the
1:11:25
우리는 단지 하나의 행만 얻을 것이며, 이는 우리가 필터링하고 있기 때문입니다.
output we will get only one row and that's because we are filtering
1:11:28
많은 데이터가 있으므로 매우 간단합니다. group by 이전에 실행될 것이며, 집계 후 having이 실행될 것입니다.
a lot of data so it is very simple we're going to be executed before the group by before the aggregations having going to be executed after the group by after the aggregations so now let's go back to SQL in order to practice.
1:11:40
좋습니다, 이제 매우 흥미로운 작업이 있습니다. 각 국가의 평균 점수를 찾아보세요.
Okay, so now we have very interesting tasks. Find the average score for each country, considering only customers with a score not equal to zero.
1:11:48
조건처럼 들리며, 평균 점수가 430보다 큰 국가만 반환합니다.
So it sounds like condition and return only those countries with an average score greater than 430.
1:11:55
그래서 이것은 또 다른 조건입니다. 단계별로 진행해 보겠습니다.
So this is again another condition. So I know there is a lot of things that's going on. Let's do it step by step.
1:12:01
보통 필요한 열과 데이터를 포함한 매우 간단한 select 문으로 시작합니다.
Usually I start by doing a very simple select statement with the columns and data that I need.
1:12:06
그럼 간단한 select로 시작해 보겠습니다. 여기서 우리는
So let's start with a simple selects so what do we need over here we
1:12:09
점수가 필요하고, 국가가 필요합니다. 다시 점수와 국가가 필요합니다.
need a score we need a country again we need a score country
1:12:13
우리가 필요한 것은 두 개의 열입니다. 이제 고객 ID를 보려고 선택하겠습니다.
so all what we need is two columns now i'm gonna go and select the
1:12:16
고객 ID를 보기 위해 ID를 선택한 후, 테이블에서 국가 점수를 가져오겠습니다.
id just to see the customer id then let's go and get the
1:12:19
고객의 국가 점수를 테이블에서 가져옵니다.
country score from our table customers so
1:12:22
그럼 이제 쿼리를 실행해 보겠습니다.
let's go and query that so now as you can see i start with the basics query
1:12:26
이제 우리가 해야 할 작업은 각 국가의 평균 점수를 찾는 것입니다.
the data and then build up on top of it the second step
1:12:29
즉, 몇 가지 집계를 수행해야 하며 여기에는 두 가지 조건이 있습니다.
now what do we have in the task we have to find the average score for each country that means we have to do some aggregations and here we have two conditions the first condition
1:12:37
첫 번째 조건은 점수가 0이 아닌 고객만 필요하다는 것입니다.
says we need only the customers with a score not equal to zero and the second one we need only the countries with an average score greater than 430.
1:12:46
두 번째 조건은 평균 점수가 430보다 큰 국가만 필요하다는 것입니다.
now you have to decide for each condition whether you're going
1:12:49
이제 각 조건에 대해 사용할 것인지 결정해야 합니다.
to use the where or having now for the first
1:12:52
첫 번째 조건은 점수를 기준으로 필터링하고자 합니다.
one we want to filter based on the scores so that
1:12:55
즉, 집계 전에 필터링하고자 합니다.
means we want to filter before the aggregations it's
1:12:58
평균 점수가 아니라 점수 자체를 말하고 있습니다.
not saying the average score it's saying the score itself so
1:13:01
따라서 이를 위해 where 조건을 사용할 수 있습니다.
that means we can use for this a where condition now
1:13:04
두 번째 조건은 평균 점수가 430보다 큰 국가입니다.
about the second one says countries with an average score
1:13:08
즉, 점수를 집계한 후 데이터를 필터링해야 합니다.
greater than 430 that means we want to filter the
1:13:11
따라서 이 조건에 대해 having을 사용해야 합니다.
data after aggregating the score so that means for this
1:13:14
이제 첫 번째 조건을 구현하고 싶습니다.
condition we have to use the having now what i would like to do
1:13:17
매우 간단합니다. 점수에서 where를 사용하겠습니다.
is to implement the first condition it's very
1:13:20
0이 아닌 점수를 기준으로 하겠습니다.
simple we're gonna say where after the from the score
1:13:23
이제 실행해 보겠습니다.
is not equal to zero so let's go and
1:13:26
이제 평균 점수부터 시작하겠습니다.
execute it and with that we don't have any customers where the scores is not equal to zero so that we have solved this part But now for the second condition, first we have to do the aggregations.
1:13:37
평균 점수를 보려면 국가별로 집계해야 합니다.
So we're going to start with the average score. We're going to go over here and say average. And we're going to call it average score.
1:13:44
이를 위해 group by를 사용합니다.
Now we don't want to see only the average score. We want to see the average score for each country. So that means we have to aggregate by the country.
1:13:52
group by는 항상 where 절 다음에 옵니다.
And for that, we use the group by. Group by comes always after the we're clause. So group by. And which column?
1:13:58
국가가 될 것입니다. 이제 문제가 있습니다.
It's going to be the country. So country. Now there is like an issue here. You cannot execute it like this.
1:14:04
id를 제거해야 하므로 필요하지 않습니다.
we have to go and get rid of the id we don't need it at all so
1:14:07
이제 실행해 보겠습니다.
let's go and execute it so with that we have
1:14:10
각 국가의 평균 점수와 우리는 해결했습니다
the average score for each country and we have solved the
1:14:13
첫 번째 부분이므로 첫 번째와 두 번째 부분을 의미합니다
first part so that means the first and the second parts
1:14:16
완료되었습니다. 이제 마지막 부분에 대해 이야기할 것입니다
they are completed now we're going to talk about the last part the
1:14:20
평균 점수는 430보다 높아야 합니다
average score must be higher than 430 and
1:14:23
그에 따라 having을 사용할 것입니다. having은 group 다음에 옵니다
for that we're going to use the having and having comes after the group
1:14:26
이제 조건을 지정해야 합니다. 집계된 열이어야 하므로 여기서 평균 점수를 가져와서 halving 뒤에 두고 430보다 커야 합니다.
by now we need to specify the condition it must be the aggregated column so we're going to take the average score from here and put it after the halving and it should be greater than 430.
1:14:37
그래서 이제 우리는 마지막 부분이 있습니다
so that's it with us we have the last part as
1:14:40
이제 실행해 보겠습니다
well let's go and execute it now and with us
1:14:43
친구들, 우리는 집계 후 데이터를 필터링했습니다
my friends we have filtered the data after the aggregation
1:14:46
이것이 내가 where와 having을 결정하는 방법입니다
so this is how i decide between the where and having it
1:14:49
매우 간단합니다. 그래서 이를 통해 집계된 데이터를 필터링하는 방법을 배웠습니다
is very simple all right so with that you have learned how to filter the aggregated data using the halving and now next we're gonna go back to the top where we can use
1:14:57
select 바로 뒤에 distinct 키워드가 있습니다
there the keyword distinct exactly after the select so let's go now and learn about the distinct
1:15:07
그렇다면 distinct는 정확히 무엇인가요? SQL에서 사용하면
okay so what is exactly distinct if you use it in sql it's
1:15:11
데이터의 중복을 제거합니다. 중복은
gonna go and remove duplicates in your data duplicates are
1:15:14
데이터의 반복된 값과 같으며, 각 값이 결과에 한 번만 나타나도록 보장할 수 있습니다
like repeated values in your data and it can make sure
1:15:17
그래서 매우 간단하게 들리고 구문도 쉽습니다
that each value appears only once in the results so it sounds very simple and as well the syntax is easy so as usual we
1:15:24
항상 select로 시작하며 그 뒤에
start always with a select by directly after the
1:15:27
select 뒤에 distinct 키워드를 사용합니다
select we use the keyword distinct so there is nothing
1:15:30
그 사이에 아무것도 없고, 일반적인 내용을 지정합니다
between them and then the normal stuff we specify the columns
1:15:33
그런 다음 테이블에서 데이터를 가져오기 위해 from을 사용합니다
and then the from in order to get the data from table let's
1:15:36
고유한 국가 값을 얻고 싶다고 가정해 보겠습니다
say that i would like to get a list of unique values of the country so
1:15:39
가장 먼저 할 일은 데이터를 가져오는 것입니다
the first thing that is going to do of course is to get the data from
1:15:43
데이터베이스에서 from을 사용하고 이제 두 번째 단계는 select입니다
the database using the from and now the second step is the select so is going to execute it and going to select only one
1:15:50
열은 국가이고 다른 모든 열은 결과에서 제외되고 제거됩니다
column the country all other columns going to be excluded and removed from the results and now
1:15:55
세 번째 단계로 가서 distinct를 적용할 것입니다
scale going to go to the third step it's going to go and apply the distincts
1:15:58
국가 값에 따라 필터처럼 작용하여
on the country values so it acts like a filter where
1:16:01
각 값이 한 번만 발생하도록 할 것입니다.
it's going to make sure each value happens only once so it's
1:16:04
첫 번째 값인 독일로 시작할 것입니다. 이제 결과를 살펴보겠습니다.
going to start with the first value germany now we're going to look to the results do
1:16:07
독일이 있습니다. 아직 아무것도 없으므로
we have germany well we don't have anything yet so that's why it's
1:16:11
결과에 포함될 것입니다. 다음 값은 미국입니다. 결과에 미국이 없으므로 포함할 수 있습니다.
going to include it in the results then the next value is going to be usa the same thing we don't have usa in the results so it can go and include
1:16:18
영국에도 동일하게 적용됩니다. 최종 결과에 영국이 없습니다.
it and this happens as well for the uk we don't have
1:16:21
결과에 포함될 것입니다. 이제 독일이 다시 나옵니다. 잠시 기다리세요.
uk in the final results that's why it's gonna go as well include it
1:16:24
이미 있으므로 다시 추가하지 않을 것입니다.
now comes germany again now is gonna say wait we
1:16:27
한 번만 나타나야 하므로
have it already so it will not go and add it again in the output
1:16:30
한 번만 나타나야 하므로 우리는 그렇지 않을 것입니다.
because it must appear only once so we will not
1:16:33
독일이 두 번 나타나지 않도록 하고 마지막 값인 미국은 이미 결과에 있으므로 다시 나타나지 않을 것입니다. 그래서 우리는 데이터 내에서 중복이나 반복을 제거했습니다.
have germany twice and as well for the last value the usa we have it already in the results that's why it will not appear again and with that we have removed the duplicates or the repetition inside our data
1:16:45
그래서 각 값이 고유해졌습니다. 이제 SQL로 돌아가겠습니다.
so each value is unique now let's go back to sql okay
1:16:48
그 작업은 매우 간단합니다. 고유한 목록을 반환하라고 합니다.
that task is very simple it says return unique list
1:16:51
모든 국가의 목록을 반환하라고 하니, 그걸 해봅시다.
of all countries so let's go and do that it's
1:16:55
재미있을 것입니다. 그러니 선택하고 이제 국가 열을 가져옵니다.
gonna be funny so select and now let's get the column country
1:16:58
우리 테이블 고객에서 이렇게 이제 모든 국가의 목록을 볼 수 있습니다.
from our table customers like this now you can see
1:17:01
하지만 작업에서는 고유한 목록이 필요하다고 합니다.
we have a list of all countries but the task says we need a
1:17:04
즉, 여기서 반복이 있어서는 안 됩니다.
unique list so that means i cannot have here repetitions inside it
1:17:07
그래서 우리는 매우 멋진 distinct를 사용할 것입니다. 이렇게 하면 가서
and with that we're gonna use the very nice distinct so if you do it like this let's go and
1:17:13
실행하면 결과에 중복이 없다는 것을 알 수 있습니다.
execute you will see there will be no duplicates in your results and
1:17:17
결과의 모든 값이 고유할 수 있습니다. 그래서 우리는 작업을 해결했습니다.
all the values in the result can be unique so with that we have solved the task
1:17:20
매우 간단합니다. 이제 distinct에 대해 한 가지가 있습니다.
it's it's very simple now there is like one thing about the distinct
1:17:23
많은 사람들이 필요하지 않은 경우에 많이 사용하는 것을 봅니다.
that i see a lot of people using it a lot in cases
1:17:26
예를 들어, 이제 ID를 가져가 보겠습니다.
that it's not really necessary so for example let's go
1:17:29
이제 가서 실행하면
and get the id now if you go and execute it you
1:17:32
여기에서 모든 ID의 목록이 있으며 중복이 없습니다.
can see here we have a list of all ids and there are no duplicates
1:17:35
하지만 이제 내가 distinct를 제거하고 실행하면 같은 결과를 얻을 것입니다.
but now if i go and remove the distinct and execute it we will get the same results because the ids are usually unique so it really
1:17:43
중복이 없기 때문에 distinct라고 말하는 것은 의미가 없습니다.
makes no sense to go and say distinct because as you
1:17:46
데이터베이스는 각 값이 한 번만 발생하도록 해야 합니다.
can see the database has to go and make sure each value happens
1:17:49
그래서 SQL에 추가 작업이 필요합니다.
only once so there is like extra work for the sql and
1:17:52
이것은 일반적으로 비용이 많이 드는 작업입니다.
it is usually an expensive operation so if your data
1:17:55
데이터가 이미 고유하다면 distinct를 적용하지 마세요.
is already unique don't go and apply distinct only if
1:17:58
중복이 보이고 원하지 않는 경우에만 distinct를 적용하세요.
you see repetitions and duplicates and you don't want to see that
1:18:01
이것은 일반적으로 나쁜 관행입니다.
only in this scenario go and apply that distinct don't go blindly for each query applying distinct just in case there is duplicates
1:18:09
그래서 distinct에 대한 모든 내용은 여기까지입니다.
this is usually bad practices okay so that's all for distinct
1:18:12
친구들, 이제 중복을 제거하는 방법을 배웠습니다.
okay my friends so with that you have learned how to remove the
1:18:15
다음 단계에서는 select와 함께 사용할 수 있는 또 다른 키워드에 대해 이야기할 것입니다.
duplicates using the distinct in the next step we're gonna talk about another
1:18:19
데이터를 제한하기 위해 top을 사용할 수 있습니다.
keyword that you can use together with the select you can
1:18:22
이게 무슨 뜻인지 이해해 봅시다.
use top in order to limit your data so now let's go and understand
1:18:25
이게 무슨 뜻인지 알겠죠
what this means okay
1:18:30
그래서 정확히 무엇이 top인지, 다른 데이터베이스에서는 limit이라고 부릅니다. 다시 말해, SQL에서 필터링의 일종입니다. 이를 사용하면 결과에서 반환되는 행의 수를 제한합니다.
so what is exactly top or in other databases we call it limit so it is again some kind of filtering in sql if you use it it's gonna gonna go and restrict the number of rows returned in the results.
1:18:42
결과에서 보고 싶은 행의 수를 제어할 수 있습니다. 구문은 매우 간단합니다.
So you have a control on how many rows you want to see in the results. The syntax is very simple.
1:18:47
select 바로 뒤에 top이라는 키워드를 사용합니다. 그리고 결과에서 보고 싶은 행의 수를 지정합니다.
As well, directly after the select, you're gonna use the keyword top. And then you specify the number of rows you want to see in the results.
1:18:54
예를 들어, 3입니다. 그 다음에 원하는 열을 지정하고, 어떤 테이블에서 가져올지 지정합니다.
So for example, three. And then only after that, you specify the columns that you want, and then from which table.
1:18:59
이제 SQL이 이를 어떻게 실행하는지 봅시다. 일반적으로 from이 실행됩니다. 데이터를 가져올 것입니다.
Now let's see how SQL gonna execute it. So as usual, the from gonna be executed. We will get our data.
1:19:05
그 다음 단계는 열을 선택하는 것입니다. 이 경우 모든 열이 유지됩니다.
And then the second step is going to go and select the column. In this case, all the columns are going to stay.
1:19:09
그 후에 top을 실행합니다. 작동 방식은 매우 간단합니다. 데이터베이스의 각 행에 대해 행 번호가 있습니다.
And then after that, it's going to execute that top. So how it works, it's very simple. For each row in database, we have a row number.
1:19:17
이는 데이터, 예를 들어 ID와는 아무런 관련이 없습니다. 현재 결과에서 행 번호는 1, 2, 3, 4, 5입니다.
It has nothing to do with your data, with the IDs, for example, here. Like in the current result, we have row number 1, 2, 3, 4, 5.
1:19:24
이 숫자는 실제 데이터가 아닙니다. 데이터베이스에서 기술적인 것입니다. 예를 들어 ID와 같지 않습니다.
Those numbers are not your actual data. It is something technical from the database. So it is not equal to the IDs, for example.
1:19:31
ID는 실제로 귀하의 콘텐츠, 귀하의 데이터입니다. 따라서 여기서는 행 번호를 기준으로 데이터를 필터링하지 않습니다.
The IDs is actually your content, your data. So here we are not filtering based on the data based on the row numbers.
1:19:37
그래서 여기서 우리는 세 개를 정의했으므로 카운트할 것입니다. 알겠죠, 1, 2, 3번 행, 그게 전부입니다.
So since here we have defined three, it's gonna count. Okay, row number one, two, three, and that's it.
1:19:43
그래서 3번 이후의 모든 행은 결과에서 제외되고, 결과에서 세 개의 행만 얻을 것입니다.
So it's gonna make a cut and all the rows after number three, they will be excluded from the results and you will get only the three rows at the results.
1:19:51
그래서 이제 보시다시피, 이 유형의 필터링은 조건에 기반한 것이 아닙니다. 단지 행 번호에 기반한 것입니다.
So now as you can see, this type of filtering is not based on a condition or something. It's just based on the row numbers.
1:19:58
그래서 결과가 무엇이든.
So whatever results are.
1:20:00
데이터에 있는 내용을 바탕으로 특정 행에서 잘라낼 것입니다.
you have in your data it will go and make a cut at specific
1:20:03
그래서 이제 간단한 작업이 있습니다. '오직'을 검색하라고 합니다.
row so let's go to scale and practice that okay
1:20:06
세 명의 고객을 검색하라고 합니다. 그러니 가서 선택합시다.
so now we have a very simple task it says retrieve only
1:20:09
우리 테이블 고객에서 별을 선택하고 실행합시다.
three customers so let's go and do that we're gonna go and select
1:20:12
지금 보시다시피 출력에서 다섯 명의 고객이 있지만,
star from our table customers and execute
1:20:15
작업에서는 세 명만 원한다고 합니다. 조건에 대한 사양이 전혀 없으므로 조건을 작성할 필요가 없습니다.
it now as you can see in the output we have five customers but
1:20:18
우리는 단지 세 명의 고객만 원합니다. 그래서 선택 후 바로 top을 추가하고 출력에서 보고 싶은 행의 수를 지정하면 됩니다.
the task says we want only three and there is no specifications at all about any condition so i don't have to go and make a way clause where we We write a condition based on our data.
1:20:28
그래서 select top 3을 선택하고 별을 추가합니다. 가서 실행합시다. 그리고 그렇게 해서 세 명의 고객을 얻습니다. 그게 전부입니다. 매우 간단합니다.
We just want three customers. So we can do that very simply by just adding top exactly after the select and then specify the number of rows you want to see from the output.
1:20:38
좋습니다. 이제 다른 작업으로 넘어갑니다. 최고 점수를 가진 상위 세 명의 고객을 검색하라고 합니다.
So select top three and then the star. Let's go and execute it. And with that, we are getting three customers. That's it. It's very simple.
1:20:45
물론 이것은 데이터를 정렬하고 필터링하는 것의 혼합과 같습니다, 맞죠?
All right. Now, moving on to another task. It says retrieve the top three customers with the highest scores.
1:20:52
그래서 우리는 일반적으로 점수를 기준으로 데이터를 최고에서 최하로 정렬합니다. 하지만 이제는 두 가지를 함께 하고 있는 것과 같습니다. 그러니 다시 단계별로 해봅시다.
Now, of course, this is like a mix between ordering the data and filtering the data, right?
1:20:57
저는 고객에서 select star로 돌아갈 것입니다. 이제 우리가 할 수 있는 것은 점수를 기준으로 데이터를 최고에서 최하로 정렬하는 것입니다.
So we usually sort the data by the scores from the highest to the lowest. But now it's like we are doing both together. So let's do it again step by step.
1:21:05
그래서 score로 정렬하고 내림차순으로 설정합니다. 그러니 가서 실행합시다.
I will just back to the select star from customers. Now what we can do, we can go and sort the data by the score from the highest to the lowest using the order by.
1:21:14
이제 첫 번째 고객이 가장 높은 점수를 가지고 있다는 것을 볼 수 있습니다.
So order by score and then descending. So let's go and execute it.
1:21:18
그 다음은 두 번째로 높은 점수이고, 이제 여러분은 이미 알았다고 생각합니다.
now you can see the first customer is with the highest score and then the
1:21:21
상위 세 명의 고객을 얻으려면,
second highest and so on now i think you already got
1:21:24
가서 top 3을 입력하면 됩니다.
it in order to get the top three customers with
1:21:27
여기서 top 3이라고 말하고 실행하면,
the highest scores what you have to do is to just go over
1:21:30
이제 데이터에 대한 정말 멋진 분석이 생겼습니다.
here and say top three and execute it and
1:21:33
이것은 우리가 최고 점수를 가진 상위 고객을 찾는 보고서와 같습니다. 정말 놀랍고 매우 쉽습니다.
with that you have now really nice analyzes on your data
1:21:36
데이터를 정렬하면서 top을 혼합하면 상위 분석기를 만들 수 있습니다.
it's like a report where we are finding the top customers with the highest score so this is really amazing and very easy so as you can see mixing the top
1:21:45
데이터를 정렬하면 상위 분석기를 만들 수 있습니다.
with sorting the data you can make top end analyzers
1:21:48
하위 분석기를 만들 수 있습니다. 그러니 이 작업을 수행하여
or bottom end analyzers so let's have this task retrieve the
1:21:51
점수를 기준으로 가장 낮은 두 고객을 가져오고 싶습니다.
lowest two customers based on the score so now we want
1:21:54
우리 테이블에서 가장 낮은 점수를 가져오고 싶습니다.
to get the lowest scores in our table and in order
1:21:58
그것을 수행하는 것은 매우 간단합니다. 우리가 할 것은 그것을 뒤집는 것입니다.
to do that is very simple what we're gonna do we're gonna flip that so we're
1:22:01
가장 낮은 점수에서 가장 높은 점수로 데이터를 정렬할 것입니다.
gonna sort our data based on the scores ascending from the lowest
1:22:04
가장 낮은 두 고객만 원하므로 세를 두로 바꾸고 실행할 것입니다.
to the highest and since we want only the lowest two customers we're gonna
1:22:07
가장 낮은 두 고객을 가져올 것입니다. 피터와 마리아입니다. 그들은
replace the three with the two and execute it and with that we're gonna
1:22:10
가장 낮은 점수를 가지고 있습니다. 다시 말해, 매우 쉽습니다. 자, 재미있습니다.
get at the lowest two customers it is peter and maria they have
1:22:13
가장 낮은 두 고객을 가져올 것입니다. 피터와 마리아입니다. 그들은
the lowest scores again it's very easy okay this is fun
1:22:16
가장 낮은 점수를 가지고 있습니다. 다시 말해, 매우 쉽습니다. 자, 재미있습니다.
let's go to the next one get the two most recent
1:22:19
다음으로 가서 가장 최근의 두 주문을 가져옵니다.
orders well this time we are speaking about another table
1:22:22
이번에는 다른 테이블에 대해 이야기하고 있습니다.
let's go and select everything from the table orders like
1:22:27
주문 테이블에서 모든 것을 선택하겠습니다.
this so now as you can see we have here four orders and we want
1:22:30
여기 네 개의 주문이 있습니다. 우리는
the two most recent orders so most recent means we have to deal with the order dates and we can build that
1:22:37
가장 최근의 두 주문을 원합니다. 가장 최근은 주문 날짜를 다루어야 합니다.
by sorting the data by the order date so order
1:22:40
주문 날짜로 데이터를 정렬하여
by order date and since we are saying the
1:22:43
가장 높은 날짜에서 가장 낮은 날짜로 정렬합니다.
most recent orders so from the highest date to
1:22:46
내려가는 것을 의미합니다. 자, 실행해 보겠습니다.
the lowest that means descending right let's go and execute it
1:22:50
우리 데이터에 기반하여 결과를 볼 수 있습니다. 이것은
and as you can see based on our data and now we can look to our results this
1:22:53
우리 비즈니스에서 가장 마지막 주문입니다.
is the last order in our business based on the order date
1:22:56
이것은 가장 초기의 주문 중 하나입니다.
and this one is one of the earliest orders so
1:22:59
그것으로 데이터를 정렬했습니다. 가장 최근의 두 개를 원하므로
with that we have sorted the data and since we want the two most
1:23:02
여기에서 정확히 가겠습니다.
recent orders we go over here and say we go exactly
1:23:05
선택 후 상위 두 개를 말하고 실행합니다.
after the select and say top two and execute and
1:23:09
그로 인해 이제 우리의 마지막 두 주문이 있습니다.
with that we have now the last two orders in our
1:23:12
비즈니스에서 보시다시피, 상위와 주문을 결합할 수 있습니다.
business so as you can see combining the top with the order by you
1:23:15
놀라운 분석을 할 수 있습니다. 좋아요, 이것이 당신이
can do amazing analysis all right so this is how you
1:23:18
상위를 사용하여 데이터를 제한하는 방법을 배우는 것입니다.
limit your data using top and with that you have learned the basics everything
1:23:22
배울 수 있는 모든 것과 함께 모든 절을 배웠습니다.
that you can learn and with that you have learned all the clauses the
1:23:25
쿼리에서 사용할 수 있는 섹션입니다.
sections that you can use in any query in
1:23:28
SQL에서 모든 절을 처리하는 방법을 배우기 위해 모든 것을 하나의 쿼리로 결합할 것입니다.
sql now next what we're gonna do we're We're going to put everything together in one query in order to learn how SQL going to go and deal with all those clauses and how SQL going to go and execute it.
1:23:38
그럼 이제 쿼리의 코딩 순서를 보여드리겠습니다.
So let's go and do that. Okay, so now I'm going to show you the coding order of a query compared to the execution order that happens in the database.
1:23:50
쿼리의 코딩 순서는 항상 select로 시작합니다.
So the coding order of a query starts always with a select. And then exactly after that, you can put a distinct.
1:23:56
distinct 다음에 top을 넣을 수 있습니다.
And then after the distinct, you can put a top. So this is the order of all those keywords. And then you can go and select like few columns.
1:24:03
열을 지정한 후, SQL에 데이터가 어떤 테이블에서 오는지 tell합니다.
And after you specify the columns separated with a comma, you tell SQL from which table your data come from using the from clause.
1:24:10
이것은 항상 from 다음에 바로 옵니다.
Now, after that, if you want to filter the data before the aggregation, you can use the where clause.
1:24:16
그룹화를 원하면 where 절 다음에 해야 합니다.
And this always comes directly after the from. And if you want to group the data, then you have to do it after the where clause using the group by.
1:24:23
그룹화 다음에 having이 옵니다.
And after the group by comes the having if you want to filter the data.
1:24:27
쿼리에서 지정할 수 있는 마지막 것은 항상 order by입니다.
And the last thing that you can specify in query, it is always the order by.
1:24:32
이것은 쿼리의 모든 구성 요소의 순서입니다.
So this is the order of all those components of the query. And if you don't follow this order, you will get an error from the database.
1:24:38
이 쿼리를 보면 데이터를 필터링할 수 있는 많은 것들이 있습니다.
Now, if you look to this query, there are a lot of things that's going to filter your data. So let's check them one by one.
1:24:44
첫 번째는 열을 필터링하는 것입니다.
The first thing that you can do is to filter the columns. If you don't want to see all the columns, you want to see only specific columns. You use the selects.
1:24:51
물론, 반드시 사용해야 합니다.
And of course, you must use it. So the columns that you specify will be shown in the results. So it's like filtering the columns.
1:24:56
지금은 중복을 필터링하는 또 다른 유형의 필터가 있습니다.
Now there is another type of filter where you filter out
1:25:00
고유한 결과를 보려면 distinct를 사용합니다.
the duplicates if you want to see unique results and that's using the
1:25:03
결과를 행 번호에 따라 필터링할 수 있습니다.
distinct so this is another type of filter moving on we
1:25:06
top을 사용하여 결과를 제한할 수 있습니다.
can filter the result based on the row numbers
1:25:09
이 필터는 조건이 필요하지 않습니다.
so we can limit the results using the top but this type
1:25:13
행 번호와 결과에 따라 순전히 기반합니다.
of filter doesn't need any conditions it's purely based
1:25:16
행 번호와 결과에 따라 필터링합니다.
on the row number and the results now moving on if you want
1:25:19
데이터를 조건에 따라 필터링할 수 있습니다.
to filter your data based on conditions based on your data you
1:25:22
집계 전에 행을 필터링할 수 있습니다.
can filter the rows before the aggregation using
1:25:25
where 절을 사용하여 행을 필터링할 수 있습니다.
the where clause and the last type of filtering you
1:25:28
having을 사용하여 집계 후 행을 필터링할 수 있습니다.
can filter your rows after the aggregation using the having
1:25:32
다섯 가지 유형이 있습니다.
so as you can see we have like five different types and
1:25:35
결과를 필터링하는 방법을 살펴보겠습니다.
how to filter the results in sql so now let's
1:25:38
SQL이 from 절을 실행합니다.
see the execution order as we learned the first thing that's gonna happen is that sql gonna execute the from clause so sql gonna go and find your data in the database
1:25:47
이 데이터에 기반하여 다음 단계가 진행됩니다.
where all the next steps gonna be based on this data now the
1:25:51
다음 단계는 데이터를 필터링하는 것입니다.
next step that is going to do is that it's going to go and filter
1:25:54
where 절을 사용하여 데이터를 필터링해야 합니다.
the data using the where clause this has to be happened
1:25:57
먼저 데이터의 범위를 설정해야 합니다.
before anything else so before any aggregations and so on
1:26:00
일부 행이 제거될 수 있습니다.
we have to make scope of the data so once sql apply it maybe
1:26:03
데이터가 필터링된 후 그룹화를 실행합니다.
some of the rows gonna be removed and once the data is
1:26:06
유사한 값을 하나의 행으로 결합합니다.
filtered the third step is going to execute the group i so it's going to take the results and start combining the similar
1:26:14
그룹화 후 두 번째 필터를 적용합니다.
values in one row and start aggregating the data based on the aggregate function that you have specified.
1:26:19
조건에 따라 일부 집계 데이터를 제거합니다.
So now after the group by after aggregating the data what is going to do now we're going to go and apply the second type of filter the having.
1:26:26
다섯 번째 단계로 넘어갑니다.
So based on the condition the SQL going to go and start removing few aggregated data away and keep the rest.
1:26:32
select distinct를 실행합니다.
Now moving on to the step number five finally it's going to go and execute the select distinct.
1:26:38
결과에서 필요한 열을 선택합니다.
So it's going to go and start selecting the columns that we need to see in the results and remove the other stuff.
1:26:43
선택된 열에 따라 실행됩니다.
and once the columns are selected sql gonna go and execute
1:26:46
지정한 열에 따라 데이터를 정렬합니다.
the order by so it's gonna start sorting the
1:26:50
데이터가 다르게 정렬됩니다.
data based on the column that you have specified and the mechanism
1:26:53
마지막 단계가 발생합니다.
as well so the data will be sorted differently and my
1:26:56
최상위 문장을 실행합니다.
friends the last step that's gonna happen in your query will
1:26:59
항상 최상위 문장이 될 것이므로 최종 결과를 기반으로 SQL이 최상위를 실행합니다. 여기서 우리는 상위 두 개를 말하고 있습니다. 즉, 조건 없이 처음 두 개의 행만 유지하고 싶습니다.
be always the top statements so based on the final final results sql gonna go and execute the top so here we are saying top two that means we want to keep only the first two rows without any conditions.
1:27:11
SQL이 행 번호 하나, 둘을 계산한 후 잘라내고 그 이후의 모든 것을 제거합니다.
So SQL gonna count okay row number one two and after that it's gonna make cuts and remove anything after that.
1:27:17
이것이 마지막 필터이며 마지막 단계입니다.
So this is the last filter that's gonna happen and as well the last step.
1:27:21
이제 이 코드를 보고 있으면 코딩 순서가 실행 순서와 완전히 다릅니다.
So now if you sit back and look at this the coding order is completely different than the execution order.
1:27:26
코딩에서는 먼저 선택 항목을 지정해야 합니다. 실제로 선택 항목은 거의 마지막에 실행됩니다.
In the coding we have first to specify the selects. Actually the selects gonna be executed just almost at the end.
1:27:33
단계 5에서 SQL이 실행되는 방식을 이해하면
So at the step number five and once you understand how SQL execute
1:27:36
쿼리를 이해하고 올바른 쿼리를 작성하는 방법을 알 수 있습니다.
your query you can understand how to build correct queries
1:27:40
그래서
so
1:27:44
우리가 배운 첫 번째는 우리가 하나를 가질 수 있다는 것입니다.
now the first thing that we have learned that that's we can go and have like one
1:27:47
쿼리, 즉 select star와 같은 것입니다.
query right something like this select star
1:27:50
고객으로부터, 이제 이것은 하나의 쿼리입니다.
from customers now this is one query and in
1:27:53
출력에는 하나의 결과가 있지만, SQL에서
the output we have one results but did you know that in SQL
1:27:56
우리는 여러 쿼리와 여러
we can have like multiple queries and multiple
1:28:00
결과를 한 번에 가질 수 있다는 것을 알고 계셨나요? 그래서 우리는 모든 것을 함께 할 수 있습니다.
results in one go so we can do everything together like
1:28:03
예를 들어, 주문에서 데이터도 선택한다고 가정해 보겠습니다.
for example let's say I'm selecting as well the data from orders
1:28:06
즉, 우리는 두 개의 쿼리를 가지고 있으며, 이제 만약 당신이
so that means we have two queries and now if you
1:28:09
실행하면 어떤 일이 발생할까요? 당신은
go and execute what can happens you will get
1:28:13
두 개의 결과 그리드를 얻게 됩니다. 첫 번째 결과 그리드는 첫 번째
two result grids the first result grid is for the first
1:28:16
쿼리를 위한 것이고, 두 번째 것은 두 번째
query and the second one is for the second
1:28:19
쿼리를 위한 것입니다. 그래서 이를 통해 같은
query so with that you can do multiple queries in the same
1:28:22
창에서 여러 쿼리를 할 수 있으며, 그 결과는
window and with that the results can be splitted into
1:28:25
쿼리 수에 따라 여러 창으로 나눌 수 있습니다. 일반적으로 SQL에서는
multiple window depend how many queries you have and usually in SQL
1:28:28
각 쿼리 끝에 세미콜론이 있다는 것을 발견할 수 있습니다.
you might find that by the end of each query there
1:28:32
이와 같이, 첫 번째 쿼리 끝에는 세미콜론이 있고, 두 번째 쿼리에도 있습니다.
is a semicolon like this so at the end of the first
1:28:35
또한 세미콜론이 있습니다.
query we have semicolon and for the second query we have as well
1:28:38
끝에 SQL 서버를 위한 또 다른 세미콜론이 있습니다.
at the end another semicolon for the sql server it is
1:28:41
필수는 아니지만 다른 데이터베이스에서는 여러 쿼리가 있을 경우
not a must but for other databases if you have multiple queries
1:28:44
하나의 실행에서 세미콜론으로 구분해야 합니다.
in one execution you must separate them with a
1:28:47
세미콜론으로 구분하면 데이터베이스가 첫 번째 쿼리의 끝과 두 번째 쿼리의 끝을 이해할 수 있습니다.
semicolon and with that the database can understand okay this is the end of the first query and this is the end of the
1:28:54
두 번째 쿼리이므로 쿼리 간에 구분이 있습니다.
second query so you have like separations between queries
1:28:57
좋아요
okay
1:29:02
이제 SQL에서 또 다른 멋진 기능으로 넘어가겠습니다.
now moving on to another cool thing in sql now what
1:29:05
테이블 내부의 데이터를 쿼리하고 싶지 않다면
if we don't want to query the data inside our tables we
1:29:08
우리에게서 정적 값을 보여주고 싶습니다.
would like to show a static value from us from the one that
1:29:11
쿼리를 작성하는 사람에게서 정적 값을 보여주고 싶습니다.
is writing the query and this is very practical if you are like practicing
1:29:15
테이블에서가 아닌 당신의 값을 사용하여 무언가를 확인하고 싶다면
and you want to check something using a value from you not
1:29:18
테이블에서 무언가를 확인하고 싶다면
from the tables so how we can do that it is very
1:29:21
간단합니다. SELECT를 작성할 것입니다.
simple we're gonna write select and then now after
1:29:24
그 후에 열 이름 대신
that instead of having a column name you can go
1:29:27
숫자를 추가할 수 있습니다. 예를 들어 1, 2, 3과 같은
and add any value like one two three so it is just a
1:29:30
그 후에 어떤 테이블도 지정하지 않습니다.
number and we do not specify after that any table
1:29:34
이렇게 두 개의 숫자를 선택하고 필요하지 않습니다.
so we leave it like this select one two three and we don't need to
1:29:37
FROM 절을 사용하지 않으므로 이렇게 두 개의 숫자를 선택하고 필요하지 않습니다.
use the from clause so now if you go and execute it you will
1:29:40
이렇게 하면 1, 2, 3을 얻을 수 있습니다.
get one two three so this is a static value and of course you can go and rename the column like static number so excuse again so with With that, we have a static value.
1:29:50
정적 값이므로 문자열과 같은 것을 추가할 수 있습니다.
And you can go and add anything like string as well. So let's say hello as static, for example, string.
1:29:57
이제 실행해 보겠습니다. 이제 두 개의 쿼리가 있습니다.
So let's go and execute. Now we have two queries.
1:29:59
두 번째 쿼리에서 정적 값 hello를 볼 수 있습니다.
The second one you can see our static value hello so
1:30:03
쿼리에서 우리 값도 추가할 수 있습니다.
in queries we can add values from us not only selecting
1:30:06
쿼리에서 데이터베이스의 데이터를 가져오고
data from the queries of course you can go and mix stuff so
1:30:09
우리의 정적 데이터를 쿼리에 포함할 수 있습니다.
we can have like in one query data from the database and
1:30:12
정적 데이터와 데이터베이스에서 데이터를 가져올 수 있습니다.
static data from us so let me show you what i mean let's go
1:30:15
여기에서 선택하고 고객 테이블에서 예를 들어 ID와 이름을 가져옵니다.
over here and say select and let's go and get for example the id the first name from the table customers like this So with us, we can see we are getting data from the database.
1:30:26
이제 여기서 무슨 일이 일어나고 있나요? 데이터베이스의 두 개의 열과 우리의 한 열이 있습니다.
But now I can go and add something from me. New customer. And we can call it customer type.
1:30:33
이제 실행하면 ID와 이름은 데이터베이스에서 가져온 데이터입니다.
So now what is going on here? Two columns from the database and one column from us. It is the static one.
1:30:38
각 레코드에 대해 항상 같은 정적 값을 가져옵니다.
So if you go and execute it, you can see for the ID and the first name, those data comes from the database.
1:30:43
이 정보는 쿼리에서 가져온 것입니다.
But for each record, we are always getting the same static value. New customer, new customer, and so on.
1:30:49
데이터베이스에 저장되지 않고 두 정보는
So this piece of information comes from the query. it is
1:30:52
데이터베이스에 저장된 데이터에서 가져옵니다.
not stored inside the database and those two informations come
1:30:55
여기서 몇 가지 정보를 추가할 수 있습니다.
from the stored data inside the database so this is
1:30:58
데이터베이스에서 데이터를 가져올 수 있습니다.
really cool thing you can add few informations from you
1:31:01
정적 값입니다.
and you can get the data from the database this is the static
1:31:05
값이 괜찮습니다
values okay
1:31:09
내가 보여주고 싶은 또 하나의 멋진 점은 쿼리가 있을 때입니다
one more cool thing that i want to show you that if you have a query like
1:31:13
이것은 테이블에서 선택하고 데이터를 필터링하는 것이며 이제
this you are selecting from table and filtering the data and now you
1:31:16
전체를 실행하지 않고 일부만 실행하고 싶습니다
would like not to execute the whole thing you would like to execute
1:31:19
이 쿼리의 일부만 실행하고 싶습니다. 그래서 때때로 쿼리를 작성할 때
only a part of this query so now sometimes as you are writing a
1:31:22
전체를 실행하고 싶지 않고 일부만 실행하고 싶습니다
query you don't want to execute the whole thing you want to execute only
1:31:25
예를 들어 모든 고객을 보고 싶습니다
a part of the query like for example i would like to see all the customers
1:31:28
이 쿼리에서 이 필터 없이 다시
again in this query without this filter so instead of
1:31:32
제거한 다음 쿼리를 실행하거나 다시 추가하는 대신
removing it and then query and then again or adding
1:31:35
원하는 부분을 강조 표시하고 필터 없이 실행할 수 있습니다
it what you can do you can highlight what you want without
1:31:38
그래서 데이터베이스가 강조 표시한 내용을 정확히 실행할 수 있습니다
now the filter and execute so that the database can execute
1:31:41
이제 보시다시피 필터 없이 모든 고객을 얻고 있습니다. 아무것도 강조 표시하지 않고 실행하면
exactly what you highlighted and now as you can see i'm getting all the customers without the filter and if you don't highlight anything and execute what can happen is you're gonna execute
1:31:50
편집기 내의 전체를 실행하게 됩니다. 이것은 정말 좋습니다
the whole thing inside the editor and this is really nice if you want
1:31:53
같은 편집기에서 다른 테이블을 빠르게 쿼리하고 싶을 때
to query another table quickly in the same editor like we want
1:31:56
주문에서 모든 것을 빠르게 선택하여 강조 표시할 수 있습니다.
to select everything from the orders just quickly so you can highlight
1:32:00
이 쿼리만 실행하고 그 SQL은
only this query and execute and with that sql is
1:32:03
다른 모든 것은 무시하고 내가 실행하는 것만
ignoring everything else and only executing what i'm
1:32:06
강조 표시하고 이것은 정말 좋습니다. 속도와 동적을 제공합니다.
highlighting and this is really nice it gives us like speed and dynamic
1:32:09
그래서 여러분은 제가 코스에서 그것을 많이 하는 것을 보게 될 것입니다.
and you're gonna find me doing that a lot on the course so
1:32:13
정말 좋습니다. 친구들, 그래서 우리는 기본을 배웠습니다.
this is really nice okay my friends so with that we have learned the basics
1:32:16
SQL 쿼리의 기본 구성 요소에 대해
about sql query the basic components of the
1:32:19
선택 문을 사용하여 데이터베이스와 대화할 수 있습니다.
select statements and with that you can talk to our database in
1:32:22
데이터를 가져오기 위해 다음 장에서는 데이터베이스의 구조를 정의하는 방법을 배울 것입니다.
order to get data now in the next chapter we're gonna learn how to define
1:32:25
우리 데이터베이스의 구조를 배우고 데이터 정의 언어를 배울 것입니다.
the structure of our database so we're gonna learn the data definition
1:32:29
자, 보통 비어 있는 데이터베이스가 있으면
language ddl so let's go okay
1:32:35
구조를 정의하는 것이고, 우리가 보통 하는 첫 번째 작업 중 하나는
so usually if you have like an empty database what you want to
1:32:39
새 테이블을 만드는 것입니다. 여기에는 create라는 명령이 있습니다.
do is to go and define the structure of your data so one of the first things that we usually do is we go and create
1:32:45
이 명령을 사용하면 데이터베이스 내에 새로운 객체를 만들 수 있습니다.
a new tables so here we have a command called create and
1:32:48
예를 들어 테이블을 만들 수 있습니다. 실행하면
if you use it you can create a new object inside the database
1:32:51
새로운 테이블을 얻을 수 있으며 일반적으로 테이블은 비어 있습니다.
like for example a table so once you execute it you're
1:32:54
데이터 없이 매우 간단합니다. 이것이
gonna get brand new table and usually the table gonna be empty
1:32:57
create 명령이 하는 일이며, 이제 SQL로 가서
without any data so it is very simple this is what
1:33:00
새 테이블을 생성하는 것입니다. 친구들, 우리는 다음 작업이 있습니다.
that create command does and now let's go to sql in order
1:33:03
persons라는 새 테이블을 만들고 열을 추가합니다.
to create a new table so my friends we have the following task
1:33:06
id, 이름, 생년월일 및
create a new table called persons with columns
1:33:10
전화번호. 자, 이번에는 select로 시작하지 않을 것입니다.
id person name birth date and
1:33:13
create table 명령으로 시작할 것입니다.
phone okay so this time we will not start by select we
1:33:16
SQL에 테이블을 만들라고 지시하고 그 후에 정의해야 합니다.
will start with the command create table so
1:33:19
테이블의 이름을 지정해야 합니다. 이 작업에서는 persons라고 부릅니다.
we are telling SQL to create a table and after that we have to define
1:33:22
테이블의 이름을 정의해야 하므로 이 작업에서 우리는 이를 persons라고 부릅니다.
the name of the table so in this task we have to call it persons
1:33:26
이제 우리는 이렇게 두 개의 괄호를 열어야 합니다.
now we have to go and open two parentheses like this and
1:33:29
그 사이에 열을 정의해야 하므로 먼저 필요한 것은 id입니다. 이것이 첫 번째 열의 이름입니다. 다음으로 이 열의 데이터 유형을 정의해야 합니다. 이 데이터 유형은 int가 될 것입니다.
in between we have to define the columns so what do we need first we need an id so this is the first column name and next we have to define which data type for this column it's It's going to be an int.
1:33:39
그래서 이것은 문자 없이 존재하는 숫자입니다. 이제 다음으로 몇 가지 제약 조건을 정의할 수 있습니다. ID 없이 사람을 가질 수는 없습니다.
So it is a number that does not contain any characters. And now next we can define some constraints. And we cannot have a person without an ID.
1:33:46
그래서 null이 아니어야 합니다. 그래서 not null입니다. 이것이 첫 번째 열입니다. 그래서 우리는 열의 이름, 데이터 유형 및 제약 조건을 정의했습니다.
So it should not be a null. So not null. This is the first column. So we have defined the name of the column, the data type, and the constraint.
1:33:53
좋습니다. 이제 두 번째 열로 가겠습니다. 여기서 우리는 쉼표를 가질 것입니다. 다음 이름은 person name이 될 것입니다.
Okay, so let's go to the second column. And here we're going to have a comma. And the next one name is going to be person name.
1:34:00
이것이 열의 이름입니다. 우리는 person name을 가질 수 있습니다. 이제 이 열의 데이터 유형은 varchar가 될 것입니다. 왜냐하면 person name은 문자를 포함하기 때문입니다.
So this is the column name. The person name we can have. And now the data type for this column is going to be a varchar. Because the person name contains characters.
1:34:08
그래서 var char이고 이제 길이를 정의해야 합니다. 그래서 저는 50자로 가겠습니다. 이제 이것은 필수라고 말할 수 있습니다.
So var char and now we have to define the length. So I'm going to go with 50 characters. And now I would say this is a must.
1:34:15
각 사람은 이름을 가져야 합니다. 그래서 저도 not null이라고 말할 것입니다. 그래서 우리는 이름, 유형 및 제약 조건을 가졌습니다.
So each person should have a name. So I'm going to say not null as well. So with that we have the name, the type and the constraint.
1:34:22
이제 세 번째 열로 이동해 보겠습니다. 생년월일이 될 것입니다. 생년월일 안에 어떤 유형의 정보가 있는지 알아보겠습니다.
Now let's move to the third column. It's going to be birth date. Now which type of information we have inside the birth date.
1:34:29
그래서 날짜가 될 것이고, 숫자도 아니고, 문자도 아닙니다. 그래서 데이터 유형은 date로 가겠습니다. 이제 제약 조건에 대해 이야기하자면, 글쎄요, 상황에 따라 다릅니다.
So it's going to be a date, not a number, not characters. So we're going to go with the data type date. And now about the constraint. Well, depends.
1:34:35
우리 애플리케이션에서는 선택 사항이라고 말할 수 있습니다. 왜냐하면 이것은 매우 개인적인 정보이고, 아마도 일부 사람들은 생년월일을 제공하지 않을 것입니다.
I would say in our application, it is an optional because this is very personal information and maybe some persons will not provide their birth dates.
1:34:43
그래서 이것은 선택 사항이며, 저는 not null이라고 말하지 않을 것입니다. 그래서 null이 허용됩니다. 이제 다음으로 넘어가겠습니다. 전화번호가 될 것입니다.
So this is an optional and I will not say it is not null. So nulls are allowed. Now let's move on to the next one. It's going to be the phone.
1:34:50
전화의 데이터 유형은 무엇인가요? 글쎄요, 우리는 숫자, 문자, 특수 문자가 있는 몇 가지 유형이 있습니다. 그래서 우리는 무엇이든 가질 수 있습니다.
So now what is the data type of a phone? Well, we have some types numbers, we have characters, special characters, so we could have anything.
1:34:57
그래서 저는 여기에서 far chart로 가겠습니다. 당신이 괜찮다고 생각하는 길이를 지정할 수 있습니다. 저는 15로 가겠습니다.
So that's why I'm going to go with the far chart here you can specify the length that you think it's okay i'm gonna go with 15.
1:35:04
물론 당신이 구축하는 시스템에 따라 다릅니다. 저는 이렇게 말할 것입니다.
now of course depend on the system that you are building i would say
1:35:07
글꼴은 이것이 실제 사람인지 확인하는 데 매우 중요합니다.
the fonts are very important in order to validate whether
1:35:10
이것은 실제 사람입니다. 그래서 우리는 아니라고 말할 것입니다.
this is a real person so we're gonna say not
1:35:13
null이 아니므로 이 필드에서 null을 허용하지 않습니다. 완벽합니다. 그래서 이를 통해 필요한 모든 열을 다루었습니다.
null so we are not allowing nulls in this field perfect so with that we have covered all the columns that are required we have defined
1:35:21
데이터 유형과 제약 조건을 정의했습니다. 이제 마지막으로
the data types and as well the constraints now the last thing in
1:35:24
각 데이터베이스 테이블에는 기본 키가 있어야 합니다.
each database table we should have a primary key
1:35:27
이 테이블이 무결성을 유지하고
in order to make sure this table has an integrity and
1:35:30
다른 테이블과 연결될 수 있도록 하기 위해서입니다. 이제 우리가 할 것은
maybe as well connectable to other tables so now what we're
1:35:33
기본 키 제약 조건을 추가하는 것입니다.
going to do we're going to go and add the primary key constraint comma
1:35:36
마지막 열에 대해 제약 조건을 설정할 것입니다.
for the last column and then we're going to say constraints now we
1:35:39
기본 키 이름을 지정해야 합니다. 이는 데이터베이스에서만 보이므로 pk로 부르겠습니다.
have to give a primary key name this is only going to be visible for the database so i'm going to call it pk for primary
1:35:46
여기서 사람들을 위한 기본 키를 지정하고 그 후에
key and here persons and then after that we're gonna
1:35:49
기본 키라고 말할 것이며 두 개의 괄호 사이에
say primary key and between two parentheses we're
1:35:52
어떤 것이 기본 키인지 선택할 것입니다. 물론 그것은
gonna go and pick which one is the primary key and of course it's gonna be
1:35:56
id가 될 것입니다. 그래서 여기서 id라고 말할 수 있습니다.
the id so we can go over here and say id so again
1:35:59
새로운 제약 조건이 있습니다. 이것은
we are saying there is a new constraint this is the name of
1:36:02
데이터베이스 내부에서만 사용되며, 이 필드 id에 대한 기본 키라고 말하고 있습니다. 그래서 이제 우리는 테이블에 대한 기본 키를 정의했습니다. 실행해 보겠습니다. 성공적으로 완료되었습니다.
it it's only internal for the database and then we are saying this one is a primary key on the field id so that's it with that we have defined a primary key for our table let's go and execute it so as So as you can see, it is successful.
1:36:14
우리의 새로운 테이블을 확인해 보겠습니다. 만약 이미 보이지 않는다면, 데이터베이스를 마우스 오른쪽 버튼으로 클릭하고 새로 고침해야 합니다.
Let's go and check our database for our new table. So if you don't see it already, you have to right click on the database and then go and refresh.
1:36:21
테이블로 가보겠습니다. 이제 'persons'라는 새로운 테이블이 생겼습니다. 그래서 우리는 새로운 테이블을 만들었습니다.
So let's go to the tables and now we have a brand new table called persons. So with that, we have created our new table.
1:36:28
물론 DDL 명령어에 대해서는 결과나 데이터를 얻지 못할 것입니다.
Now, of course, for the DDL commands, you will not get results or data.
1:36:32
당신이 받는 것은 데이터베이스의 메시지이며, 그 메시지는 명령이 성공적으로 완료되었다고 말합니다.
All what you're getting is a message from the database and the message says here the command completed successfully.
1:36:38
그리고 우리는 이것이 완료된 날짜를 가집니다. 즉, DDL 명령어는 결코 데이터를 반환하지 않습니다.
And then we have a date when this is completed. So that means that DDL commands will never return data.
1:36:43
이는 데이터베이스의 구조를 변경하고 있습니다. 데이터 검색과는 관련이 없습니다.
It is changing the structure of your database. It's not about retrieving any data and so on.
1:36:49
이 명령어는 데이터베이스에서 무언가를 변경했습니다. 이 경우, 새로운 테이블을 생성했습니다.
So this command did change something in our database. And in this scenario, it created a new table.
1:36:54
그래서 우리는 이것을 데이터 정의 언어 DDL이라고 부릅니다. 데이터베이스를 정의하고 있기 때문입니다.
And that's why we call this data definition language DDL. Because we are defining the database.
1:37:00
이제, 만약 당신이 'persons'라는 새로운 테이블에서 select star를 실행하면.
Now, of course, if you go and say select star from our new table persons.
1:37:05
하이라이트하고 실행해 보겠습니다.
So let's go highlight it and then execute it.
1:37:08
당신은 물론 열을 얻고 있습니다. 그래서
you will see we are getting of course the columns so the
1:37:11
id, 사람 이름, 생년월일, 전화번호가 있지만
id the person name birth date the phone but we
1:37:14
행이 없다는 것은 우리의 테이블이 비어 있다는 의미입니다.
don't have any rows that means our table is empty
1:37:17
이제 매우 중요한 것은 당신이 이 정보를 SQL 스크립트에 저장하는 것입니다.
now what is very important to that you go and save
1:37:20
나중에 이 테이블을 재정의해야 할 수도 있지만, 당신이
those informations in an sql script because maybe
1:37:23
다른 쿼리를 만들었고 스크립트를 잃어버렸다고 가정해 보겠습니다.
later you have to redefine this table but let's say that you
1:37:26
이것에 대한 생성 문을 다시 보고 싶습니다.
have created different queries and you have lost the script and now
1:37:30
다른 쿼리를 만들었고 스크립트를 잃어버렸다면, 왼쪽으로 가면 방법이 있습니다.
i would like to see again the create statements for this
1:37:33
테이블에 대해 다시 보고 싶습니다. 왼쪽으로 가면
table well there is trick for that if you go to the left side
1:37:36
여기 있는 사람들을 볼 수 있고, 오른쪽 클릭한 다음
you see the persons right here right click on it and then you
1:37:39
스크립트 테이블이 있으며, 이제 다양한 옵션이 있습니다.
have here script table as and now we have here different options
1:37:43
테이블에서 실행할 수 있는 것들이며, 첫 번째는 생성합니다.
that we can run on the table and the first one says create
1:37:46
그럼 새로운 쿼리 편집기로 가봅시다.
two then let's go to new query editor so
1:37:50
이제 데이터베이스가 메타데이터 정보를 읽었습니다.
now what happened the database did read the metadata informations
1:37:53
사람에 대한 정보를 가지고 ddl 쿼리를 생성했습니다.
about the person and created your ddl query with
1:37:57
우리가 하지 않은 많은 추가 내용이 있습니다. 이것이 템플릿입니다.
many extra stuff that we haven't done this is the template that
1:38:00
데이터베이스가 사용하는 템플릿입니다. 이제 많은 내용을 볼 수 있지만
the database uses so now we can see a lot of stuff but what is
1:38:03
흥미로운 것은 이 생성 테이블입니다. 생성할 수 있습니다.
interesting is this create table so we can see create
1:38:07
스키마 dpu 기본값인 테이블과 사람들입니다.
table the schema dpu the default one then the persons
1:38:10
그리고 우리는 열, 데이터 유형 및 제약 조건을 가지고 있습니다.
and then we have our columns the data type and as
1:38:13
이로써 ddl 문장을 얻었습니다.
well the constraints so with that you got back your ddl
1:38:17
테이블에 대한 많은 다른 정보가 있지만, 지금 제가 정말 필요한 것은 이 테이블에 대한 생성 문장을 보는 것입니다.
statements and many other stuff about the table which is now not
1:38:20
이것이 ddl 명령을 되찾는 방법입니다. 물론 제가 추천하는 것은
interesting but now what i really need is to see the create statements about this table so this is how you can get back your ddl command but of course what i recommend you is
1:38:28
항상 코드를 git 저장소에 넣고
always put your code inside a git repository and
1:38:32
항상 최신 상태로 유지하여 작업을 확인할 수 있도록 하는 것입니다.
always keep it up to date so that always you can check your work
1:38:35
그리고 그것을 확장하세요.
and extend it okay
1:38:40
이제 데이터베이스 구조로 무엇을 더 할 수 있는지.
so now what else you can do with the structure of your database if
1:38:43
이미 테이블이 있다면, 할 수 있는 것은 편집하는 것입니다.
you have already a table what you can do you can go and edit
1:38:47
테이블의 정의를 변경하는 것입니다. 예를 들어, 새로운 열을 추가하고 싶다고 가정해 보겠습니다.
and change the definition of the table so for example let's say i would like to add a new column in order to do that
1:38:53
우리는 alter 명령어를 사용할 수 있습니다. alter는 당신이 원한다는 뜻입니다.
we can use the command alter alter means you want
1:38:56
테이블의 정의를 편집하고 변경하고 싶다는 뜻입니다.
to edit the definition of your table and you want to change
1:38:59
새로운 열을 추가하거나 데이터 유형을 변경하는 것과 같은.
it like adding new column or maybe changing the data type
1:39:03
테이블의 정의에서 모든 것을 변경하는 것입니다. 그래서 alter 명령어입니다.
and anything in the definition of the table so the alter command
1:39:06
테이블 정의를 변경하기 위해 사용할 수 있습니다.
you can use it in order to change the definition of your table and
1:39:09
이제 스케일로 돌아가서 무언가를 변경해 보겠습니다.
now let's go back to scale and try to change something all right now
1:39:12
작업은 이메일이라는 새 열을 추가하라고 합니다.
the task says add a new column called email to
1:39:15
사람의 테이블이므로 할 수 있는 일이 매우 간단합니다.
the person's table so it is very simple what you can do we can use
1:39:18
ALTER TABLE 명령을 사용하므로 새 테이블을 만들지 않습니다.
the alter table command so we are not creating a
1:39:22
수정할 테이블은 사람 테이블입니다.
new table we want to edit already existing table so
1:39:25
SQL에 사람 테이블에서 무언가를 변경하겠다고 말하고 있습니다.
which table we want to modify it's going to be the persons so we
1:39:28
물론 SQL에 무엇을 변경할 것인지 알려야 합니다.
are telling sql we want to change something in the table persons and
1:39:31
열을 제거할 것인지, 추가할 것인지 이 시나리오에서는
of course we have to tell sql what we want to change are we removing
1:39:35
새 열을 추가할 것이므로 이메일 정보를 추가하겠습니다.
a column are we adding column in this scenario we want to
1:39:38
이제 이메일에는 문자, 숫자, 특수 문자가 포함됩니다.
add a new column so let's go and add the email information so this is the column name and as you are creating a table you have to to define column name, the data type and the constraint.
1:39:47
이제 길이는 50으로 하겠습니다. 각 사람은 이메일을 가져야 합니다.
So now for the emails, we're going to have like characters, numbers, special characters. So we're going to go with the varchar.
1:39:54
NULL이 아니므로 이를 통해 완전히 추가하고 있습니다.
And about the length, it's going to be, let's say 50. And I'm going to say each person has to have an email.
1:40:00
새 열이므로 이제 실행해 보겠습니다.
not null so with that we are adding completely a
1:40:03
다시 말하지만, 이것은 쿼리가 아니라 DDL 명령입니다.
new column so that's it let's go and execute it now
1:40:06
출력에서 데이터는 얻지 못하고 메시지를 받게 됩니다.
again this is not a query this is a ddl command and
1:40:09
모든 것이 올바르게 진행되었는지 확인하는 메시지를 받습니다.
in the output we will not get data we will get the message whether everything
1:40:13
이 작업이 완료되면 간단한 쿼리를 실행하여 테이블을 확인할 수 있습니다.
went correctly so it says commands completed successfully at
1:40:16
새 열인 이메일이 테이블의 끝에 항상 추가됩니다.
the time when this is completed now we can go and do simple query just to have a check to the table so and now you can see we have our columns and at the end we have a new column called emails This is very important.
1:40:27
이메일을 중간에 두고 싶다고 할 수도 있습니다.
If you are adding a new column, it's going to be always at the end of the table.
1:40:32
그렇게 하려면 테이블을 완전히 삭제하고 다시 만들어야 합니다.
But now you might say, you know what, I would like to have the email like something in the middle, maybe after the person name.
1:40:37
테이블 끝에 새 열을 추가하는 것이 괜찮다면 다른 테이블을 사용할 수 있습니다.
Well, in order to do that, you have completely to delete and drop the table and create it from the scratch using create command, which might be bad if you have data inside the table.
1:40:46
중간에 두고 싶다면 안타깝게도 모든 것을 삭제해야 합니다.
So if you are fine by adding your new column at the end, you can use the other table.
1:40:51
모든 것을 삭제하고 처음부터 시작해야 합니다.
but if you say i would like it in the middle then sadly you have to go and
1:40:55
모든 것을 삭제하고 처음부터 시작하겠습니다.
drop everything and start from the scratch okay so now let's have
1:40:58
다른 작업이 있으며, 그 작업은 그 사람의 전화 열을 제거하라고 합니다.
another task and it says remove the column phone from that person's
1:41:01
그래서 이제 우리는 정확히 반대로 할 것입니다. 그것을 완전히 제거할 것입니다.
table so now we're gonna do exactly the opposite we're gonna go remove it
1:41:04
테이블에서 데이터를 포함하여 완전히 제거할 것입니다. 그래서 우리는
completely with its data from the table so we're
1:41:07
여전히 'persons' 테이블을 수정하겠다고 말하고 있습니다. 우리는 테이블 정의를 수정하고 싶습니다. 이제 추가하는 대신
gonna still saying alter table persons we are saying we want to edit the definition of the table persons and now instead of adding we will be dropping
1:41:16
열을 삭제할 것입니다. 그리고 그 후에 우리는
a column and then after that we have to specify
1:41:19
열 이름을 지정해야 합니다. 전화가 될 것이지만 우리는 다시
as well the column name gonna be the phone but we don't
1:41:22
데이터 유형과 제약 조건을 언급할 필요가 없습니다.
have to mention again the data type and the constraint
1:41:25
데이터베이스가 이미 그 정보를 알고 있기 때문입니다. 그래서
and that's because the database already knows those informations so
1:41:29
우리는 새로운 것을 만들 때 그 정보가 필요합니다. 그래서 우리는
we need those informations if we are creating something new that's why we
1:41:32
그것을 없앨 수 있습니다. 우리는 열 이름만 필요하고
can get rid of that we just need the column name and
1:41:35
데이터베이스가 나머지를 처리할 것입니다. 그러니 가서 해봅시다.
the database is gonna do the rest so let's go and do that
1:41:38
이제 성공적으로 보입니다. 이제 우리의
now you can see successful and now let's go and check our
1:41:41
테이블을 확인해 봅시다. 이제 볼 수 있듯이 우리는 ID, 이름, 생일
table and now as can see we have the id person name birth
1:41:45
이메일이 있으며 전화 열이 없습니다. 조심하십시오. 만약
date email and we don't have the column phone be careful if
1:41:48
열을 삭제하면 그 열의 모든 데이터도 잃게 됩니다.
you are deleting column you will be losing as well all the data
1:41:51
그래서 볼 수 있듯이 이것은 매우 간단합니다. 이것이
inside this column so as you can see this is very simple this
1:41:54
우리 테이블의 정의를 수정하는 방법입니다. 열을 추가하고
is how we can edit the definition of our table by adding
1:41:57
열을 제거하는 것 괜찮아요
and removing columns okay
1:42:03
이 명령 그룹의 마지막으로 넘어갑니다. 지금까지 우리가 한 일은
now moving on to the last one in this group of commands so now so far what we have done
1:42:07
데이터베이스에 새로운 것을 만들었고, 우리는 변경했습니다.
we have created something new in the database we have changed
1:42:11
데이터베이스 내부의 무언가의 정의를
the definition of something inside our database and
1:42:14
이제 마지막으로, 데이터베이스에서 무언가를 삭제할 수 있습니다.
now the last one you can go and drop something from the
1:42:17
다른 테이블이 있다고 가정하고, 우리는 그것이 필요하지 않습니다.
database let's say we have another table and we don't need
1:42:20
더 이상 그래서 우리는 드롭 명령을 사용할 수 있습니다.
it anymore so we can go and use the drop command
1:42:23
테이블을 완전히 제거하기 위해서입니다.
in order to remove the table completely from the
1:42:26
데이터베이스에서 테이블을 완전히 제거하려면 이 테이블과 그 안의 모든 것을 제거해야 합니다. 이제 스케일로 가서 데이터베이스에서 무언가를 삭제해 보겠습니다. 자, 이제 우리의 작업은 데이터베이스에서 persons 테이블을 삭제하라는 것입니다.
database and this means as well removing everything that table and that inside it so now let's go to scale and let's drop something from our database okay so now our Our task says delete the table persons from the database.
1:42:39
이것은 SQL에서 가장 간단한 명령 형태이지만, 가장 위험한 형태이기도 합니다.
This is the simplest form of command in SQL, but yet the most risky one.
1:42:44
우리가 필요한 것은 전체 persons 테이블을 삭제하고 제거하는 것입니다. 더 이상 필요하지 않습니다. 테이블을 삭제하겠다고 말할 것입니다.
So what we need, we have to delete and drop the whole table persons. We don't need it anymore. We're going to say drop table.
1:42:51
그런 다음 우리가 해야 할 모든 것은 persons 테이블의 이름을 지정하는 것입니다. 세 단어입니다. 아무것도 지정할 필요가 없습니다.
And then all what we have to do is to give the name of the table persons. So three words. We don't have to specify anything.
1:42:58
그냥 persons 테이블을 파괴하십시오. 가서 실행해 보겠습니다. 성공했습니다. 보시다시피 매우 간단합니다.
Just destroy the table persons. Let's go and execute it. It is successful. So as you can see, it is very simple.
1:43:04
이제 데이터베이스의 왼쪽에서 새로 고침하고 테이블로 가면 persons 테이블이 보이지 않을 것입니다.
Now on the left side to your database, go refresh and go to the tables and you will not see the table persons.
1:43:10
drop 명령은 매우 간단하지만, 매우 위험합니다.
So the drop command, it is very simple, but yet very risky.
1:43:13
이제 create table과 drop table을 비교하면, 무언가를 파괴하는 것이 그것을 만드는 것보다 훨씬 쉽다는 것을 알 수 있습니다.
So if you compare now create table with a drop table, you can see destroying things is way easier than building it.
1:43:20
이것이 바로 create, alter, drop 명령입니다. 이러한 명령은 데이터베이스의 구조를 정의하는 데 사용됩니다. DDL 명령입니다.
Those are the commands create, alter, drop. Those commands we use in order to define the structure of our database, the DDL commands.
1:43:29
그래서 매우 간단한 이유입니다. 자, 이제 데이터 정의 언어 DDL에 대한 모든 것입니다.
That's why it's very simple. All right, so that's all about the data definition language DDL.
1:43:33
이제 여러분은 데이터베이스에서 새로운 것을 정의하는 방법을 배웠습니다.
and with that you have learned how to define new stuff in your database now
1:43:37
다음으로 넘어가서 데이터 조작 언어에 대해 배워보겠습니다.
moving on to the next one we're going to learn about the data manipulation language
1:43:40
여기서 우리는 데이터베이스 내에서 데이터를 조작하는 방법을 배울 수 있습니다.
and here we can learn how to manipulate our data inside the database
1:43:43
모두 가봅시다.
let's go all
1:43:49
자, 이제 우리가 할 일은 데이터를 수정하고 조작하는 것입니다.
right so now what we're going to do we're going to go and modify and manipulate your
1:43:53
데이터베이스 내에 테이블이 있고 그 테이블이 비어 있을 때가 있습니다. 테이블 안에 행이나 데이터가 없습니다.
data inside the database so now sometimes what happens you have a table inside your database and the table is empty you don't have any rows any data inside the table.
1:44:02
이제 테이블에 데이터를 추가하려면, inserts 명령을 사용할 수 있습니다.
Now in order to add your data to the table, what you can do, you can use the command inserts.
1:44:07
insert는 테이블에 새로운 행을 추가할 것입니다. 물론 테이블이 비어 있어야만 데이터를 추가할 필요는 없습니다.
So insert going to go and add a new rows to your table. And of course, not always the table must be empty to add your data.
1:44:14
기존 데이터에 새로운 행을 추가할 수 있습니다. SQL은 테이블의 끝에 추가할 것입니다.
You can add new rows to already existing data. And SQL going to go and append it at the end of the table.
1:44:20
이제 친구들, 목표 테이블에 새로운 데이터를 삽입하기 위해 두 가지 방법이 있습니다.
Now my friends, in order to insert new data to the target table, there are two methods.
1:44:25
새로운 데이터를 삽입하는 첫 번째 방법은 insert 명령을 사용하고, 테이블에 삽입해야 할 값을 수동으로 지정하는 것입니다.
The first and the classical way in order to insert new data, we can use the insert command and manually specifying the values that should be inserted to the table.
1:44:34
스크립트에서 값을 지정하기 시작하면, 그 값들이 목표 테이블에 새로운 행으로 삽입될 것입니다.
So you're going to start specifying in the script the values and then they're going to be inserted as a new rows to the target table.
1:44:41
이 과정에서 SQL 스크립트를 사용하여 테이블에 새로운 값을 수동으로 삽입하고 있습니다.
So in this process you are manually inserting new values to the table using like an SQL script.
1:44:47
이제 데이터 삽입 방법에 대한 이 시나리오에 집중하겠습니다. 자, 이제 insert 명령의 구문을 빠르게 확인해 보겠습니다.
So now we're going to focus on this scenario on how to insert data. All right now let's check quickly the syntax of the insert command.
1:44:53
insert into라는 키워드로 시작하고, 그 다음에 테이블 이름을 지정해야 합니다.
It starts with the keyword insert into and after that we have
1:44:56
테이블 이름을 지정해야 하므로 삽입할 위치를 정하고
to specify the table name so where we want to insert and
1:44:59
우리가 원하는 모든 열의 목록을 만듭니다.
then we make a list of all columns that we want to
1:45:02
값을 삽입할 열 목록을 지정합니다.
insert and then we specify a list of columns where we're gonna
1:45:05
값을 삽입할 열 목록을 지정합니다.
insert values into them and after that we say values
1:45:09
테이블에 삽입해야 할 데이터를 지정하고
and finally we're gonna go now and specify the data
1:45:12
열을 지정하지 않으면 선택 사항입니다.
that should be inserted to the table and we make it as well as a list like we have done for the columns now in the insert statements specifying those columns it is totally
1:45:21
SQL은 값을 삽입할 것으로 예상합니다.
optional so if you don't specify the columns of the table then
1:45:24
각 열에 값을 삽입해야 합니다.
sql gonna expect you to insert values into
1:45:27
각 열에 대한 값을 제공할 수 있습니다.
each column because sometimes of course we don't want to insert
1:45:31
각 열에 대한 값을 제공할 수 있습니다.
value for each column you can skip few columns of course
1:45:34
각 열에 대한 값을 지정하거나 건너뛸 수 있습니다.
but if you want to insert a value for each column either
1:45:37
열과 값의 수는 일치해야 합니다.
you go and specify them as a list or you can skip it
1:45:40
정확히 세 개의 값을 삽입해야 합니다.
now for the insert statements there is a very important rule the number of columns and values must match so if you specify here three columns then you must
1:45:49
이것은 일치해야 하며 구문에 대한 마지막 사항입니다.
insert as well exactly three values so
1:45:52
한 번에 여러 값을 삽입할 수 있습니다.
this must be matching and one last thing about the syntax you
1:45:55
각 행에 삽입해야 할 값 목록을 지정할 수 있습니다.
can insert multiple values in one go so for each
1:45:59
구문에 대한 모든 내용은 여기까지입니다.
row you can specify a list of values that must be inserted
1:46:02
값 목록을 지정할 수 있습니다.
so that's all about the syntax let's go back to sql in
1:46:05
새 고객을 삽입하는 것은 매우 간단합니다.
order to practice inserts command okay so now let's go and
1:46:08
고객 이름을 지정해야 합니다.
insert a new customers so it's very simple it starts with insert into so we are saying we want to insert data into so we have to go and specify the table
1:46:17
데이터를 삽입할 열을 지정해야 합니다.
name customers now after that we have to specify list of
1:46:20
테이블에 어떤 열이 있는지 확인할 수 있습니다.
columns where we want to insert data into it and what you
1:46:23
값이 필요합니다. 어떤 데이터를 삽입해야 할까요?
can do we can go and check which columns do we have inside our table so we can see we have id first name country score and we can go and make a list of that so we can say id first name
1:46:34
이제 ID를 지정해야 합니다.
country and score so we just have a list of all columns inside our table customers now what we need we need the values so which data should be inserted so we can go and open two parentheses
1:46:46
마지막 고객은 다섯이었습니다.
and now we have to specify an id we know the last customer was
1:46:50
다섯이므로 고객 여섯으로 가겠습니다.
five so we're gonna go with the customer six now we have to give
1:46:53
고객의 이름을 입력해야 합니다. 안나로 가죠.
the name of the customer let's go for anna and then a
1:46:56
국가를 입력해야 합니다. 미국으로 가죠.
country let's go for usa and this customer has
1:47:00
점수가 없으므로 null이라고 할 수 있습니다.
no scores so what we can do we can say null so
1:47:03
이 고객의 점수를 알 수 없습니다. null은
we don't know the score of this customer nulls means
1:47:06
아무것도 알 수 없으므로 한 행을 삽입할 수 있습니다. 이제 두 번째 행을 삽입하고 싶다고 가정해 보겠습니다.
nothing we don't know so with that you can go and insert one row but now let's say that i would like to go and insert like a second row one more customer what
1:47:14
쉼표로 구분할 수 있습니다.
can do we can separate this with a comma and
1:47:17
그런 다음 전체를 반복할 수 있습니다. ID는
then we can go and repeat the whole thing again so the id
1:47:21
일곱입니다. 다음 고객은 샘이라고 부르겠습니다.
is seven the next one let's call this customer sam and
1:47:24
이 고객의 국가를 알 수 없으므로 null이라고 하겠습니다.
we don't know the country of this customer so we're gonna say it's
1:47:27
그러나 점수는 이미 알고 있습니다. 100입니다.
null but the score we know it already it is 100 so
1:47:30
각 열에 값을 추가하고 있습니다. 만약
as you can see we are adding a value for each of those columns and if
1:47:33
답을 모른다면 null로 설정하세요. 데이터베이스가 허용한다면.
you don't know the answer then make it null if the database allows
1:47:36
null이 될 수 있습니다. 일부 열은 null이 허용되지 않습니다.
it to be null some columns they are not allowed to be null like
1:47:40
기본 키와 같은 열입니다. 여기서 null이라고 하면 데이터베이스가
the primary key so if you go say over here null the database will
1:47:43
허용하지 않을 것입니다. 실제로 테스트해 보겠습니다.
not allow it well actually we can go and test it let's
1:47:46
실행해 보세요. null 값을 삽입할 수 없음을 알 수 있습니다.
execute and you can see you cannot insert the value null
1:47:49
ID 열에 null을 삽입할 수 없습니다. 이는 허용되지 않습니다.
into the column id so this is not allowed you can have a seven
1:47:52
다른 열은 허용됩니다. 정의를 확인할 수 있습니다.
but for the other columns it is allowed you can go and check the definition
1:47:56
이제 테이블을 실행하고, 수정 명령의 출력이
of the table now we go and execute now the
1:47:59
데이터에 어떤 일이 발생했는지 항상 나타낼 수 있습니다. 두 행이 영향을 받았다고 합니다.
output of the modifications command it can always indicate what happens to the data so it says two rows affected affected might be inserted updated, deleted.
1:48:09
데이터베이스에서 일반적인 문장을 얻을 수 있지만, 영향을 받은 레코드 수를 얻고 있습니다.
So you can get a general statement from the database, but you are getting how many record is affected.
1:48:14
두 개의 레코드를 삽입했으므로 두 개를 얻었습니다. 이제 보시다시피, 쿼리와는 다릅니다.
So we got two because we have inserted two records. So now as you can see, it's not like the query. We are not getting any data in the output.
1:48:21
우리는 단지 메시지를 받고 있습니다. 이는 선택을 사용하여 데이터를 쿼리하는 것과 삽입을 사용하여 데이터를 수정하는 것의 큰 차이입니다.
We are just getting a message. So this is a big difference between querying the data using the selects and modifying the data using inserts.
1:48:29
우리는 이제 데이터베이스 내의 데이터에 직접 수정을 하고 있습니다.
We are doing now direct modifications to the data inside our database.
1:48:33
물론, 데이터를 보고 싶다면 고객이 무엇을
Of course, if you you want to see the data and the customers what
1:48:36
할 수 있는지 데이터를 쿼리해 보겠습니다.
we can do we can go and query the data right so let's
1:48:39
전체 테이블을 보고 싶으니 마크하고 실행해 보세요.
go and do that select star from customers i would like to see
1:48:42
고객이 7명 있다는 것을 알 수 있습니다. 우리는 데이터를 조작했습니다.
the whole table so mark it and execute it now
1:48:45
여기 앤나와 샘이 있습니다. 이렇게
you can see we have seven customers so we just manipulated
1:48:48
여기 데이터가 있습니다. 안나와 샘, 이것이 당신이
our data we have here anna and sam this is how you
1:48:51
데이터베이스에 데이터를 삽입하는 방법입니다. 이제 몇 가지 규칙이 있습니다. 새 데이터를 테이블에 삽입할 때 주의해야 할 점은
can insert data to the database now there is like few rules you have to be careful as you are inserting new data to your tables you have to pay attention that the order of
1:49:00
정의한 열의 순서가 삽입하는 값과 일치해야 한다는 것입니다.
the columns that you have defined insert is matching
1:49:03
예를 들어 보겠습니다.
the values that you are inserting over here let's have an example
1:49:06
여기서 이것을 제거하고, 새로운 번호 8을 삽입한다고 가정해 보겠습니다.
i'm gonna go and remove this over here and let's say
1:49:09
첫 번째 이름에 고객의 이름 대신
that we are inserting new one number eight and now in
1:49:12
국가인 미국을 삽입했습니다.
the first name instead of the name of the customers we have inserted
1:49:16
국가에는 이름을 삽입했습니다. 단순한 실수입니다. 우리는 모두 인간이니까요. 그러니 이런 이름을 사용해 보겠습니다. 맥스.
the country like usa and in the country we have
1:49:19
이제 실행하면 데이터베이스는
inserted the name it's just a mistake and we are all human right so let's have a name like this max now if you go and execute it the database
1:49:26
이것이 오류라는 것을 이해하기가 정말 어렵기 때문에 수용할 수 있습니다.
can accept it because it is really hard for the database to understand that you
1:49:29
두 개 모두 varchars이고 데이터베이스는
have made here an error both of them are varcharts and the database
1:49:32
데이터 유형 규칙을 따르는 한 데이터의 내용에 신경 쓰지 않습니다.
doesn't care about the content of the data as long as you are
1:49:35
이제 고객 데이터에서 선택하면
following the rules of the data type so now if you go and select the
1:49:39
이제 우리는 맥스라는 고객이 있는 것을 볼 수 있습니다.
data from the customers you can see now we have a customer called
1:49:42
국가에서 미국을 선택했습니다. 그래서 SQL은
usa from the country max so the sql
1:49:45
데이터를 삽입하는 것을 맹목적으로 수행할 것입니다. 데이터 유형 규칙과 제약 조건을 따르는 한.
gonna do it blindly like you insert the data as long as you are following the data type rules and the constraints
1:49:51
예를 들어, 여기서 이 오류를 발생시키고 ID가 맥스라고 말하면,
So for example, if you made this error over here and you say the
1:49:55
첫 번째 이름이,
ID is max and let's say the first name is,
1:49:58
아홉이라고 가정하고 여기서 실행하면
let's say nine and you execute it here the
1:50:01
데이터베이스는 똑똑하게도 뭔가 잘못되었다고 말할 수 있습니다.
database is smart enough to say you know what there is something wrong the
1:50:04
id는 제한되어서는 안 되므로 데이터베이스가 삽입을 거부할 수 있습니다
id should not be strained so the database can reject your inserts
1:50:07
이제 열의 순서에 주의하세요, 가봅시다
be careful of the order of your columns now let's go
1:50:10
이제 삽입 명령어에 있다면 테이블에서 쿼리하세요
and query in our table now if you are in the insert commands
1:50:13
테이블과 정확히 같은 모든 열을 정의합니다
defining all the columns exactly like the table
1:50:17
보시다시피 여기에는 id, 이름, 국가, 점수가 완벽하게 일치합니다
so as you can see we have here complete match id first name country score
1:50:20
모든 열과 올바른 순서가 있습니다
we have all the columns and as well as the correct order there is like
1:50:23
여기에서 전체를 제거할 수 있는 간단한 방법이 있습니다
lazy way you can go and remove the whole thing over here and with
1:50:26
데이터베이스가 이해할 수 있도록 값을 삽입하고 있습니다
that the database can understand okay we are inserting values
1:50:29
각 열에 올바른 방향으로 무언가를 삽입하고 있습니다
to all of the columns so it's really gonna understand you are inserting
1:50:32
올바르게 진행합시다, 아홉, 여기서
something to each columns in the correct direction so
1:50:36
안드레아스가 있다고 가정하고
let's go and do that correctly nine and here let's
1:50:39
독일에서 온다고 말하고 있습니다
say we have andreas and we are saying from
1:50:42
열을 정의하지 않았지만 작동할 것입니다
germany so if you go and execute it it will be working
1:50:45
삽입하는 값이 정확히 같은 수의 열이기 때문입니다
even though we didn't define the columns and that's because the
1:50:49
테이블의 열 수와 규칙을 따릅니다
values that we are inserting has exactly the same number of
1:50:52
다음으로 넘어가서 두 개의 열만 추가할 수 있습니다
columns of the table and following as well the rules now moving
1:50:55
다음으로 넘어가서 두 개의 열만 추가할 수 있습니다.
on to the next one you can go and add only two columns
1:50:58
점수가 null이면 두 가지 정보만 알고 있습니다
in the definition if you know already always the country
1:51:01
id와 이름이므로 항상 null이라고 말할 필요는 없습니다
and the score is null we know only two informations
1:51:04
null null null 등등, 우리는 그것을 건너뛸 수 있습니다
the id and the name then you don't have always to go and say
1:51:07
이제 제가 무슨 뜻인지 보여드리겠습니다, 테이블 이름 뒤에 가겠습니다
null null null and so on we can go and skip that okay so
1:51:11
우리는 id와
now let me show you what i mean we're gonna go after the table name and
1:51:14
이름만 정의할 것입니다
we're going to define only two columns the id and the
1:51:17
두 개의 열만 정의할 것이므로
first name so that means we are telling sql we want to insert
1:51:20
여기 두 개의 열을 정의하면 값도 두 개의 열이어야 합니다
only two columns and now you have to be careful if you define
1:51:23
여기 두 개의 열이 있으므로 값도 두 개의 열이어야 합니다
here two columns then the values should be as well two columns
1:51:26
그래서 우리는 국가와 점수를 제거할 것입니다
so we're going to remove the country and the score
1:51:29
그리고 우리는 예를 들어 사라를 추가할 수 있습니다
and we can go and add only two informations so then
1:51:32
당신이 실행하면 작동할 것이고 이제 기술이란 무엇인가
and we can go and add here for example sarah so if
1:51:35
다른 두 열과 함께 하는 것은 null이 될 것이므로
you go and execute it it will be working and now what is skill
1:51:38
다시 테이블에서 선택해 보겠습니다. 여기 사라가 보입니다
is doing with the other two columns it's gonna be nulls so let's
1:51:41
국가와 점수에 null이 있습니다. 왜냐하면 우리는
go and select again from our table you can see here sarah
1:51:45
그 정보를 정의하지 않았지만 여기서 건너뛰면 안 됩니다
has null in the country and as well in the score because we
1:51:48
null이 허용되지 않는 열을 건너뛰면 안 됩니다
didn't define those informations but be careful you cannot here skip
1:51:51
항상 목록에 null이 아닌 모든 열을 포함해야 합니다
a column that is not allowed to be null so you have
1:51:54
예를 들어, 나는 이름만 삽입할 수 없고 오류가 발생할 것입니다
always to have in your list all the columns that are not
1:51:57
모든 열이 null이 아닌 목록을 항상 유지해야 합니다
null for example i cannot go and insert only the first name i will get an error because the database can try to insert a null in the id and this is not allowed so you can skip only nullable columns
1:52:12
좋습니다, 친구들. 이것이 데이터를 삽입하는 첫 번째 방법이었습니다
all right my friends so that was the first method on how to
1:52:15
타겟 테이블에 데이터를 삽입하는 방법을 보았습니다
insert data to your target table as you saw by typing
1:52:18
수동으로 삽입 명령어 안에 값을 입력하고
manually the values inside an insert command using
1:52:22
이제 다른 방법으로 이동해 보겠습니다. 이번에는 수동으로
values and now let's move to another methods we're gonna insert data but this time not manually we're gonna insert data using another
1:52:29
데이터를 삽입할 것입니다. 이미 존재하는 테이블이 있습니다
table so imagine we have the following scenario we have an already
1:52:33
데이터가 있는 테이블과 이것이 소스 테이블이 될 것입니다
existing table with data and this is going to be the source table
1:52:36
당신의 데이터 소스와 또 다른 테이블이 있습니다
the source of your data and we have another table this
1:52:39
이 테이블은 비어 있으며 새로운 데이터를 삽입하고 싶습니다
table is empty and we want to insert a new data to
1:52:42
이 타겟 테이블에 이제 할 수 있는 것은
this target table now what you can do we can take the data from
1:52:45
소스 테이블에서 데이터를 가져와 타겟에 삽입하는 것입니다
the source table and insert it into the target
1:52:48
스크립트를 수동으로 작성하지 않고
table without manually writing a script for the
1:52:51
우리는 한 테이블에서 다른 테이블로 데이터를 이동하고 있습니다
values so we are moving the data from one table to another
1:52:55
이제 그렇게 하려면 두 단계를 수행해야 합니다
now in order to do that we need to do two steps the
1:52:58
첫 번째 단계는 SQL 쿼리를 작성하는 것입니다.
first step we have to write an sql query using
1:53:01
데이터를 선택하기 위해 select from 등을 사용해야 합니다.
select from and so on in order to select the data
1:53:04
소스 테이블에서 필요한 데이터를 가져오면
that we need from the source table and once you
1:53:08
결과를 얻을 수 있습니다. 이것은 일반 쿼리를 작성하는 것과 같습니다.
do that you will get a result so this is like you are doing
1:53:11
결과와 함께 답변을 얻을 수 있습니다. 다음 단계에서는 이 결과를 가져와서
a normal query you write select and you will get an
1:53:14
대상 테이블에 이 결과를 삽입하기 위해 insert 명령을 사용할 수 있습니다.
answer with the results and now what you can do in the next step we can take these results and use an insert command in order to insert these results into the target table.
1:53:25
이로써 소스 테이블에서 대상 테이블로 데이터를 이동했습니다. 먼저 소스 테이블에서 쿼리를 작성하세요.
And with that, we have moved the data from the source table to the target table. So first, write the query on the source table.
1:53:31
두 번째 단계는 이 결과를 대상 테이블로 이동하기 위해 insert를 사용하는 것입니다.
And the second step, use an insert to move these results to the target table. So let's go back to SQL in order to do that.
1:53:38
이제 다음 작업이 있습니다. 고객 테이블에서 사람 테이블로 데이터를 삽입하라고 합니다.
So now we have the following task, and it says, insert data from the table customers into the table persons.
1:53:42
즉, 소스 테이블은 고객이고 대상 테이블은 사람입니다.
So that means the source table is the customers and the target table is persons.
1:53:49
보통 제가 하는 방법은 대상 테이블의 구조를 이해하기 위해
Now, how I usually do it is that, I keep my eye on the target table to understand the structure of this table and I start writing the query from the source table.
1:53:59
왼쪽으로 가면 ID, 이름, 생년월일, 전화번호가 있습니다.
If you go to the left side, we can see, okay, we have here an ID, we have here person name, birth date, and phone.
1:54:04
생년월일만 볼 수 있고, 나머지는 항상 정보를 제공해야 합니다.
And you can see only the birth date, except nulls, and the rest we have always to provide information.
1:54:09
이로써 사람 테이블에 대한 이해가 생겼습니다. 이제 소스에서 쿼리를 작성하기 시작하겠습니다.
So with that, I have now understanding about the table persons. Now next, I'm going to go and start writing the query from the source.
1:54:16
이렇게 시작합니다. 고객 테이블에서 모든 데이터를 선택하여
So we start like this. Select star from our table customers just to have an overview of our table.
1:54:22
우리 테이블의 개요를 확인합니다.
Now the next step we're gonna go and design a perfect result from this query that is matching the target table.
1:54:30
이제 다음 단계는 이 쿼리에서 대상 테이블과 일치하는 완벽한 결과를 설계하는 것입니다.
So in the output we need id and we have it from the customer from the original table. We're gonna go and select id.
1:54:36
출력에서 ID가 필요하며, 원본 테이블의 고객에서 가져옵니다.
Okay so now next we need a person name and here we have from the original table something called first name. So this is a perfect match.
1:54:43
이제 다음으로 사람 이름이 필요하며, 원본 테이블에서 이름이 있습니다.
So we're gonna I'm going to go and select this table as a second column. So we have covered the first two. Then the third one is going to be the birth date.
1:54:50
따라서 두 번째 열로 이 테이블을 선택하겠습니다.
Well, my friends, we don't have birth dates, but the database can accept it as a null.
1:54:54
첫 번째 두 개를 다루었습니다. 세 번째는 생년월일이 될 것입니다.
So I'm going to go and write a null because I don't have such information from the source table.
1:54:59
친구들, 우리는 생년월일이 없지만 데이터베이스는 null로 수용할 수 있습니다.
And now the next one gonna be the phone as well we don't have
1:55:02
따라서 소스 테이블에서 그런 정보가 없기 때문에 null을 작성하겠습니다.
phone informations but we cannot have it as a null because it
1:55:05
다음은 전화번호입니다. 전화 정보가 없지만
says here is not null so what we're gonna do we're gonna go and add
1:55:08
null로 가질 수는 없습니다. 여기서 null이 아니라고 하므로
a static value a default value so we're gonna have
1:55:11
두 개의 작은 따옴표 사이에 'unknown'이라고 적습니다.
two single quotes and in between we're gonna say unknown
1:55:14
이것은 varchar이므로 이 단어를 수용할 수 있습니다.
since it is varchar it can accept this word
1:55:17
이제 쿼리를 실행해 보겠습니다.
so now let's go and just query so we have the
1:55:20
id, 이름, 생년월일이 있습니다.
id we have the first name the birth date is
1:55:23
빈 값이고 글꼴은 알 수 없습니다. 하지만
empty and the fonts is unknown now you might say but
1:55:27
열 이름이 해당 열 이름과 일치하지 않습니다.
the column name is not matching with the column name of the
1:55:30
사람들, 데이터베이스는 그에 대해 신경 쓰지 않습니다.
persons well the database does not care about that as
1:55:33
데이터 결과가 일치하는 한
long as the result of the data is matching the
1:55:36
데이터베이스는 열 이름을 비교하지 않습니다.
table it can go and insert it so the database will never
1:55:39
여기에서 별칭을 추가할 수 있습니다.
compare the column names together but if you like and go and
1:55:42
테이블에 영향을 주지 않지만 결과에는 영향을 미치지 않습니다.
add here like the aliases exactly like the target
1:55:45
결과가 괜찮습니다. 이제 쿼리 선택을 해보겠습니다.
table it will not hurt but it has no effect on
1:55:48
결과가 괜찮습니다. 이제 쿼리 선택이 있습니다.
the results all right okay so now we have like query select
1:55:52
이것을 테이블에 삽입하는 방법입니다.
and we have a result but this is not an insert so
1:55:55
사람들, 이를 위해 삽입 명령이 필요합니다.
how we can insert the result of this into the table
1:55:58
따라서 삽입하고 이제
persons well for that we need the inserts into commands
1:56:02
대상 테이블은 사람들일 수 있습니다.
so insert into and now we have to specify the
1:56:05
모든 열 이름을 나열할 수 있지만
target table can be the persons and of course you can
1:56:08
정확히 일치하면 생략할 수 있습니다.
go and list all the column names but if you have like
1:56:12
하지만 저는 항상 추가하고 싶습니다.
exact match you can skip it but for me i would like always to add it just to make sure that we don't have an issue so the id person
1:56:19
이제 실행해 보겠습니다.
name birth date and the phone so
1:56:24
작동하고 있습니다. 10개의 행이 영향을 받았습니다.
that's it let's go and execute so it
1:56:27
이는 고객 테이블에서 10개의 행이 삽입되었음을 의미합니다.
is working now we can see 10 rows affected well that
1:56:30
대상 사람들로 들어갔습니다.
means 10 rows are inserted from the table customers
1:56:33
이제 우리는 사람들 테이블을 쿼리할 수 있습니다.
into the target persons and now what you
1:56:36
우리가 할 수 있는 것은 테이블을 쿼리하여 확인하는 것입니다.
can do we can go and query the table persons just to check
1:56:39
모든 것이 완벽하게 작동하는지 확인하십시오. 고객으로부터 추가한 10명의 사람들을 확인해 보겠습니다.
that everything is working perfectly select star from persons and let's go and execute and with that you can see
1:56:46
고객으로부터 추가한 10명의 사람들을 확인해 보겠습니다.
our 10 persons that we have added from the customers
1:56:50
하나의 테이블에서 데이터를 이동하고
so with that we have moved the data from one table and
1:56:53
다른 테이블에 삽입했습니다. 매우 간단합니다.
inserted into another table and as you can see it was very
1:56:56
먼저 소스 테이블에서 쿼리를 작성해야 합니다.
simple first you have to write a query from the source
1:56:59
필요한 데이터를 수집한 후 대상 테이블에 삽입합니다. 정말 쉽습니다.
table in order to collect the data that you need and then you go and insert it into the target table so this is really nice and easy and this is another way on how to insert data into your database.
1:57:15
이제 새로운 데이터가 없다고 가정해 보겠습니다.
Okay, so with that we have learned how to insert data to our tables. Now let's say that I don't have something new.
1:57:20
테이블에 추가할 행이 없지만 업데이트가 있습니다.
I don't have any rows to be added to my table, but I have an update.
1:57:24
기존 행의 내용을 변경하고 싶습니다.
I would like to go and change the content of the already existing rows.
1:57:29
기존 행의 내용을 변경하는 데 사용할 수 있는 업데이트 명령을 사용할 수 있습니다.
So what you can do, we can use the command updates in order to change the content of already existing rows.
1:57:37
다시 말해, 삽입은 완전히 새로운 행을 추가하고, 업데이트는 기존 행의 데이터를 변경합니다.
So again, my friends, insert going to go and insert completely new rows, but update going to go and change the data of already existing row.
1:57:45
업데이트의 구문을 빠르게 살펴보겠습니다. 업데이트라는 키워드로 시작합니다.
Now, let's have a look quickly to the syntax of the updates. It starts with the keyword updates and then we have to specify the table name.
1:57:52
각 열에 대해 업데이트할 새 값을 작성해야 합니다.
And after that, we're going to use it in order to specify what are the new values for the columns.
1:57:57
그 후에 조건을 지정해야 합니다. 쿼리와 마찬가지로 조건을 작성합니다.
So you have to write down for each column that you want to update a new value. And you separate the columns, of course, using a comma.
1:58:03
그렇게 하지 않으면 모든 행이 업데이트될 수 있습니다.
Now, after that, we have to specify as well a where condition. So it's like the queries you say where and then you write a condition.
1:58:10
그래서 항상 where 절이 필요합니다. 알겠죠?
And if you don't do that and you don't use the where clause, what can happen?
1:58:15
구문에 대한 모든 내용은 여기까지입니다. SQL로 돌아가서 데이터를 업데이트합시다.
You will be end up updating all the rows inside your table. So that's why we need always the where clause. All right.
1:58:21
다음 작업은 고객 6의 점수를 0으로 변경하는 것입니다.
So that's all about the syntax. Let's go back to SQL in order to update our data. OK, so let's have the following task.
1:58:26
고객 ID가 6인 데이터를 수정해야 합니다. 먼저 데이터를 확인해 보겠습니다.
And it says change the score of customer six to zero.
1:58:30
고객으로부터 모든 데이터를 선택합니다. 이제 이 고객을 대상으로 합니다.
So that means we have to go and modify the data of the customer ID equal to 6. So now first I would like to go and have a look to our data.
1:58:37
null을 0으로 바꾸고 싶습니다. 이 정보를 테이블 내에서 어떻게 업데이트할 수 있을까요?
So select star from customers. Now the task is targeting this customer over here.
1:58:43
업데이트 명령을 사용할 수 있습니다. 업데이트를 작성하기 시작하겠습니다.
And we would like to replace the null to zero. Now how can we go and update this information inside the table?
1:58:49
그 후에 테이블 이름을 지정해야 합니다. 고객을 업데이트하고 있습니다.
We can use the update command. So what we're going to do, we're going to start writing updates.
1:58:54
그런 다음 데이터베이스에 값을 설정하도록 지시할 수 있습니다.
And after that, we have to specify the table name. So what we are updating, we are updating the customers.
1:59:00
그런 다음 데이터베이스에 값을 설정하라고 지시할 수 있습니다.
and then we can tell the database to set the value of the
1:59:03
점수를 0으로 설정하므로 업데이트하고 변경하고 싶습니다.
score to a zero so we'd like to update and change the
1:59:06
값을 null에서 0으로 변경하고 이제 뭔가가 옵니다.
value from null to zero and now here comes something
1:59:09
매우 위험하므로 이 쿼리를 아직 실행하지 마십시오.
very risky don't execute this query yet if you do that
1:59:12
무슨 일이 일어날지 데이터베이스가 고객 테이블로 가고
what's gonna happen the database gonna go to the table customers and
1:59:16
모든 고객의 값을 0으로 바꿉니다.
replace all those values of all customers to
1:59:19
그래서 전체 테이블을 업데이트하게 되며, 이는 물론 매우 위험합니다. 그래서 업데이트 명령에서는 조건을 지정해야 합니다.
zero so it's gonna go and update the whole table and this is of course very risky that's why in the update command we have to give aware condition
1:59:27
특정 행만 대상으로 삼기 위한 필터입니다.
a filter in order to target only specific row
1:59:30
또는 이 경우 수정하려는 행입니다.
or the rows that you want really to modify in this case
1:59:33
하나의 규칙만 변경하고 싶으므로 해야 할 일은
we want to change only one rule so what we have to do is
1:59:36
where 조건을 지정하는 것입니다.
to go and specify the where condition like we have
1:59:39
고객 ID가 다음과 같다고 말할 것입니다.
done in the select query nothing new right so we're
1:59:42
고객 ID가 같다고 말할 것입니다.
gonna say where the customer id is equal to
1:59:45
6이고, 그 SQL은 먼저 모든 것을 업데이트하지 않고 데이터를 필터링한 다음 업데이트합니다. 이제 실행하기 전에 어떤 데이터가 영향을 받을 수 있는지 확인합니다. 매우 간단합니다.
six and with that sql will not go and update everything first gonna filter the data and then updates and now before i execute just to make sure i go and check which data can be affected So it's very simple.
1:59:56
고객 테이블에서 별을 선택합니다.
You go and select star from table customers.
2:00:00
그런 다음 정확한 조건을 가져와서 쿼리에 넣습니다. 그리고 전체를 선택하고 실행합니다.
And then I go and take the exact where and put it in my query. And then I select the whole thing and execute.
2:00:07
이 쿼리가 수정되어야 할 데이터를 제공하면 업데이트 명령을 올바르게 수행하고 있는 것입니다.
And now if this query gives me the data that should be modified, then I'm doing the update command correctly.
2:00:13
이 경우, 우리는 단 하나의 고객만을 대상으로 하고 있습니다. 이것은 고객 번호 6입니다. 그래서 저는 제 업데이트에 대해 정말 자신감을 느낍니다.
And in this case, we are targeting only one customer. This is the customer number six. And with that, I feel really confident with my update.
2:00:20
그래서 나중에 사용할 것이기 때문에 전체를 명령에 넣겠습니다. 지금 실행하면 오직 업데이트만 실행됩니다.
So what we can do, since I'm going to use this later, I'm going to put the whole thing in a command. And if I execute now, only the update is going to be executed.
2:00:28
그럼 가서 해봅시다. 이제 메시지를 확인하는 것이 매우 중요합니다.
So let's go and do that. Now very important to check the message.
2:00:31
하나의 행이 영향을 받았음을 볼 수 있습니다. 이는 정말 좋은 일입니다. 여기서 10개의 행이 영향을 받았다고 보면 모든 것이 업데이트되었다는 의미입니다.
You can see one row is affected, which is really good because if I see here 10 rows is affected, that means everything is updated.
2:00:39
이제 데이터를 확인해 봅시다. 여기서 조건을 제거하고 전체 테이블을 확인하겠습니다.
Now let's go and check the data. I'm going to go and remove the where here and check the whole table.
2:00:44
이제 여전히 이전 점수가 있는 것을 볼 수 있습니다. 오직 안나만 이제 널 대신 0점을 기록했습니다.
Now you can see we still have the old scores. Only Anna has now scored zero instead of null.
2:00:51
이것이 제가 일반적으로 데이터를 업데이트하는 방법입니다. 매우 주의 깊게 해야 합니다.
So this is how I usually update the data. You have to do it very carefully.
2:00:55
이제 다른 작업으로 넘어갑니다. 변경하라고 말할 것입니다.
now let's move to another task it's gonna say change the
2:00:58
고객 번호 10의 점수를 0으로 변경하고
score of the customer number 10 to zero and update
2:01:01
국가를 영국으로 업데이트합니다. 이제 우리는
the country to uk so now this time we are targeting
2:01:04
사용자 번호 10을 대상으로 하고 있습니다. 보시다시피 그녀는
the user number 10 as you can see she doesn't have the
2:01:07
국가와 점수가 없으며, 작업은 우리에게
country and score and the task wants us to change the
2:01:10
점수를 0으로 변경하고 국가를 영국으로 바꾸라고 요구합니다. 이제 어떻게
score to zero and the country to uk so now how we can
2:01:13
할 수 있을까요? 우리는 동일한 명령을 사용할 것입니다. 하지만 조건이 다릅니다.
do it we're going to use the exact same commands but with different condition
2:01:17
이번에는 ID가 10이고 점수가 0으로 설정되어야 합니다. 하지만 이제 우리는
so the id this times is equal to 10 and a score is to zero but now we have to change as
2:01:23
국가를 변경해야 합니다. 여러 업데이트를 원하신다면
the country now if you want to do multiple updates
2:01:26
점수 뒤에 쉼표와 새 줄이 필요합니다.
you're gonna have here a comma after the score and the new line
2:01:29
그리고 국가를 설정한다고 가정해봅시다. 그러면 추가할 수 있습니다.
and let's say country equal and then we can add
2:01:33
영국으로 설정하고 전체를 선택한 다음 진행합니다.
uk so select the whole thing and let's go
2:01:36
그리고 실행합니다. 다시 말해, 이는 단 한 행에만 영향을 미칩니다.
and execute so again it is affecting only one row
2:01:39
정말 좋습니다. 테이블 검색을 확인해보면
this is really good and if you go and check the table search
2:01:42
사라에 대한 업데이트가 이루어졌음을 알 수 있습니다.
for sarah you can see in one update we have updated
2:01:46
두 개의 열, 국가와 점수를 업데이트했습니다. 이를 통해 우리는
two columns the country and as well the score so
2:01:49
작업을 해결했습니다. 매우 간단합니다. 이제 두 번째 작업으로 넘어갑니다. 모든 고객의 점수가 null인 경우 점수를 0으로 설정하라고 합니다.
with that we have solved the task it's very simple now moving on to the The second task, it says update all customers with a null score by setting their score to zero.
2:01:59
이번에는 특정 고객에 대해 이야기하는 것이 아닙니다. 고객의 일부 데이터 업데이트에 대해 이야기하고 있습니다.
So this time we are not speaking about one specific customer. We are talking about updating the data for a subset of customers.
2:02:06
이제 수백 명의 고객이 있다고 상상해보세요. 각 고객에 대해 업데이트 명령을 내리는 것은 정말 시간 낭비입니다.
So now imagine you have like hundreds of customers and you are making one update command for each customer. It can be really wasting of time.
2:02:12
그 대신 여러 고객을 대상으로 하는 조건을 지정할 수 있습니다.
Now instead of that, we can specify a condition that targets multiple customers.
2:02:18
그 고객들에 대한 업데이트를 한 번에 수행할 것입니다. 이제 어떻게 할 것인지 살펴보겠습니다.
And we're going to do the updates for those customers in one go. So now let's see how we're going to do it.
2:02:22
우리는 null을 0으로 교체하는 것만 이야기하고 있습니다. 따라서 국가는 필요하지 않습니다. 점수를 0으로 설정하세요.
We are talking only about replacing the nulls with a zero. So we don't need the country. So set score equal to zero.
2:02:29
하지만 이제 ID에 대해 구체적이지 않을 것입니다. 이제 새로운 조건을 만들어야 합니다. 이렇게 말할 것입니다. 점수가 null인 경우.
But now we will not be specific for the IDs. Now we have to make a new condition. It's going to say like this. Where score is null.
2:02:37
물론, 강의에서는 null에 대한 전용 장이 있습니다.
Now, of course, in the course, we have a full dedicated chapter about the nulls.
2:02:41
여기서 여러분이 하는 모든 것은 null과 같은 점수를 검색하는 것입니다. 하지만 우리는 같음을 쓸 수 없습니다.
And here all what you are doing is we are searching for scores that is equal to null. But we cannot write an equal.
2:02:46
이렇게 써야 합니다. null입니다. 물론, 무엇이든 업데이트하기 전에 쿼리에서 테스트해야 합니다.
We have to write it like this is null. Now, of course, before we update anything, we have to go and test it in a query.
2:02:53
고객의 점수가 null인 경우를 선택하세요. 실행해 보겠습니다.
So select star from customers where score is null. Let's go and execute.
2:02:57
이제 고객의 점수가 null인 두 명이 있습니다.
Now, as you can see, we have two customers where the score is null.
2:03:01
즉, 이 조건은 고객의 하위 집합을 대상으로 하고 있습니다.
So that means this condition is targeting a subset of customers.
2:03:05
이 하위 집합에 대해 여러 행을 업데이트할 것입니다. 따라서 이 쿼리를 실행할 수 있습니다.
And we're going to do now the updates for multiple rows for this subset. So that means we can run this query.
2:03:12
실행해 보겠습니다. 이제 두 개의 행이 영향을 받았습니다.
Let's go and execute it. Now you can see two rows are affected.
2:03:15
즉, 여러 행이 영향을 받고 업데이트되었습니다.
So that means multiple rows got affected, got updated.
2:03:20
이제 고객 테이블을 쿼리하면 점수에 null이 없습니다.
So now if you go and query our table customers, you can see we don't have any nulls inside the scores.
2:03:26
모든 null을 0으로 대체했습니다. 물론, 같은 작업을 할 수 있습니다.
And we have replaced all the nulls with zero. And of course, you can do the same thing.
2:03:30
국가의 모든 null을 대체하기 위해 업데이트 명령을 만들 수 있습니다.
You can go and make an update command in order to replace all the nulls in the country to maybe something unknown or any default value that you want.
2:03:39
이렇게 하면 여러 행을 한 번에 업데이트할 수 있습니다.
So this is how you can update multiple rows in one go.
2:03:46
좋아요, 친구들. 이제 새로운 로스트를 삽입하는 방법을 배웠습니다.
all right my friends so with that we have learned how to insert a new roast
2:03:49
우리 테이블과 내용을 업데이트하는 방법을 배웠습니다.
our tables and as well how to update the content of
2:03:53
이미 존재하는 행에 대해 마지막으로 할 수 있는 것입니다.
already existing row now the last thing or command
2:03:56
테이블의 데이터에서 행을 제거할 수 있습니다.
that we can do to the data inside the table of that we
2:03:59
우리는 delete 명령을 사용하여 이를 수행할 수 있습니다.
can go and remove rows from our table and
2:04:02
delete는 이미 존재하는 행을 제거하기 시작할 것입니다.
we can do that using the command delete so if we use
2:04:05
delete from이라고 말한 다음 테이블을 작성할 것입니다.
delete is going to go and start removing already existing rows inside your table all right now for the syntax of the delete it's going to be very simple
2:04:13
여기서 중요한 것이 추가되어야 합니다.
we're going to say delete from and then we're going to write the table
2:04:16
where 조건을 추가해야 하며, 업데이트와 같습니다.
name and here comes something very important we have to add
2:04:20
where 조건을 포함하지 않으면 발생할 수 있는 일입니다.
a where condition and it's like the update if you don't do that
2:04:23
테이블의 모든 행이 삭제될 것입니다.
if you don't include where condition what can happen you
2:04:26
구문이 매우 간단하니 다시 스케일로 돌아갑니다.
will end up deleting all the rows inside the table
2:04:29
데이터를 삭제하기 위해, id가 5보다 큰 모든 고객을 삭제하는 작업이 있습니다.
so the syntax is very simple let's go back to scale in order
2:04:32
어떻게 할 수 있을까요? 매우 간단합니다. delete from이라고 말할 것입니다.
to delete some data okay so now we have the following task delete all customers with an id greater than five so now Now we have to go and delete all the customers that we recently added.
2:04:42
즉, 테이블에서 무언가를 삭제하고 싶다는 의미입니다.
So how we can do it? It's very simple. We're going to say delete from.
2:04:45
즉, 테이블에서 무언가를 삭제하고 싶다는 의미이며, 테이블 이름을 지정해야 합니다. 고객 테이블이 될 수 있습니다. 구문은 매우 간단합니다.
So that means I want to delete something from a table and we have to specify the table name. It can be the customers. So that syntax is very simple.
2:04:52
이제, 친구들, 이것은 업데이트보다 더 위험합니다. 이렇게 실행하면 안 됩니다.
Now, my friends, this is more risky than updates, because if you executed like this, don't do that yet.
2:04:58
기다려, 무슨 일이 일어날까? 고객의 모든 데이터가 삭제될 것입니다.
Wait, what's going to happen? All the data of the customers going to be deleted.
2:05:02
그래서 빈 테이블이 생기고 우리는 그렇게 하지 않을 것입니다. 이제 업데이트 명령과 정확히 같은 방식으로 진행할 것입니다.
So you will get an empty table and we will not do that. So now we're going to do exactly like the update command.
2:05:08
우리는 where 절을 지정할 수 있습니다. 즉, ID가 5보다 커야 한다고 합니다.
We can specify the where clause. So it says the ID should be greater than five.
2:05:13
즉, ID가 5보다 높아야 한다는 의미입니다.
So that means ID higher than five.
2:05:16
따라서 이를 통해 삭제해야 할 데이터의 하위 집합을 정의하고 있습니다. 모든 것이 아닙니다.
So with that, we are defining a subset of the data that should be deleted, not everything.
2:05:20
업데이트를 확인하면, 우리는 여기서 이중 확인을 해야 합니다.
And if you check in the updates, we have here to do a double check
2:05:24
무언가를 삭제하기 전에 다시 한 번 우리가 선택하는 것은
before deleting anything so again what we do we select
2:05:27
고객 테이블에서 모든 데이터를 선택하고, 우리는
star from table customers and we're gonna go
2:05:30
where 조건을 복사하여 무엇을 테스트할 수 있는지 확인할 것입니다.
and copy the where condition in order to test what
2:05:33
삭제할 수 있는 것은 모든 고객이 5보다 높은 것입니다.
can be deleted so it's gonna be all the customers that is higher
2:05:36
그래서 내가 여기서 보는 것처럼 내 삭제 명령이 올바른지 확인하고 있습니다.
than five and with that i'm making sure that my delete
2:05:40
명령이 올바르며, 여기서 보이는 것처럼 올바릅니다.
command is correct which is from what i see here is correct so
2:05:43
그 다섯 고객은 삭제되어야 하므로 이제 그 고객들을 삭제하겠습니다. 그리고 이제 메시지를 읽는 것이 매우 중요합니다. 다섯 개의 행이 영향을 받았다고 합니다. 즉, 다섯 고객이 삭제되었습니다.
those five customers should be deleted so now let's go and delete those customers and now very important to read the message it says five rows affected so So that means five customers got deleted.
2:05:54
물론 이것은 10보다 낫습니다. 이제 남아 있는 고객들을 확인해 보겠습니다. 우리는 하나, 둘, 셋, 넷, 다섯이 있습니다.
This is better than 10, of course. So let's go and check what customers left. So we have one, two, three, four, five.
2:06:01
이것들이 원래 고객들이고 나머지는 모두 삭제되었습니다. 이렇게 우리는 작업을 해결했습니다. 이것이 테이블에서 데이터를 삭제하는 방법입니다.
Those are the original customers and everything else got deleted. And with that, we have solved the task. And this is how we can delete data from tables.
2:06:08
매우 조심하세요. 삭제 명령을 실행하기 전에 항상 테스트하세요.
Be very careful. Always test before doing the delete command.
2:06:11
좋습니다. 이제 다음 작업이 있으며, 테이블 persons의 모든 데이터를 삭제하라고 합니다.
OK, so now we have the following task and it says delete all data from table persons.
2:06:17
즉, 우리는 테이블 persons에서 모든 것을 삭제해야 합니다.
So that means we have to go and drop everything from the table persons.
2:06:21
하지만 우리는 테이블을 삭제하고 싶지 않습니다. 우리는 단지 데이터를 삭제하고 싶습니다.
but we don't want to delete the table we just want to delete the data
2:06:24
이제 테이블 내부에서 데이터를 삭제할 것입니다. 이제 우리가 할 일은 삭제 명령을 작성하는 것입니다.
inside the table now so now what we're gonna do we're gonna write delete
2:06:27
from을 사용하고 이제 테이블 persons를 지정해야 합니다.
from and now we have to specify the table persons and
2:06:31
이를 실행하면 발생할 수 있는 일은 persons의 모든 데이터를 삭제하는 것입니다.
if we execute it what can happen is going to go and drop all the
2:06:34
하지만 SQL에서는 더 많은 기능이 있습니다.
data in the persons but in sql we have more
2:06:37
모든 것을 삭제하고 싶다면 흥미로운 명령어가 있습니다.
interesting commands if you want to delete everything from the
2:06:40
사람 테이블을 비우는 방법이 있습니다. 그것은 정확히
table persons we have that truncate truncate it is exactly
2:06:43
사람 테이블을 비우는 방법이 있습니다. 그것은 정확히
like delete from persons it's gonna go and make the whole table
2:06:47
빈 테이블을 만들 것입니다. 하지만 왜 트렁크를 사용하는지
empty but why i like to use trunk it because it is
2:06:50
대량의 테이블이 있을 경우 삭제보다 훨씬 빠릅니다.
way faster than deletes if you have large tables the delete
2:06:53
삭제 명령은 정말 느려질 것입니다. 삭제와 함께
command gonna be really slow because with the delete there is like
2:06:56
많은 일이 뒤에서 일어나고 있습니다. 로그와
a lot of things happening behind the scenes there is like logs and
2:06:59
프로토콜이 있지만 트렁크를 사용하면 데이터베이스는
protocols but if you are using trunk the database can skip
2:07:02
모든 추가 작업을 건너뛰고 매우 빠르게 진행됩니다.
all those extra stuff and it's gonna be very fast
2:07:05
테이블의 모든 데이터를 삭제하고 싶다면 이렇게 할 수 있습니다.
so if you want to delete all the data from table you can do it like this
2:07:09
작은 테이블이라면 제가 보통 하는 것은
if it's like small table but what i usually do i go and
2:07:12
트렁크를 작성한 다음 테이블을
write truncate and then table we're
2:07:15
같은 효과를 얻을 수 있으며, 이로써 모든 것을 초기화합니다.
gonna get the same effects and with that i'm saying reset everything
2:07:18
테이블을 비우게 되므로 실행해 보겠습니다.
make the table empty so let's go and execute it and
2:07:21
이제 삭제된 행의 수를 얻지 못할 것입니다.
now with that you will not get the number of deleted rows and
2:07:24
그렇기 때문에 트렁크는 훨씬 빠릅니다. 프로토콜이 없습니다.
that's why it's runcate is way faster it is not protocoling
2:07:28
아무것도 기록하지 않고 모든 데이터를 삭제합니다.
anything it's not logging anything it just go and delete all
2:07:31
추가 단계 없이 데이터를 삭제하는 방법입니다.
the data without any extra steps so this
2:07:34
테이블에서 모든 데이터를 삭제하는 방법입니다. 하지만 테이블은
is how we can delete all the data from a table but the table
2:07:37
여전히 존재합니다. 친구들, 이제 기본을 배웠습니다.
still exists okay my friends so with that you have learned the basics
2:07:40
데이터베이스 내에서 데이터를 조작하는 방법에 대해
on how to manipulate your data inside the database the data
2:07:43
데이터 조작 언어 DML에 대해 배웠습니다.
manipulation language dml and with that i can tell you we
2:07:46
SQL의 기본을 다루었습니다. 이제
have covered the basics of sql so with that
2:07:49
초급 수준을 다루었습니다. 다음 장에서는
we have covered the beginner level now in the next chapters we
2:07:52
중급 수준에 들어가고, 첫 번째로 배울 것은 데이터 필터링입니다.
will be in the intermediate level and the first thing that you're going to learn in
2:07:56
중급 수준에서는 데이터를 필터링하는 방법을 배웁니다.
the intermediate level you will learn how to filter your data and
2:07:59
여기에서는 내부에서 사용할 수 있는 여러 연산자를 복구할 것입니다.
here we're going to recover many operators that you can use inside the
2:08:02
WHERE 절로 가보겠습니다.
where clause so let's go all
2:08:08
그렇다면 이제 SQL의 다양한 연산자에 대한 개요를 살펴보겠습니다.
right so now let's have an overview about all different operators in sql so
2:08:11
첫 번째 그룹의 연산자는 비교 연산자입니다.
the first group of operators we have the comparison operators they
2:08:15
비교 연산자는 가장 간단한 것으로, 두 값을 비교하는 것입니다.
are the easiest one where all what we have to do is to compare two values
2:08:18
여기에는 여섯 가지 다른 변형이 있습니다.
and we have like six different variants how to do that now to
2:08:21
다음으로는 논리 연산자가 있습니다.
the next one we have the logical operators we use it in
2:08:24
여러 연산자를 결합하기 위해 사용됩니다.
order to combine multiple operators and moving on
2:08:27
다음으로 범위 연산자가 있습니다.
to the next one we have the range operator here we have only one the
2:08:31
여기에는 하나만 있습니다.
between we're gonna use it in order to check whether a value falls
2:08:34
우리는 'BETWEEN'을 사용할 것입니다.
within a specific range now moving on to the next one we
2:08:37
값이 특정 범위에 있는지 확인하기 위해 사용됩니다.
have the membership operator and here we have two things we have
2:08:40
다음으로는 멤버십 연산자가 있습니다.
the in operator or not in here all what you have to do is
2:08:43
여기에는 두 가지가 있습니다.
to check whether a value is in a list or not and
2:08:46
'IN' 연산자 또는 'NOT IN'이 있습니다.
the last category that we have is the search operator and
2:08:49
여기서 해야 할 일은
here as well we have only one operator the like we use it
2:08:53
값이 목록에 있는지 확인하는 것입니다.
in order to search for a specific thing in a text so
2:08:56
마지막 카테고리는 검색 연산자입니다.
my friends we're gonna go through all those operators one by one okay
2:08:59
여기에도 하나의 연산자만 있습니다.
so now let's go and deep dive into the first category the comparison
2:09:02
'LIKE'를 사용하여 특정 항목을 검색합니다.
operators and we're gonna cover all those stuff so what is exactly comparison
2:09:06
운영자 괜찮아
operator okay
2:09:11
그렇다면 비교 연산자는 정확히 무엇인가요? 매우 간단합니다.
so what is exactly comparison operators it is very simple we
2:09:14
우리는 두 가지를 비교하고 싶고, 비교할 수 있는 것들이 많습니다.
want to compare two things and there is a lot of things that
2:09:17
하지만 그것에 대한 공식은 다음과 같습니다.
we can compare in sql but the formula for that is going to be
2:09:20
항상 이렇게 첫 번째 표현이 있고 그 다음
always like this so we have the first expression and then
2:09:23
연산자가 있고 그 다음 또 다른 표현이 있습니다
operator and then we have another expression and
2:09:26
이것은 조건이라고 불리는 것을 형성할 수 있습니다. 여기에는 많은
this can form something called condition so here we have a lot
2:09:29
변형이 있어 한 열을 다른 열과 비교할 수 있습니다
of variants we can compare one column to another
2:09:32
열입니다. 예를 들어, 첫 번째 이름과
column so for example you can go and compare the first name with
2:09:36
성(last name)을 비교할 수 있습니다. 두 표현 모두 열입니다
the last name so both of the expressions are columns here
2:09:39
또 다른 시나리오로, 열을
another scenario you want to compare a column with a
2:09:43
정적 값과 비교하고 싶습니다. 예를 들어, 첫 번째 이름은
value a static value like for example you say the
2:09:46
이름은 다음과 같은 값과 같아야 합니다.
first name must be equal to a value like
2:09:49
존, 그래서 이제 우리는 열을 값과 비교하고 있습니다. 더 이상 두 개의 열이 아닙니다. 이제 우리는 열에 함수를 적용하고 그 결과를 아마도 값과 비교하고자 하는 다른 시나리오가 있습니다.
john so now we are comparing a column with a value it's not anymore two columns now we have another scenario where we want to apply a function to a column and then compare their results to maybe a value.
2:10:01
예를 들어, 우리는 첫 번째 이름에 대문자 함수를 적용합니다.
So, for example, we apply the upper function to the first name.
2:10:04
그리고 이것은 모든 글자가 대문자인 존과 같아야 합니다. 그리고 당신이 비교할 수 있는 또 다른 것이 있습니다.
And then this must be equal to a value like John with all the letters in the upper case. And one more thing that you can compare.
2:10:12
한 쪽에 표현식을 쓸 수 있습니다. 예를 들어, 가격과 수량을 곱하면 1000과 같아야 한다고 말할 수 있습니다.
You can write an expression in one of the sides. Like, for example, you can say if we multiply price with the quantity, it must be equal to 1000, for example.
2:10:22
여기 우리는 표현식이 있습니다. 한 쪽에 여러 열이 포함되어 있습니다. 그리고 이 표현식의 출력은 1000과 같아야 합니다.
So here we have an expression. We have multiple columns included in one side. And the output of this expression must be equal to 1000.
2:10:29
이제 마지막 것은 조금 더 고급스러울 것입니다. 그리고 우리는 물론 다른 장에서 그것을 다룰 것입니다.
And now the last one is going to be a little bit more advanced. And we're going to cover that, of course, in another chapter.
2:10:34
우리는 전체 쿼리, 완전한 쿼리를 한 쪽에 포함할 수 있습니다. 우리는 이것을 서브쿼리라고 부릅니다.
We can include a whole query, the complete query to one of the sides. And we call this a subquery.
2:10:40
그래서 한 쪽에 전체 쿼리, 선택, FROM, WHERE, 원하는 것을 작성할 것입니다.
So in one of the sides, you're going to write a whole query, select, from, where, whatever you want.
2:10:45
그리고 이 쿼리의 결과를 예를 들어 값이나 열과 비교합니다.
And you go and compare the result of this query to, for example, a value or a column.
2:10:49
보시다시피 SQL에서는 많은 것들을 함께 비교할 수 있습니다.
So as you can see in SQL, we can compare a lot of things together.
2:10:53
열을 서로 비교하거나 열과 값을 비교하거나
either comparing the columns together or a column with a value
2:10:56
함수나 표현식을 사용하거나
or we use a function or an expression or
2:10:59
심지어 전체 쿼리까지, 이것이 우리가 조건을 만드는 방법입니다.
even a whole query so this is how we build conditions
2:11:02
SQL에서, 알겠죠, 친구들? 조건이 어떻게 작동하는지 봅시다.
in sql okay my friends so let's see how the conditions
2:11:06
우리는 데이터, 이름, 국가가 있습니다.
works in sql so we have our data the name the country
2:11:09
점수를 가지고 있다고 가정합시다. 조건을 만들었다고 합시다.
the score and let's say that we have built a condition where
2:11:12
국가는 미국과 같아야 한다고 말합니다. 이는 매우 간단한 비교 연산자이며, 우리가 WHERE 절 안에서 사용하는 조건입니다.
it says the country must be equal to the usa so this is very simple comparison operator and this is the condition that we are using inside the where
2:11:21
이 필터를 데이터에 적용하면 어떤 일이 발생할까요?
clause so once you apply this filter to your data what
2:11:24
행별로 평가하여 조건을 충족하는지 확인합니다.
can happen is going to go row by row evaluating whether
2:11:27
조건을 충족하지 않으면 결과에서 제거됩니다.
it is meeting the condition if it's not fulfilling the condition
2:11:30
조건을 충족하면 유지됩니다. 이제 우리는
then is going to remove it from the results but if it
2:11:33
열의 값과 정적 값을 비교하고 있습니다.
is fulfilling the condition it's going to keep it so now we are comparing the
2:11:37
미국과 비교할 것입니다. 우리가 얻는 값을 비교합니다.
values of column together with a static value
2:11:40
국가와 미국을 비교할 것입니다. 이제 어떻게 진행되는지 봅시다.
the usa so we're going to compare whatever value we get from the
2:11:43
이 필터를 첫 번째 고객 데이터에 적용합니다.
country together with the usa so now let's see how is going
2:11:46
첫 번째 고객의 데이터에 이 필터를 적용하기 위해
to apply this filter to our data for the first customer
2:11:49
독일이라는 것을 알 수 있습니다. 이제 이 SQL은 독일을 비교합니다.
maria now you can see the value inside the country is
2:11:52
미국과 비교합니다. 같지 않기 때문에 이 SQL은
germany so isql now gonna go and compare germany
2:11:55
미국과 비교할 것입니다. 같지 않기 때문에 이 SQL은
to usa since it is not equal then isql
2:11:58
마리아가 조건을 충족하지 않는다는 것을 이해할 것입니다.
gonna understand okay maria is not fulfilling the condition
2:12:01
그래서 이는 거짓이며 이 SQL은
so it is false and isql gonna go i remove
2:12:04
이 고객을 결과에서 제거할 것입니다. 그녀는 조건을 충족하지 않습니다.
this customer from the results so she is not fulfilling
2:12:07
다음 고객인 존으로 넘어갑니다. 이제 이 SQL은
the condition moving on to the next one to john now isql gonna take
2:12:10
국가의 값이 미국입니다. 미국과 같으므로 존은 조건을 충족합니다.
the value inside the country the usa it is equal to usa so that means john is fulfilling the condition and isql gonna be happy about it
2:12:19
그래서 이는 참이며, 이는 이 SQL이 존을 유지할 것임을 의미합니다.
so it is true and this means isquels gonna keep join in
2:12:22
최종 결과로 넘어갑니다. 조지의 값은
the final results now moving on to george the value is
2:12:25
영국, 미국과 같지 않으므로 그는 조건을 충족하지 않습니다.
uk not equal to usa he is not fulfilling the condition
2:12:28
이 SQL은 그를 최종 결과에서 제거할 것입니다.
isquels gonna go i remove him from the final results
2:12:31
마틴에게도 같은 일이 발생합니다. 독일은 미국과 같지 않습니다.
same thing for martin germany is not equal to usa
2:12:34
이 SQL은 이 고객도 제거할 것입니다. 마지막 고객에게 가겠습니다.
isquels gonna remove this customer as well and to the last one
2:12:38
피터, 이제 값이 미국이라는 것을 알 수 있습니다. 미국은 미국과 같습니다.
peter you can see the value is usa so usa equal usa
2:12:41
조건이 충족되면 이스퀼스는 이에 대해 기쁘게 생각합니다.
the condition is fulfilled isquels is happy about it and
2:12:44
고객을 출력에 남겨두고 이제 이 조건을 적용하면 됩니다.
gonna leave the customer in the output so now if you go and apply this condition
2:12:48
비교 연산자를 데이터에 사용하면 두 개만 있습니다.
using the comparison operator to your data only two
2:12:51
고객이 외부에 남게 되며, 이것이 정확히 어떻게 작동하는지입니다.
customers gonna be left in the outwards this is exactly how
2:12:54
조건과 비교 연산자가 SQL에서 작동하는 방식입니다.
the conditions and the comparison operators works in sql
2:12:58
좋습니다. 이제 첫 번째 연산자를 시작해 보겠습니다. 매우 간단합니다.
okay so now let's start with the first operator it's very simple we
2:13:01
같은 값을 확인하는 연산자가 있습니다.
have the equal it's gonna checks if the two values are
2:13:04
예를 들어 보겠습니다. 이제 이 작업이 있습니다. 독일의 모든 고객을 검색하라고 합니다.
equal that's very simple let's have an example okay so now we have this task it says retrieve all customers from germany so this is very basic
2:13:11
우리는 선택할 것이고, 모든 열을 선택할 것입니다. 테이블 고객에서
we're gonna go and select and we're gonna select all the columns since we don't
2:13:14
어떤 사양도 없기 때문에
have any specifications from the table customers and
2:13:17
실행하면 모든 고객이 표시되지만 우리는 그게 필요하지 않습니다.
if you go and execute it you will get all the customers but we don't need that
2:13:21
독일에서 오는 고객만 필요합니다. 그래서 우리는
only the customers that comes from germany so we have to go
2:13:24
조건을 적용해야 합니다. where 절을 사용하여 국가를
and apply a condition using the where clause country
2:13:27
독일의 값과 같게 설정합니다. 정확히 데이터베이스와 같이 작성해야 합니다.
equal to the value germany so make
2:13:30
그렇지 않으면 작동하지 않습니다. 그래서 실행해 보겠습니다. 그렇게 하면
sure you are writing it exactly like in the database otherwise it will not work so let's go and execute and with that we are getting only
2:13:37
독일의 고객만 가져옵니다. 매우 간단합니다. 이것이
the customers from germany so it is very simple and this is
2:13:40
우리가 같은 연산자를 사용하는 이유입니다. 이제 다음으로 넘어갑니다.
why we use the equal operator okay so now moving on
2:13:43
다시 매우 간단합니다. 두 값이 같지 않은지 확인하려면
to the next one again very simple if you want to check if
2:13:46
같지 않음을 사용할 수 있습니다. 예를 들어 보겠습니다.
two values are not equal we can use the not equal
2:13:50
반대 작업이 있습니다. 모든 고객을 검색하라고 합니다.
operator so let's have an example okay so now we let's have the
2:13:53
독일에서 오지 않는 고객입니다. 매우 간단합니다. 우리는 여기서
opposite task it says retrieve all customers who
2:13:56
그들이 독일과 같지 않다고 말하고 있습니다. 그래서 같지 않음을 사용하여
are not from germany so this is very simple we are saying here who are not they are not equal to germany so we can use the not equal operator in order to get
2:14:07
이 고객들을 얻을 수 있습니다. 실행 후 보시다시피
these customers so with that as you can see after executing we
2:14:11
모든 고객이 국가가 같지 않은 것을 얻고 있습니다.
are getting all the customers country is not equal to
2:14:14
독일과 같지 않은 고객을 얻고 있으며, 같지 않음을 수행하는 또 다른 방법이 있습니다.
germany and there is like another way on how to do the not equal
2:14:17
이렇게 하면 같은 결과를 얻을 수 있습니다, 친구들.
doing it like this we'll get the same results all right my friends
2:14:20
다음으로 넘어가서 값이
moving on to the next one we can check if a value is
2:14:23
다른 값보다 큰지 확인해 보겠습니다. 그래서 우리는 큰 연산자를 사용합니다. 예를 들어 보겠습니다. 자, 다음 작업은 점수가 500보다 큰 모든 고객을 검색하라고 합니다.
greater than another value so we use the greater operator let's have an example okay so now the next task it says retrieve all customers with a score greater than 500.
2:14:35
이제 우리는 점수를 기준으로 데이터를 필터링하고자 합니다, 그래서 우리는
now we want to filter the data based on the score so we're gonna
2:14:38
점수를 말하고 이제 작업이 말합니다.
say where score and now the task says
2:14:41
500보다 큰 경우 연산자 500보다 큰 것을 사용할 것입니다. 매우 간단합니다. 그래서 이를 통해 점수가 500보다 높은 고객만 얻을 수 있습니다.
greater than 500 we're gonna use the operator greater than 500 it's very simple so with that we will get only the customers where the score is higher than 500.
2:14:53
예를 들어 마리아는 조건을 충족하지 않습니다. 피터와 마틴도 마찬가지입니다. 500보다 커야 합니다.
so for example maria it's not fulfilling the condition the same thing for the peter and as well for martin it must be greater than 500.
2:15:01
그래서 실행하면 500보다 큰 두 고객만 얻을 수 있습니다.
So if you go and execute it, you will get only those two customers because they are greater than 500.
2:15:08
좋습니다, 다음으로 넘어갑니다. 이번에는 값이 다른 값보다 크거나 같은지 확인할 것입니다.
Okay, moving on to the next one. This time, we're going to check if a value is greater than or equal to another value.
2:15:14
그래서 이는 크다와 같다의 혼합과 같습니다. 둘 중 하나가 충족되면 값이 조건을 충족하게 됩니다.
So it is like mix between the greater than and the equal. If one of them is fulfilled, then the value going to meet the condition.
2:15:20
그에 대한 예를 들어 보겠습니다. 이제 작업이 검색하라고 말하면
So let's have an example for that. Now, if the task says retrieve
2:15:23
점수가 500 이상인 모든 고객을 포함할 것입니다. 이번에는 점수가 500과 같거나 더 높은 고객도 포함할 것입니다.
all customers with a score of 500 or more, this time we're going to go and include the customers where their score is equal as well to 500 or higher.
2:15:33
그래서 점수와 500 값에 기반한 유사한 조건을 가질 것입니다.
So we're going to have a similar condition based on the score and the 500 value.
2:15:37
이번에는 500보다 크거나 같다고 말할 것입니다.
This time we're going to say greater or equal to 500.
2:15:41
그래서 지금 가서 실행하면 이번에는 점수가 500인 고객 마틴을 볼 수 있습니다.
So if you go now and execute it, this time we're going to see the customer Martin with the score of 500.
2:15:47
이 시나리오에서는 크거나 같음을 사용할 것입니다.
So on this scenario, we're going to use greater or equal.
2:15:51
좋습니다, 이제 계속 진행합시다. 다음은 매우 간단합니다.
all right so now let's keep moving the next one is as well very simple we're
2:15:54
이번에는 값이 다른 값보다 작은지 확인할 것입니다.
gonna check this time if a value is less than another
2:15:57
값이므로 우리는 작다 연산자를 사용할 것입니다. 이제 예를 들어 보겠습니다.
value so we're gonna use the less operator let's have an
2:16:01
이제 다른 간단한 작업으로 넘어갑니다. 점수가 500보다 낮은 모든 고객을 검색합니다.
example now moving on to another simple task retrieve all
2:16:04
이번에는 점수가 낮은 모든 고객을 원합니다.
customers with a score less than 500 so
2:16:07
정확히 반대의 경우를 사용할 것입니다. 점수가 500보다 낮고 다시 여기서 같지 않습니다.
this time we want all the customers with a lower score and
2:16:10
그래서 가서 실행하면 점수가 낮은 모든 고객을 얻을 수 있지만
we're gonna use exactly the opposite it's gonna be the score is less than 500 and again here it is not equal right so if you go and execute you
2:16:18
마틴은 500과 같기 때문에 얻지 못할 것입니다.
will get all the customers with a low scores but you will not
2:16:21
마틴은 500과 같기 때문에.
get martin because martin is equal to 500 so
2:16:24
그것으로 우리는 작업을 해결했습니다. 우리는 점수가 있는 모든 고객을 가지고 있습니다.
with that we have solved the task we have all the customers with the score
2:16:27
500 미만의 고객을 이제 넘어가겠습니다.
less than 500 okay my friends now moving on to the
2:16:31
마지막 하나입니다. 당신은 이미 알았을 것 같고, 우리는 확인할 것입니다.
last one i think you already got it so we're gonna check whether a
2:16:34
값이 다른 값보다 작거나 같은지 확인할 것입니다.
value is less than or equal to another
2:16:37
값이 다른 값보다 작거나 같으므로, 우리는 작음 연산자를 결합할 수 있습니다.
value so you can go and combine the less operator together with the equal and if one of them is fulfilled then the value gonna meet the condition So let's have an example for that.
2:16:46
이번에는 점수가 500 이하인 모든 고객을 검색하고 있습니다. 쿼리는 매우 유사할 것입니다.
This time we are retrieving all customers with a score of 500 or less. So the query is going to be very similar.
2:16:53
하지만 우리는 500 이하라고 말하고 있습니다. 그래서 우리는 조건에 값을 포함하고 있습니다.
But we are saying it is less or equal to 500. So we are including the value in our condition.
2:17:00
그것으로 우리는 여전히 점수가 500 미만인 두 고객을 가지고 있습니다.
And with that, as you can see, we still have our two customers where we have the score less than 500.
2:17:05
하지만 이제 점수가 500인 마틴도 있습니다. 알겠죠, 친구들?
But we have now as well Martin with a score of 500. Okay, my friends.
2:17:10
그것으로 우리는 첫 번째 그룹, 비교 연산자를 다루었습니다. 이제 다음 그룹으로 넘어가겠습니다.
So with that, we have covered the first group, the comparison operators. Now we can move on to the next group. We're going to speak about the logical operators.
2:17:17
여기에는 세 가지가 있습니다. AND 또는 NOT. 첫 번째부터 시작해 보겠습니다.
And here we have three. AND or NOT. So let's start with the first one. What is exactly AND operator?
2:17:27
AND의 정의는 무엇인가요? 모든 조건이 참이어야 한다고 합니다.
Okay, so now what is the definition of the AND? It says all conditions must be true.
2:17:32
WHERE 절에 있는 모든 조건이 참이어야 결과에 행을 유지할 수 있습니다.
So all the conditions that you have in the WHERE clause must be true in order to keep the row in the results. So let's understand what this means.
2:17:40
상황이 더 복잡해질 수 있으며, 여러 조건을 가질 수 있습니다.
things can get more complicated where you can have not only
2:17:43
여기에서 두 번째 조건을 추가할 수 있습니다.
one condition but you might have multiple conditions in
2:17:46
우리는 단순히 국가가 미국과 같아야 한다고 말할 것입니다.
your query so here we can add a second condition where
2:17:49
또한 점수가 500보다 높아야 한다고 말할 것입니다.
we're gonna say not only the country must be equal to usa
2:17:52
이제 두 가지 조건이 있으며, 이를 넣어야 합니다.
but also the score must be higher than 500
2:17:55
WHERE 절에 넣어야 하며, 이러한 조건을 결합해야 합니다.
so now you have two conditions and you have to put
2:17:58
논리 연산자를 사용하여 조건을 결합해야 합니다.
them in the where clause now you have to combine those conditions using
2:18:02
여기에는 두 가지 옵션, 두 개의 연산자가 있습니다.
the logical operator and here we have two options two operators the and operator and the
2:18:08
AND 연산자와 OR 연산자입니다.
or operator in this scenario if you say and then
2:18:11
이 시나리오에서 AND를 사용하면 SQL은 매우 제한적입니다.
sql is very restrictive both of the conditions must
2:18:14
두 조건 모두 참이어야 결과에 행을 유지할 수 있습니다.
be true in order to keep the row in the results
2:18:17
이제 첫 번째 행과 첫 번째 조건이 어떻게 작동하는지 봅시다.
so now let's see how this is gonna work now for the first row and for
2:18:20
첫 번째 조건은 독일이고
the first condition you can see the country is germany and it
2:18:23
첫 번째 조건을 충족하지 않으므로
is not fulfilling the first condition so this
2:18:27
거짓이 될 것이고, 첫 번째 조건의 두 번째를 확인하면
is gonna be false and as well if you check the second condition for the first
2:18:30
점수가 350이므로
row you can see the score is 350 so that means this
2:18:33
이 고객은 두 번째 조건조차 충족하지 않습니다.
customer is as well not fulfilling even the second condition
2:18:36
두 조건 모두 거짓이므로 이 고객을 결과에서 제거합니다.
so both of the conditions is false and it's going to go i remove
2:18:40
이 고객을 결과에서 제거한 후 다음은 존입니다.
this customer from the results now to the next one john you
2:18:43
존은 첫 번째 조건을 충족하고
can see john is fulfilling the first condition because the country
2:18:46
두 번째 조건도 충족합니다. 그의 점수는 900이고 500보다 높습니다.
is equal to usa and as well fulfilling the second
2:18:49
이스라엘은 두 조건이 모두 참이므로 매우 기쁠 것입니다.
condition his score is 900 and this is higher than 500
2:18:53
그래서 존은 결과에 남게 됩니다. 이제 조지로 넘어갑니다.
so now israel gonna be very happy about it because both of them is true and this is the only way in order to keep the row in the output because we are using the operator AND.
2:19:02
그는 첫 번째 조건을 충족하지 않지만 두 번째 조건은 충족됩니다.
So, John is going to stay in the output. Now, moving on to George. He is not fulfilling the first condition. But now, the second condition is fulfilled.
2:19:10
그의 점수는 750이고 500보다 높습니다. 그래서 지금은 50-50입니다.
His score is 750, and this is higher than 500. So, now, it's like 50-50, right?
2:19:15
한쪽은 거짓이고 다른 쪽은 참입니다. 하지만 이는 AND 연산자에 충분하지 않습니다.
In one side, it's false, but the other side is true. But this is not enough for the AND operator.
2:19:20
두 조건 모두 참이어야 결과를 유지할 수 있습니다.
Both of them should be true in order to keep the result in the output. That's why SQL is going to remove this true. Now, moving on to Martin.
2:19:26
그는 두 조건 모두를 충족하지 않으므로 SQL은 이를 제거합니다.
He is not fulfilling both of the conditions. So, SQL is going to go and remove it from the
2:19:30
결과에서 마지막으로 피터가 첫 번째 조건을 충족합니다.
results and now for the last one Peter is fulfilling the
2:19:34
국가는 미국과 같지만 두 번째 조건은 충족되지 않습니다.
first condition the country is equal to USA but the second
2:19:37
조건이 충족되지 않아 점수가 0입니다.
condition is sadly not fulfilled so we have the score zero
2:19:40
500보다 높지 않으며, 같은 시나리오입니다.
not higher than 500 again we have the same scenario it's
2:19:43
50-50이고 이는 AND 연산자에 충분하지 않습니다.
50 50 and this is not enough for the and operator that's
2:19:47
그래서 SQL은 이를 제거합니다. 조건이 충족되지 않으면 많은 행이 제거됩니다.
why SQL gonna go I remove it so as you can see if you use
2:19:50
AND 연산자는 매우 제한적이며 두 조건 모두 충족되어야 합니다.
an and operator a lot of rows gonna be removed if one of the condition is not met so the and operator is very restrictive both of the conditions must be fulfilled
2:20:00
결과에서 행을 유지하려면. 이게 바로 AND 연산자의 작동 방식입니다.
to keep the row in the results. So this is exactly how the end operator works. Okay, so now we have the following task.
2:20:06
미국 출신이고 점수가 500보다 큰 모든 고객을 검색합니다.
Retrieve all customers who are from USA and have a score greater than 500.
2:20:12
그래서 우리는 여러 조건을 결합하고 단계별로 진행할 것입니다. 첫 번째로, 올바른 테이블에서 데이터를 선택해야 합니다.
So here we are like combining multiple conditions and let's go and do it step by step. So the first thing is that we have to go and select the data from the correct table.
2:20:19
그래서 고객 테이블에서 모든 고객을 선택하고 있습니다.
So select star from customers and with that we are getting all the customers from the table.
2:20:24
이제 첫 번째 조건은 미국에서 온 고객이 필요합니다.
Now the first condition we need the customers that come from USA.
2:20:28
그래서 우리는 그 두 고객만 필요하고 이를 위해
So we need only those two customers and in order to do that
2:20:31
국가가 미국과 같아야 합니다.
as we learned we can go and use the where clause and the condition going
2:20:34
실행하면 그 두 고객을 얻을 수 있습니다. 아무것도
to be country equal to usa so
2:20:38
새로운 압축 연산자 '='를 사용했지만
if you go and execute we will get those two customers nothing is
2:20:41
아직 끝나지 않았습니다. 그 두 고객에 대한 또 다른 조건이 있습니다.
new we have used the compression operator equal but we
2:20:44
고객의 점수가 필요한 고객만 필요합니다.
are not done yet we have another condition from those two
2:20:48
500보다 높은 점수를 가져야 하므로, 그 두 고객을 보면
customers we need only the customers where their score is
2:20:51
더 나은 고객은 500보다 높은 점수를 가지고 있지 않습니다.
higher than 500 so now by looking to those two customers you can see we see that the better here does not have a score higher
2:20:58
그래서 우리는 결과에서 그것을 보고 싶지 않습니다.
than 500 and we don't want to see that in the results
2:21:01
그래서 이제 해야 할 일은 조건을 작성하는 것입니다.
so now what you have to do we have to go and write a condition for
2:21:04
여기서 이 조건은 점수를 기준으로 합니다.
this one over here so this is based this time on the scores
2:21:07
국가가 아니라 점수가 500보다 커야 합니다.
not on the country so the score should be greater
2:21:11
이제 첫 번째 조건을 확인할 수 있습니다.
than 500 now as you can see we have the first
2:21:14
첫 번째 조건과 두 번째 조건을 연결하는 방법에 대한 질문입니다.
condition for the first one here and the second condition
2:21:17
여기에는 두 가지 옵션이 있습니다. 그리고 솔직히 말하면, 매우
for the second requirement now the question how to connect those two conditions so here we have two options and or and to be honest this is very
2:21:26
간단합니다. 고객은 두 조건을 모두 충족해야 합니다.
simple the task says it customer should fulfill both
2:21:29
조건은 미국에서 와야 하며 동시에
of the conditions should be from usa and as well at
2:21:32
500보다 커야 합니다.
the same time greater than 500 so it
2:21:35
매우 간단합니다. 그래서 우리는 연결했습니다.
is very simple we're gonna say and so with that we have connected
2:21:38
두 조건을 모두 충족하는 고객을 얻을 수 있습니다.
both of those conditions and if you go and query it you
2:21:41
모든 고객 중에서 한 명의 고객만 있습니다.
will get only one customer that is fulfilling our
2:21:44
미국에서 온 고객이며 동시에 이 고객의 점수가 500보다 높습니다.
conditions so from all customers we have only one customer
2:21:47
미국에서 온 고객이 이 조건을 충족하며, 이 고객의 점수가 500 이상입니다. 이렇게 두 조건을 연결하기 위해 AND 연산자를 사용합니다.
that's fulfilled this condition that comes from usa and at the same time the score of this customer is higher than 500 So this is how we use the AND operator in order to connect two conditions.
2:22:00
좋아요, 친구들. 그래서 AND 연산자는 여기까지입니다. 이제 OR 연산자에 대해 이야기해봅시다.
Okay, my friends. So that's all for the AND operator. Let's speak now about the OR operator.
2:22:09
좋아요. 이제 OR 연산자는 최소한 하나의 조건이 참이어야 한다고 말합니다. 그래서 AND보다 덜 제한적입니다.
All right. Now the OR operator, it says at least one condition must be true. So it is less restrictive than the AND.
2:22:16
결과에 행을 유지하기 위해서는 하나의 조건만 참이면 충분합니다. 이것이 정확히 무엇을 의미하는지 이해해봅시다. 알겠죠.
It is enough to have one condition true in order to keep the row in the results. Let's understand exactly what this means. Okay.
2:22:22
이제 같은 시나리오가 있습니다. 두 가지 조건이 있고
So now we have the same scenario. we have two conditions and
2:22:25
SQL에서는 AND를 사용하거나
in SQL you have to connect them either using the and
2:22:28
연산자 또는 이 시나리오에서 OR 연산자를 사용해야 합니다.
operator or the or operator in this scenario
2:22:31
우리는 OR 연산자에 대해 이야기할 것입니다. 그리고 우리가 말했듯이
we're going to talk about the or operator and as we said at
2:22:35
최소한 하나의 조건이 충족되어야 결과에 남겨집니다. 그러니 무슨 일이 일어날지 봅시다.
least one of the conditions must be fulfilled in order to
2:22:38
최소한 하나의 조건이 충족되어야 결과에 남겨집니다. 그러니 무슨 일이 일어날지 봅시다.
leave the record in the results so let's see what's going to happen
2:22:41
여기 첫 번째 고객 마리아가 있습니다. 그녀는 조건을 충족하지 않습니다.
here now the first customer Maria she is not
2:22:44
첫 번째 조건과 두 번째 조건 모두 충족하지 않으므로 둘 다 거짓입니다. 이것이 SQL이 결과에서 레코드를 제거하는 유일한 시나리오입니다. 최소 요구 사항을 충족하지 않기 때문입니다.
fulfilling the first condition and as well the second condition so both of them is false and this is the only scenario where SQL gonna remove the record from the results because it is not fulfilling the minimum.
2:22:56
최소한 하나는 참이어야 합니다. 둘 다 거짓입니다. 그러면 SQL은 이 행을 제거합니다. 이제 다음 고객인 존으로 넘어갑니다.
At least one of them should be true. Both of them is false. Then SQL gonna go I remove this row. Now moving on to the next one to John.
2:23:02
존은 미국 출신이며 점수가 500보다 높습니다. 두 조건 모두 충족됩니다. 그래서 둘 다 참입니다.
John is from USA and has higher score than 500. Both of the conditions is green. So both of them is true.
2:23:10
이것은 출력을 유지하기에 충분합니다. 그래서 우리는 출력에서 존을 볼 것입니다. 이제 세 번째 고객인 조지로 넘어갑니다.
And this is more than enough to keep the row in the output. That's why we will see John in the output. Now moving on to the third one George.
2:23:17
조지는 첫 번째 조건을 충족하지 않습니다. 왜냐하면 영국은 미국과 같지 않기 때문입니다.
George is not fulfilling the first condition because UK is not equal to USA.
2:23:21
하지만 이번에는 존이 두 번째 조건을 충족하고 있습니다. 그래서 여기 참이 있습니다.
But John this time is fulfilling the second condition. So we have here true.
2:23:26
그리고 최소한 하나가 참이므로 이 레코드를 출력에 유지하기에 충분합니다. 그래서 결과에서 조지를 볼 수 있습니다.
And since we have at least one true, this is good enough to keep the record in the output. So you will see George in the results.
2:23:33
이제 마틴으로 넘어갑니다. 그는 첫 번째 조건을 충족하지 않으며 두 번째 조건도 충족하지 않습니다. 둘 다 거짓입니다.
Now moving on to Martin. He is not fulfilling the first condition as well not fulfilling the second condition. Both of them is false.
2:23:40
이것은 출력을 유지하기에 충분하지 않습니다. 그래서 여전히 제거될 것입니다. 이제 마지막 고객인 피터로 넘어갑니다.
And this is not enough to keep the result in the output. So that's why it's still going to go and remove it. Now moving on to the last one Peter.
2:23:47
그는 첫 번째 조건을 충족하지만 두 번째 조건은 충족하지 않습니다.
He is fulfilling the first condition but not the second condition.
2:23:50
하지만 여전히 모든 것이 괜찮습니다. 왜냐하면 그는 최소한 하나의 조건을 충족하고 있기 때문입니다. 그래서 최소 요구 사항을 충족하고 SQL은 출력을 유지합니다.
But still everything is fine because he is fulfilling at least one condition. So we have the minimum and SQL gonna leave it in the output.
2:23:58
보시다시피 OR 연산자는 AND 연산자처럼 제한적이지 않습니다. 출력을 유지하기 위해 하나의 참만 있으면 충분합니다.
So as you can see the OR operator is not restrictive like the AND operator. It's enough to have one true in order to keep the data in the output.
2:24:05
이것이 바로 OR 연산자가 작동하는 방식입니다. 이제 두 번째 작업을 살펴보겠습니다.
And this is exactly how the OR operator works. Now let's see the second task.
2:24:09
미국 출신이거나 점수가 500보다 큰 모든 고객을 검색합니다.
Retrieve all customers who are either from USA or have a score greater than 500.
2:24:15
그래서 매우 유사한 작업입니다. 두 가지 조건이 있습니다. 그래서 우리는 미국에서 온 고객이 필요합니다.
So it is a very similar task. We have two conditions. So we need the customers that are either from USA.
2:24:21
그래서 이 조건은 미국과 같아야 합니다. 두 번째 조건은 점수가 500보다 커야 합니다.
So it is based on this country equal to USA. And the second condition is the score is greater than 500.
2:24:28
하지만 이번에는 매우 느슨합니다. 이 조건이 충족되거나 두 번째 조건이 충족됩니다.
But this time we are very relaxed. Either this condition is fulfilled or the second one.
2:24:33
그래서 and 대신 or 연산자를 사용할 것입니다. 그래서 이 조건 중 하나만 충족하면 충분합니다.
So instead of having and, we will be using the operator or. So it is enough to fulfill one of those conditions.
2:24:39
그리고 실행하면, 이제 보시다시피 더 많은 결과를 얻고 있습니다. 조건을 충족하기가 더 쉽기 때문입니다.
And if we go and execute, now as you can see, we are getting more results. because it is easier to fulfill the conditions.
2:24:45
그래서 우리는 세 명의 고객이 첫 번째 조건이나 두 번째 조건을 충족하는 것을 볼 수 있습니다.
So we can see those three customers either fulfilling the first condition or the second one.
2:24:50
좋아요, 친구들, 그래서 OR 연산자는 여기까지입니다. 이제 이 그룹의 마지막인 NAT로 넘어가겠습니다.
All right, my friends, so that's all for the OR operator. And we're going to move to the last one in this group, the NAT.
2:24:55
그렇다면 not 연산자는 무엇을 의미합니까?
So what do we mean with the not operator okay
2:25:02
그래서 이제 이 not 연산자는 무엇입니까? 이것은 반대 연산자로, 일치하는 값을 제외할 것입니다. 그러면 이것이 정확히 무엇을 의미하는지 간단한 예를 들어보겠습니다.
so now what is this operator not it is a reverse operator it's gonna go and exclude the matching values so what this exactly means let's have a very simple example all right so now
2:25:13
not 연산자는 or 및 and와 다릅니다.
the not operator is not like the or and and
2:25:17
이 연산자는 두 조건을 결합하지 않으므로 하나의 조건과만 사용할 수 있습니다. 현재 조건이 이렇다고 가정해 보겠습니다.
this operator will not go and combine two conditions so you can use it with only one condition and let's say that our current condition is like this
2:25:24
국가는 미국과 같아야 하므로 이것은 비교입니다.
the country must be equal to usa so this is like a comparison
2:25:28
연산자를 데이터에 적용하면, 우리가 배운 대로 두 고객인 존과 피터만 남게 됩니다.
operator and if you apply it to your data as we learned it's gonna
2:25:31
조건을 충족하기 때문에 두 고객인 존과 피터만 남게 됩니다.
leave only two customers john and peter because they fulfill the
2:25:34
모든 다른 고객은 제거됩니다. 그러므로 지금까지는 별로 놀라운 일이 아닙니다.
conditions and all other customers will be removed because
2:25:37
그들이 그 조건을 충족하지 않기 때문에 지금까지는 별로 놀라운 일이 아닙니다.
they don't fulfill that condition so nothing crazy so far but
2:25:40
이제 조건에 not 연산자를 적용하면 어떻게 될까요?
now if you go and apply the not operator to the condition
2:25:44
무엇이 발생할 수 있는지, 전체 진리를 반전시킬 것입니다.
what can happen you're gonna reverse the whole truth
2:25:47
그래서 이 조건이 충족되면 제거되어야 한다고 말하는 것입니다.
so you are saying if this condition is fulfilled it
2:25:50
최종 결과에서 제거되어야 하므로 모든 것을 전환하는 것입니다.
must be removed from the final results so it is
2:25:53
조건을 충족하지 않는 고객을 보고 싶습니다.
switching everything we want to see the customers that
2:25:56
이제 not 연산자를 함께 적용하면 어떤 일이 발생할 수 있는지 봅시다.
is not fulfilling the condition so now let's
2:25:59
조건을 적용하면 첫 번째 고객이 조건을 충족하지 않는 것을 볼 수 있습니다.
see what can happen if you apply the not operator together with
2:26:02
조건을 충족하지 않는 첫 번째 고객을 볼 수 있습니다. 이는 훌륭한 일입니다.
the condition we can see that the first customer is not fulfilling the
2:26:05
우리가 원하는 것은 조건을 충족하지 않는 고객입니다. 그래서 이스라엘은 이에 대해 기뻐할 것이고, 이를 실현하고 남겨둘 것입니다.
condition which is great thing this is exactly what we
2:26:08
우리는 조건을 충족하지 않는 고객을 원합니다. 그래서 이스라엘은 이에 대해 기뻐할 것이고 이를 실현할 것입니다.
want we want a customer that is not fulfilling the condition that's why israel gonna be happy about it and israel gonna make it true and leave it in
2:26:16
마리아는 전체를 충족하고 있습니다.
the output so maria is fulfilling the whole thing she
2:26:19
조건을 충족하지 않고 있으므로 이스라엘은 이를 남겨둘 것입니다.
is not meeting the condition so israel gonna leave it at
2:26:22
다음 항목을 위해 출력이 준비되었습니다. 이 고객은 조건을 충족하고 있습니다.
the output now for the next one so this customer is fulfilling
2:26:25
조건을 충족하고 있지 않으므로 이스라엘은
the condition and that is not a good thing so israel gonna
2:26:28
결과에서 존을 제거할 것입니다.
go and this time remove john from the results because
2:26:32
그는 조건을 충족하고 있으며 조지로 넘어갑니다.
he is fulfilling the condition and moving on to george so
2:26:35
조지는 조건을 충족하지 않는데, 이는 놀라운 일입니다.
george is not fulfilling the condition which is amazing so that's why israel gonna keep this time george in the output the same thing for martin
2:26:43
마틴은 그 조건을 충족하지 않으므로 고객을 유지할 것입니다.
martin is not fulfilling that condition so it's gonna keep the customer and better he is fulfilling
2:26:49
조건을 충족하므로 이 고객을 제거할 것입니다.
the condition so it's gonna go and remove this customer from
2:26:52
출력에서 모든 것을 뒤집었습니다.
the output so as you can see we have reversed everything right
2:26:55
not 연산자는 true를 false로 만듭니다.
the not operator gonna make the true false and
2:26:58
false를 true로 만듭니다. 이제 SQL로 돌아가서 연습해봅시다.
the false true okay so this is how it works now let's go
2:27:01
500점 이상인 모든 고객을 검색하라고 합니다.
back to sql in order to practice okay the next task
2:27:04
이제 이 조건을 기반으로 데이터를 필터링해야 합니다.
it says retrieve all customers with a score not less than 500 so this sounds really funny as usual we're Let me go and select star from customers.
2:27:16
점수가 500 이상이라고 말할 수 있습니다.
And now we have to filter the data based on this condition. So the score is not less than 500.
2:27:22
그렇다면 점수는 500 이상입니다.
Well, you can go and say, well, the score is higher, greater or equal to 500, right?
2:27:28
500 이상인 모든 고객을 얻습니다.
And with that, it is not less than 500. So if you go and execute it, we just solve the task, right?
2:27:33
NAT 연산자를 사용하여 더 재미있게 만들 수 있습니다.
We get all the customers that are not less than 500.
2:27:36
여기에서 'not'이라고 말하고 전환합니다.
Or you can go and use the NAT operator to make things more funnier.
2:27:40
점수가 500 미만입니다. 그러나 'not'을 사용하므로 모든 것이 뒤집혔습니다.
So you go over here and say it is not and then you switch it. So you make like this.
2:27:46
점수가 500 미만이 아니라고 말하고 있습니다.
So the score is less than 500. But as we use here not, then we twisted everything.
2:27:52
진리를 변환합니다. 제거하고 실행하면 500 미만인 모든 것을 얻습니다.
So we are saying the score is not less than 500. And if you execute it, you will get the exact same results.
2:27:58
그러나 nuts를 넣으면 전체 논리가 변환됩니다.
Convert the truth. If you remove it and execute, you will get everything that is less than 500.
2:28:04
이것은 정말 멋집니다. NAT 연산자를 사용하는 방법입니다.
But if you put the nuts, you will convert the whole logic. So if you go and execute, you are not getting the scores that are less than 500.
2:28:12
그래서 이것은 정말 좋습니다. 이것이 NAT 연산자를 사용하는 방법입니다. 자, 친구들. 그래서 이를 통해 우리는 논리 연산자에 대한 모든 것을 다뤘습니다.
So this is really nice. This is how we use the NAT operator. Okay, my friends. So with that, we have covered everything about the logical operators.
2:28:19
이제 우리는 세 번째 그룹으로 이동할 것입니다. 범위 연산자에 대해 이야기할 것입니다. 여기에는 하나만 있습니다, 바로 between입니다.
Now we're going to move to the third group. We're going to talk about the range operator. And here we have only one, the between.
2:28:25
between 연산자는 정확히 무엇인가요? 자, between이란 무엇인가요?
So what is exactly between operator? Okay, so what is between?
2:28:32
값이 특정 범위 내에 있는지 확인할 것입니다.
It's going to go and check if a value falls within a specific range.
2:28:36
범위가 있고 값이 그 범위 내에 있는지 또는 범위 외에 있는지를 확인하고 있습니다. 그러니 이것이 정확히 무엇을 의미하는지 이해해 봅시다.
So you have a range and you are checking whether your value is in the range or outside the range. So let's understand exactly what this means.
2:28:43
범위를 만들기 위해서는 두 가지가 필요합니다.
Okay, so now in order to build a range, you need two things.
2:28:47
범위를 위한 하한선과 상한선이 필요합니다.
You need the lower boundary for the range and you need as well the upper boundary.
2:28:52
두 개의 경계가 있으면 범위가 생깁니다. 그리고 그 두 경계 사이의 모든 것은 참이 되고, 그 경계 밖의 모든 것은 거짓이 됩니다.
Once you have two boundaries, then you have a range. And everything between those two boundaries is going to be true and everything outside those boundaries is going to be false.
2:29:02
예를 들어, 하한선이 100이고 상한선이 500이라고 가정해 봅시다.
So now for example, let's say that we have the lower boundary 100 and the upper boundary 500.
2:29:07
between에 대해 이해해야 할 한 가지가 있습니다. 경계는 포함됩니다.
And there is one thing that you have to understand about the between. The boundaries are inclusive.
2:29:12
즉, 값이 정확히 100이거나 정확히 500이면 참으로 간주됩니다.
So that means if a value is exactly 100 or exactly 500, then it's going to be considered as true.
2:29:18
따라서 범위 내에 있는 것으로 간주됩니다. 이제 이 필터를 데이터에 적용하면, 점수가 100과 500 사이여야 한다고 말합니다.
So it is considered to be inside the range. Now, if you apply this filter to our data, where we say the score must be between 100 and 500,
2:29:27
SQL은 다음과 같은 작업을 수행할 것입니다. 첫 번째 고객인 마리아의 점수가 경계 내에 있는지 확인할 것입니다.
SQL is going to go and do the following. So for the first customer, Maria, SQL is going to go and check whether her score is inside the boundaries.
2:29:35
보시다시피, 300은 100과 500 사이에 있습니다. 그래서 그녀는 녹색 영역에 있습니다.
So as you can see, 300 is between 100 and 500. So she is in the green area.
2:29:40
그래서 SQL은 이에 대해 기뻐하고 고객을 외부에 남겨둘 것입니다. 이제 존으로 넘어갑니다. 존은 900입니다.
And that's why SQL is going to be happy about it and leave the customer in the outwards. Now moving on to John. John has 900.
2:29:46
보시다시피, 900은 500보다 큽니다. 그래서 이 값은 오른쪽 경계 밖에 있게 됩니다.
As you can see, 900 is greater than 500. So this value is going to be outside the boundaries on the right side.
2:29:52
그리고 이것은 존의 점수가 범위에 없다는 것을 의미합니다. 그래서 그는 조건을 충족하지 않습니다.
And this means the score of John is not in the range. That's why he is not fulfilling the condition.
2:29:57
SQL은 이 고객을 제거할 것입니다.
and SQL gonna go and remove this customer from the
2:30:00
결과에서 조지 750으로 넘어갑니다. 같은
results now moving on to george 750 the same
2:30:03
범위 밖의 것들은 SQL이 수용하지 않으며 제거할 것입니다.
thing outside the range skill will not accept it and remove
2:30:07
이 고객을 최종 결과에서 제거하고 이제 마틴으로 넘어갑니다.
this customer from the final results now moving on to martin his
2:30:10
점수는 500이며, 이는 정확히 경계에 있습니다.
score is 500 and this is exactly at
2:30:13
그래서 만약 501이라면 범위 밖이 될 것입니다.
the boundary so if it's like 501 it's gonna be outside so
2:30:17
between이 포함되므로 SQL은 이를 수용할 것입니다.
since between is inclusive then sql gonna
2:30:20
마틴은 범위 내에 있으며 조건을 충족하는 것으로 간주됩니다.
accept it and martin considered to be in the range and fulfilling
2:30:23
조건을 충족하므로 이스키엘이 그를 최종 결과에 포함시킬까요?
the condition so isquiel gonna keep him in the final results now we
2:30:27
그는 점수가 0이고 이것은 100보다 적습니다.
are speaking about better he has zero score and this
2:30:30
범위에 포함되지 않으므로 조건을 충족하지 않으며 이스키엘이 제거할 것입니다.
is less than 100 so in the left side not in
2:30:33
그를 제거할 것입니다. 이것이 이스키엘에서 작동하는 방식입니다.
the range so not fulfilling the condition and isquiel gonna go and remove
2:30:36
그는 이스키엘에서 어떻게 작동하는지 정확히 보여줍니다.
him this is exactly how between works in isquiel it's
2:30:39
매우 간단합니다. 자, 이제 다음 작업이 있습니다. 고객의 점수가 100과 500 사이에 있는 모든 고객을 검색하라고 합니다. 그러니 평소처럼 모든 데이터를 선택하는 것부터 시작합시다.
very simple okay so now we have the following task and it says retrieve all customers whose score falls in range between 100 and 500 so let's start as usual by selecting all data
2:30:51
고객 테이블에서 데이터를 가져오고 실행합니다. 이제 작업이 시작됩니다.
from customers and execute it now the task
2:30:54
모든 고객이 범위에 있어야 한다고 합니다.
says everything we need all customers in a range so
2:30:57
우리는 하한값과 상한값이 있습니다. 그래서
we have a lower value and a higher value so in
2:31:00
그것을 수행하기 위해 평소처럼 where를 사용할 것입니다. 그리고 나서
order to do that as usual we're going to use the where and then we
2:31:03
필터링할 열을 지정할 수 있습니다. 그러니까
can specify the column that we want to filter on so it's going to be the
2:31:06
점수가 될 것이고, 두 개의 경계가 있으므로
score and since we have like two boundaries we can go and use the
2:31:09
between 함수를 사용할 수 있습니다. 첫 번째 경계인 최저 경계부터 시작합니다. 100과 500이 상한 경계입니다. 그러니까 100과 500 사이입니다.
function between and we start with the first boundary the lowest boundary so it is the 100 and 500 the high boundary the upper boundary So between 100 and 500.
2:31:22
자, 이제 실행해 보겠습니다. 그렇게 하면 이 두 고객만 얻을 수 있습니다. 왜냐하면 그들은 이 범위에 있기 때문입니다.
So now let's go and execute it. And with that, we get only those two customers because they are between this window.
2:31:29
이제 between을 사용하지 않고 이 작업을 해결하는 또 다른 방법이 있습니다.
Now, there is another way on how to solve this task by not using between.
2:31:32
비교 연산자와 논리 연산자를 함께 사용할 수 있습니다. 그 방법을 보여드리겠습니다.
We can go and use the comparison operator together with a logical operator. And so let me show you how we can do that.
2:31:38
전체 내용을 복사하겠습니다. 이제 두 가지 조건을 작성할 것입니다.
I'm going to go and copy the whole thing. And now we're going to write two conditions.
2:31:42
첫째, 점수는 100 이상이어야 합니다. 경계는 포함됩니다.
So first, the score should be higher or equal to 100 because the boundaries is inclusive.
2:31:49
그리고 다른 하나는 점수가
and the other one the score is less or equal to
2:31:52
500 이하입니다. 이것이 상한 경계입니다. 그러니까
500 so this is the upper boundary so with
2:31:55
두 가지 조건이 생겼고, 이를 연결할 수 있습니다.
that we have the two conditions and we can go and connect them using
2:31:59
and 연산자를 사용하여, between과 매우 유사합니다.
the and operator so it's like very similar to the between
2:32:02
상한과 하한 경계 사이에 and가 있지만,
we have an and between the upper and the lower boundaries but
2:32:05
비교 연산자를 사용하고 있습니다. 그러니까
we are using the comparison operators so it is
2:32:08
100 이상이고 500 이하입니다.
higher or equal to 100 and lower or equal to
2:32:11
500에 해당하는 쿼리를 실행하면 정확히 같은 결과를 얻을 수 있습니다. 이제 제가 가장 좋아하는 방법이 무엇인지 물어보면
500 if you go and run this query you will get exactly same results now if you ask me which method is my favorite i'm
2:32:18
이 방법을 선택할 것이고, 중간을 건너뛸 것입니다. 왜냐하면
gonna go with this method and i will skip the between because
2:32:21
솔직히 매번 중간을 잊어버리기 때문입니다. 경계가
each time to be honest for me i forget about the between whether the
2:32:24
포함인지 제외인지 모르겠지만, 만약 제가
boundaries are inclusive or exclusive but if i
2:32:27
스크립트를 읽으면 정확히 그 경계가
read the script i'm gonna see exactly that those
2:32:30
포함되어 있다는 것을 알게 될 것입니다. 여기서 등호가 있으므로
boundaries are inclusive because we have here the equals so i
2:32:34
압축 연산자를 사용하는 것을 정말 선호합니다. 그리고 나서
really prefer using the compressor operator together with the and then
2:32:37
between을 사용하는 것이므로, 외우면 당신에게 달려 있습니다.
using between so it's up to you if you memorize it then
2:32:40
between을 선택하겠지만, 저는 압축 연산자를 선택할 것입니다. 자, 친구들, 이제 between과 범위 연산자에 대한 모든 것입니다. 이제
go with the between but for me i'm gonna go with the compressor operators okay my friends so that's all about the between and the range operator now let's move to
2:32:48
다른 그룹으로 넘어갑니다. 우리는 멤버십 연산자가 있습니다. 여기에는
another group we have the membership operator so here we have like
2:32:51
두 가지가 있습니다. in과 not in이 있으니
two we have the in and the not in so let's
2:32:54
이것이 정확히 무엇을 의미하는지 이해해 보겠습니다.
understand what this exactly means okay
2:33:00
in 연산자는 값이 목록에 존재하는지 확인합니다. 그래서 값 목록이 있고
so what is in operator it's gonna go and check if a
2:33:03
당신의 값이 목록의 구성원인지 확인하고 있습니다.
value exists in a list so you have a list of values and
2:33:06
이것이 무엇을 의미하는지 이해하기 위해 아주 간단한 예를 들어보겠습니다. 자, 이제 어떻게 작동하는지 정확히 알아보겠습니다.
you are checking whether your value is a member of your list
2:33:09
제가 목록을 가지고 있다고 가정해 보겠습니다. 그 안에 독일과 미국이라는 두 값을 지정했습니다.
so let's have a very simple example in order to understand what this means okay so now how this works exactly what you have to do is to go and make a list of values
2:33:17
이 두 값이 이 목록의 구성원입니다. 이제 end 연산자를 사용하면, 국가의 값이 목록에 있는지 확인합니다.
So let's say that I have a list and there I have specified two values, Germany and USA.
2:33:22
하나씩 해보겠습니다. 첫 번째 고객인 마리아의 국가는 독일이고, 독일은 목록의 구성원입니다.
So those two are the members of this list. Now, if you use the end operator, it's going to go and check the value of countries, whether it is in the list or not.
2:33:31
그래서 그녀는 행복할 것이고, 마리아를 최종 결과에 남길 것입니다. 이제 존으로 넘어갑니다. 존은 미국에서 왔습니다.
So let's do it one by one. For the first customer, Maria, her country is Germany and Germany is member of the list.
2:33:37
미국은 목록의 구성원이므로 그는 조건을 충족하고 있습니다.
So it's going to be happy and going to leave Maria in the final results. Now, moving on to John. John comes from USA.
2:33:44
그래서 그는 최종 결과에 나타날 것입니다.
usa is member of the list so he is fulfilling
2:33:47
조지에게 가보겠습니다. 조지는 영국에서 왔고, 영국은
as well the condition and you're gonna see john in the final results now
2:33:50
우리 목록의 구성원이 아닙니다. 이스라엘은
we come to george george comes from uk and uk is
2:33:53
이 고객을 최종 결과에서 제거할 것입니다. 조건을 충족하지 않으므로
not member of our list and israel gonna go and
2:33:56
마틴과 피터의 마지막 두 사람의 국가는
remove this customer from the final results not fulfilling
2:33:59
조건이 이제 마지막 두 마틴과 피터의 국가에 대해
the condition now for the last two martin and peter their country
2:34:02
목록의 구성원이며 이스라엘이 가고 이 고객들을 남길 것입니다.
is a member of the list and israel gonna go and leave those customers
2:34:06
결과에서 볼 수 있듯이 매우 간단합니다.
in the final results so as you can see it's very simple or what you
2:34:09
해야 할 일은 목록의 구성원을 정의하고
have to to do is to define the members of a list and use the
2:34:12
n 연산자를 사용해야 하며, 값이 이 목록의 구성원인지 확인합니다.
n operator and if the value is a member of this list
2:34:15
참이 될 것이고, 그렇지 않으면 거짓이 될 것입니다.
it's going to be true otherwise it's going to be false now of course the other
2:34:18
연산자는 정확히 반대가 될 것이며, 우리는 'not'이라고 말합니다.
operator going to be exactly the opposite where we say not
2:34:21
목록에 있으므로 우리는
in the list so we are searching for values that are
2:34:25
이 목록에 없는 값을 검색하고 있습니다. 'not'을 사용하므로 완전히 진리를 반전시킬 것입니다.
not in this list so as we are using not it's going to go and reverse
2:34:28
이 진리를 완전히 반전시키고, 이를 적용하면 결과에서 단 하나의 고객만 얻을 수 있습니다.
completely the truth and if we apply this you will get in the result only one customer you will get george and the result because the country is UK and UK is not a member of the list.
2:34:39
따라서 'not' 또는 'in' 연산자와 함께 사용하면 정반대의 효과를 얻을 수 있습니다.
So if you use not or together with the in operator, you will get exactly the opposite effect.
2:34:44
이것이 SQL에서 'in'과 'not in' 연산자가 작동하는 방식입니다.
So this is how the in and the not in operator works in SQL. Let's go back to SQL in order to practice that.
2:34:50
좋습니다, 이제 이 작업이 있으며, 독일 또는 미국의 모든 고객을 검색하라고 합니다.
Okay, so now we have this task and it says retrieve all customers from either Germany or USA.
2:34:55
좋습니다, 이제 이 작업을 해결해 보겠습니다. 조금 까다로울 것입니다.
Okay, so let's try to solve this task. This is going to be a little bit tricky.
2:34:59
따라서 평소처럼 고객에서 별을 선택하고 실행합니다.
So select star from customers as usual and execute it.
2:35:04
이제 결과에서 독일 또는 미국에서 온 고객만 필요합니다.
So now we are need in the results only customer that comes either from Germany or USA.
2:35:08
즉, 이 고객은 영국에서 왔기 때문에 결과에서 제외되어야 합니다.
So that means this customer over here should be excluded from the result because he come from UK. So how are we going to write it?
2:35:14
아마 이렇게 될 것입니다. 첫 번째는 국가가 독일과 같거나 미국과 같아야 합니다.
It's going to be like this, maybe. So the first one going to be the country is equal to Germany or the country is equal to USA.
2:35:24
이런 식으로 작성하고 실행하면
right something like this so if you go and execute it you will
2:35:27
독일에서 온 고객만 출력에서 얻을 수 있습니다.
get in the output only the customers that are either from germany
2:35:30
또는 미국에서 온 고객만 출력에서 얻을 수 있습니다.
or usa and with that we have solved the task right well there
2:35:33
이 작업을 해결하는 또 다른 방법이 있으며, 더 명확하고
is another way in order to solve this task which is more clear and
2:35:37
짧은 방법으로 n 연산자를 사용합니다.
shorter using the n operator so now how we're
2:35:40
이제 어떻게 할 것인지, 전체를 다른 쿼리에서 가져옵니다.
gonna do it let's go and get the whole thing in another
2:35:43
이제 같음과 또는 등을 사용하는 대신 n 연산자를 사용할 것이며, 두 개의 괄호를 가질 것입니다.
query and now instead of having equals and ors and so on we're gonna use the n operator and then we're gonna have like two parentheses
2:35:51
그 안에 값 목록을 가질 수 있습니다.
and then inside it we can have a list of values so
2:35:54
독일이 될 것이고 두 번째 값은 미국이 될 것입니다.
it's going to be the germany and then the second value going to be usa
2:35:57
이렇게 해서 우리는 국가가 되어야 한다고 말하고 있습니다.
like this so we are saying country should be
2:36:00
이 목록에서 독일 또는 미국이 되어야 하고
in this list germany or usa and if
2:36:03
그 값 중 하나라면 조건이 충족됩니다.
it's like one of those values then the condition is fulfilled
2:36:06
이제 여기서 이걸 실행하면
so now if you go and execute this one over here you
2:36:09
정확히 같은 결과를 얻을 것입니다. 친구들, 조건의 단어에서 반복하고 있다면
will get the exact same results so my friends if you notice that you are repeating yourself in the word condition and you are just changing the value of the condition it is based
2:36:18
같은 열을 사용하고 있으며 또는로 연결하고 있습니다.
the same column and you are connecting them using the or
2:36:21
문제가 있는 것 같고 항상 이 시나리오를 생각하세요.
then there is something wrong and always think on this scenario
2:36:25
in 연산자를 사용하는 것이 좋습니다. 왜냐하면 이건 정말 지저분할 수 있습니다.
to use the in operator because this can be really ugly
2:36:28
값이 많아지면, 우리의 데이터베이스를 상상해보세요.
once you have a lot of values so imagine in our database
2:36:31
많은 국가가 있고 당신의 쿼리는 이렇게 될 것입니다.
we have a lot of countries and your query gonna be like something
2:36:34
이렇게 해서 당신은 국가가 같거나 반복하고 있습니다.
like this so you are keep repeating country equal or
2:36:37
국가가 같고, 대신에 한 번에 정말 멋진 국가 목록을 가질 것입니다.
country equal and so on instead of that you're gonna have a really nice list of countries in one go so this is as you can see here
2:36:45
확장하기가 더 쉽고 성능도 더 좋습니다.
it is easier to extend and as well has better performance
2:36:48
같은 것을 반복하고 있지만
so as you can see we are repeating the same thing but
2:36:51
값을 변경하고 모든 조건을 연결하고 있습니다.
we are just changing the value and we are connecting all
2:36:54
이 시나리오에서 or를 사용하세요.
those conditions using the or in this scenario go and use the n
2:36:57
연산자입니다. 친구들, 이제 멤버십 연산자에 대한 모든 것입니다.
operator all right my friends so that's all for the membership operators now we're going to speak about the last one the search operator and here we have only one the like and each time we're going to say like i'm going to remind you to like this course.
2:37:10
마지막으로 검색 연산자에 대해 이야기할 것입니다.
So let's go. Okay, so now what is like operator?
2:37:16
패턴을 검색하기 위해 사용할 수 있습니다.
You can use it in order to search for a pattern in your text.
2:37:20
텍스트나 문자가 있고 텍스트 안에서 특정 패턴을 검색하고 있습니다.
So if you have like a text or characters and you are searching for a specific pattern inside the text.
2:37:26
정확히 무엇을 의미하는지 이해하기 위해 예를 들어보겠습니다.
So let's have an example in order to understand exactly what this means. Okay, so now if you don't have yet coffee, go grab one because you have to focus for this one.
2:37:34
이제 우리가 해야 할 것은 패턴을 정의하는 것입니다.
Now what we have to do is to define a pattern. In isquiel,
2:37:37
패턴을 만들기 위해 두 개의 특수 문자가 있습니다.
in order to build a pattern, we have like two special characters if
2:37:40
백분율을 사용하면 아무것도 보이지 않으므로
you use a percentage you are seeing anything so i'm
2:37:43
아무것도 받아들일 것이므로 문자 수가 0일 수도 있습니다
gonna accept anything so it could be no characters at all or
2:37:46
아니면 하나의 문자 또는 여러 문자가 될 수 있습니다
only one character or many characters so i'm saying anything
2:37:50
이제 밑줄을 사용하면 정확히 하나의 것을 기대하게 됩니다
now if you use an underscore you are expecting
2:37:53
하나의 문자 또는 하나의 숫자와 같은 것입니다
to have exactly one thing like one character or one
2:37:56
정확히 하나입니다. 이게 복잡하게 들릴 수 있지만 예를 통해 이해할 수 있습니다. 백분율이 밑줄보다 훨씬 더 유명하다는 것을 말씀드릴 수 있습니다
number so it is exactly one i know this sounds complicated but with an example you can understand this and i can tell you the percentage is way more famous than the underscore
2:38:05
나는 밑줄을 거의 사용하지 않습니다. 이제
I rarely really use the underscore So now let's
2:38:08
패턴을 이렇게 만든다고 가정해 보겠습니다. 첫 번째 문자는
say that I build the pattern like this I say the first character
2:38:11
M이어야 하고, 그 다음은 백분율입니다. 여기서 나는 말하고 있습니다
must be M and then percentage So here I'm saying
2:38:14
내 텍스트에서 첫 번째 문자는 M이어야 합니다. 그리고
in my text the first character must be an M And
2:38:18
첫 번째 문자 이후에는 정말 신경 쓰지 않습니다. 어떤 문자든 숫자든 상관없습니다. 그래서 이것이 패턴입니다
after the first character I really don't care It could be
2:38:21
이제 몇 가지 값을 가지고 진위 여부를 확인해 보겠습니다. 그래서
any character any number whatever So this is the pattern and
2:38:24
값이 Maria인 경우를 보겠습니다. 첫 번째 문자가 M이라는 것을 알 수 있습니다. 완벽합니다. 이것이 바로 우리의 패턴입니다
now let's have a few values in order to say whether it's true or false So
2:38:28
첫 번째 문자는 m이어야 하고, 그 다음에 m 뒤에
now if you have the value Maria So now you can see the first character is an M which is perfect This is exactly our pattern
2:38:34
네 개의 문자가 있어도 괜찮습니다
the first character must be an m and then after the m we
2:38:38
maria가 우리의 패턴을 충족한다고 말할 수 있습니다
got like four characters so whatever it is totally fine
2:38:41
이것이 우리가 찾고 있는 것입니다. 이 값이 조건을 충족합니다
we can say maria is fulfilling our pattern and
2:38:44
이제 다음 값으로 넘어가겠습니다. 우리는 ma가 있습니다
this is exactly what we are searching for this value is fulfilling
2:38:47
여기서도 첫 번째 문자는 m입니다
the condition okay now moving on to the next value we have ma
2:38:50
완벽하고 그 뒤에 문자 a가 하나만 있습니다. 우리는 백분율을 저장했으므로 어떤 것이든 될 수 있습니다
so here again the first character is an m which
2:38:54
하나의 문자, 여러 문자, 숫자 또는
is perfect and after that we have only one character a well we have saved percentage so it could be anything one character multiple characters a number or
2:39:02
무엇이든지요. 그래서 이 값이 우리의 패턴과 일치할 수 있습니다
whatever so that's why this value can match our pattern and
2:39:05
이제 출력에서 볼 것입니다. 다음 값으로 넘어가겠습니다
we will see it in the outputs now moving on to the next value we
2:39:08
m이 하나만 있습니다. 이것도 괜찮습니다
have only one m which is as well totally fine because
2:39:12
첫 번째 문자는 m이어야 하고, 그 다음에 어떤 것이든 따라와야 합니다
we are saying the first character must be an m and then followed
2:39:15
이제 마지막 시나리오로 넘어가면 에마가 있습니다.
with anything now moving on to the last scenario we have emma
2:39:18
문제가 되는 것은 첫 번째 문자가 e라는 것입니다.
now this is a problematic because the first character
2:39:21
이 값은 우리의 패턴을 충족하지 않기 때문에
is an e and in our pattern we say it must start with m so we don't have that in this world the first character is an e that's why this
2:39:29
이 값을 최종 결과에서 제거할 것입니다.
value is not fulfilling our pattern and sql gonna
2:39:32
이것이 바로 이 패턴과 값들이 있을 때 발생할 수 있는 일입니다.
remove this value from the final results so this is exactly
2:39:35
이제 다른 시나리오를 살펴보겠습니다.
what can happen if you have this pattern and those values now
2:39:38
무엇이든 시작할 수 있지만, 마지막 두 문자가 매우 중요합니다.
let's have another scenario where you say you know what it could start
2:39:41
마지막 두 문자는 i와 n이어야 합니다.
with anything but for me it is very important the last two
2:39:44
무엇이든 시작할 수 있지만 마지막 두 문자는 i와 n이어야 합니다.
characters it must be an i and n so
2:39:48
그래서 우리는 I와 N이 있고 첫 번째 부분은
we could start with anything but the last two must be an i and n so let's take this value martin sql gonna go and check immediately the last two
2:39:55
괜찮습니다. 무엇이든 될 수 있습니다. 이 값은 마지막 두 문자가 I와 N이기 때문에 조건을 충족합니다.
So you can see we have an I and N and the first part marks the
2:40:00
이제 다음으로 넘어가면 VIN이 있습니다. VIN. 마지막 두 문자는 우리가 찾고 있는 것과 정확히 일치합니다.
It is fine. It could be anything. So this value is fulfilling the condition because the last two characters is an I and N.
2:40:06
조건을 충족하고 있습니다. 그리고 그 앞에는 V만 있습니다.
Now moving on to the next one, we have VIN. So VIN. The last two characters is as well exactly what we are searching for.
2:40:14
그래서 우리는 퍼센트가 있는 모든 것을 말했습니다. 이제 IN이 있습니다.
It is fulfilling the condition. And we have before it like only V. So we said anything with the percentage, right? Now one more, we have IN.
2:40:20
그래서 그것은 조건을 충족하고 있습니다. 그 앞에는 아무것도 없습니다.
So it is as well fulfilling the condition because before it, we don't have anything.
2:40:25
그래서 EN도 조건을 충족합니다.
So EN is fulfilling as well the condition the percentage
2:40:28
항상 모든 것을 말하고 있습니다.
is always saying anything now moving on to the last scenario
2:40:31
자스민이 있습니다. 마지막 두 문자는
we have jasmine they are not the last two characters the
2:40:34
마지막 두 문자는 n과 e이며, 이는
last two characters is an n and e and this
2:40:37
우리의 패턴과 일치하지 않기 때문에 이 값은
is not matching our pattern and this why this value is
2:40:40
패턴을 충족하지 않으며 결과에서 볼 수 없습니다.
not fulfilling our pattern and you will not see it in the results
2:40:44
이제 이를 통해 텍스트에서 무언가를 검색하는 방법을 이해할 수 있습니다.
so with that you can understand how we can search for something in a text using the like operator let's keep going now let's say that i have a percentage
2:40:51
시작 부분에 퍼센트가 있고 끝 부분에 퍼센트가 있습니다.
at the start and percentage at the end and in
2:40:54
그 사이에 r이라는 문자 하나만 있습니다.
between i have only one character an r if you define it like this
2:40:57
어디에 r이 있든지 상관없이 괜찮습니다.
you are saying if there is an r anywhere it
2:41:01
어디에 r이 있든지 충분합니다
is good enough whether it's beginning or at the end or
2:41:04
조건이 충족되었다고 볼 수 있습니다
in between then the condition is fulfilled so if you have maria
2:41:07
왼쪽에 r이 있으니
you can see we have an r in the middle so in the left side
2:41:10
오른쪽에 두 글자가 있습니다
we have two characters on the right side we have two characters doesn't matter the main thing we have an r somewhere so this can be fulfilling
2:41:16
조건이 충족되었습니다
the condition now moving on to better we have an r at the
2:41:19
오른쪽에 무엇이든 될 수 있습니다
end and that is totally fine because we said at the
2:41:22
조건을 충족할 것입니다
right side it could be anything so we have an r somewhere that's
2:41:25
우리는 r이 시작에 있습니다
why it's gonna fulfill the condition now we have another case where
2:41:28
그 전에 아무것도 없고
we say ryan we have an r at the start so we don't have
2:41:32
r의 위치는 중요하지 않습니다
anything before and we have after that like three characters which
2:41:35
r만 있으면 충분합니다
is totally fine so we don't really care about the position of the r it is totally acceptable to have an r anywhere and if
2:41:42
그 전에 아무것도 없고
have only an r that is as well good enough you don't have
2:41:45
그 안에 r이 없습니다
anything before you don't have anything after and that's okay but
2:41:48
이것이 유일한 경우입니다
if you have a word like alice we don't have any r inside it
2:41:51
여기 r이 없고
so that's why this is the only case where you say we
2:41:55
결과에서 이 값을 제거할 것입니다
don't have here an r and is gonna remove this value
2:41:58
이 방법은 매우 유명합니다
from the results and this way of searching of something is very famous you don't care about the words before this word and after the word right so if you are searching for any words you're gonna say
2:42:08
백분율이 필요합니다
percentage before and percentage after now i know that
2:42:11
두 개의 밑줄이 있습니다
we want to practice with the underscore so let's say that i have two underscores
2:42:15
첫 번째 위치에 무언가가 있어야 합니다
and then the character b and then a percentage so
2:42:18
두 번째 위치에도 무언가가 있어야 합니다
here what i'm saying there should be something in the first position there
2:42:21
세 번째 위치는 b여야 합니다
should be as well something in the second position then the
2:42:24
이 위치에 있어야 합니다
third position should be the character b must be exactly
2:42:27
우리는 신경 쓰지 않습니다
at this position and after that it could be anything so
2:42:30
첫 번째 위치에 무언가가 있습니다
we really don't care i know this is a little bit complicated let's have an example so we have the value albert now we can see the first position we have something
2:42:38
a 다음 두 번째 위치에도 무언가가 있습니다
the a then the second position we have as well something the
2:42:41
l 지금까지 패턴이 잘 맞고 세 번째
l so so far we are good at the pattern and then the third
2:42:44
위치에 b가 있으므로 완전한 일치가 있습니다
position we have b so we have complete match and the
2:42:47
나머지 ert 뭐든지 그래서 그 알버트와 함께
rest the ert whatever so with that albert
2:42:50
우리의 패턴과 일치하고 다음으로 넘어갑니다
is matching our pattern moving on to the next one rob you
2:42:53
첫 번째 문자가 무언가가 있는 것을 볼 수 있습니다
can see the first character we have something which is good we
2:42:56
r 그런 다음 두 번째 문자는 o가 있으므로 비어 있지 않습니다
have the r then the second character we have an o so it's not empty we have something and then the third one we have exactly b and after that we
2:43:04
무언가가 있고 세 번째는 정확히 b가 있습니다
don't have anything which is fine so again this value can fulfill the
2:43:07
그 후에는 아무것도 없으므로 괜찮습니다
condition so moving on to the next one so it starts with
2:43:10
조건을 충족할 수 있습니다
an a so we have something in the first position the second position we
2:43:14
다음으로 넘어가서 a로 시작합니다
have as well something the b but now the third character it is a
2:43:17
첫 번째 위치에 무언가가 있고 두 번째 위치에도
problem it is not p we have an e so that's why it
2:43:20
b가 있지만 이제 세 번째 문자는 a입니다
is not following our pattern and israel gonna go and remove it now moving on to last example we have an a and an n so in the first position we have something the second one as well
2:43:28
문제가 p가 아닙니다 e가 있으므로
but the third one we don't have anything we don't have a b so
2:43:32
그래서 그것이 우리의 패턴을 따르지 않습니다
that's why it's gonna be removed so my friends i know that was a lot
2:43:35
이제 마지막 예제로 넘어갑니다
but this is exactly how you build a pattern for the like operator
2:43:38
첫 번째 위치에 무언가가 있고 두 번째 위치에도
using the percentage and the underscore but the percentage
2:43:41
세 번째는 아무것도 없으므로 b가 없습니다
is more famous so this is exactly how it works let's
2:43:45
그래서 제거될 것입니다
go back to scale in order to have some examples all right let's
2:43:48
친구들, 그게 많았다는 걸 압니다
start with this task find all customers whose first name starts
2:43:51
하지만 이것이 바로 like 연산자를 위한 패턴을 만드는 방법입니다
with a capital m so let's go and start searching for those informations we're gonna start as usual select star from customers and now we have
2:43:58
퍼센트와 언더스코어를 사용하지만 퍼센트
go and build the filter logic so we're gonna say where
2:44:02
가 더 유명합니다
now we are searching something in the first name so we're
2:44:05
이것이 정확히 어떻게 작동하는지 보겠습니다
gonna say first name so that means it is very important
2:44:08
예제를 위해 스케일로 돌아가겠습니다
to start with an m and then the rest it doesn't matter so
2:44:11
우리는 검색하기 위해 like 연산자를 사용할 것입니다.
we're gonna use the like operator in order to search and
2:44:14
우리는 단일 코드를 가질 것이고 m으로 시작할 것입니다.
we're gonna have our single code and we're gonna start with the m
2:44:17
그 다음에 무엇이 오든 상관없습니다. 그래서 우리에게는 첫 번째 문자가 M인 것이 매우 중요합니다. 실행해 보겠습니다.
and it doesn't matter what comes after that so for
2:44:20
그리고 그로 인해 우리는 두 명의 고객, 마리아와 마틴을 얻었습니다. 두 사람 모두 M으로 시작합니다.
us it is very important that the first character is an m let's go and execute it and And with that, we got our two customers, Maria and Martin, and both of them start with an M.
2:44:31
그래서 우리는 이 작업을 해결했습니다. 매우 간단합니다. 이제 다음 작업이 있습니다.
So with that, we have solved the task. It is very simple. Now we have the following task.
2:44:35
이름이 N으로 끝나는 모든 고객을 찾으세요. 먼저 여기에서 모든 고객을 선택해 보겠습니다.
Find all customers whose first name ends with an N. So let's go first and select all the customers here.
2:44:42
그리고 우리는 끝에 N이 있는 모든 고객이 필요합니다. 그래서 우리는 존과 마틴이 있습니다.
And we need all those customers where they are having an N at the end. So we have John and as well Martin.
2:44:48
그럼 어떻게 할까요? 첫 번째 이름이 같은 방식으로 검색하므로, 여기서 표현식을 변경할 것입니다.
So how are we going to do it? The same thing where first name like since we are searching. But here we're going to change the expression.
2:44:55
그래서 마지막 문자가 N으로 끝나야 합니다. 그래서 그 전에 첫 번째 문자가 무엇인지 상관없습니다.
So it must end with an N as last character. So before that, it doesn't matter whether it is the first character.
2:45:01
그래서 무엇이든 될 수 있습니다. 하지만 단어의 마지막 문자는 N이어야 합니다. 그래서 그게 전부입니다. 실행해 보겠습니다.
So it could be anything. But the last character of the word should be an N. So that's it. Let's go and execute.
2:45:08
그로 인해 우리는 존과 마틴을 얻었습니다. 마지막 문자가 N이기 때문에 매우 간단하죠?
And with that, we got John and Martin because the last character is an N. It is very simple, right?
2:45:13
모든 것은 이 백분율을 어디에 배치할 수 있는지에 관한 것입니다. 알겠습니다, 이제 다음 작업이 있습니다.
It is all about where we can place this percentage. Okay, so now we have the next task.
2:45:18
이름에 R이 포함된 모든 고객을 찾으세요.
Find all customers whose first name contains an R.
2:45:22
여기서는 시작 부분에 있는지 끝 부분에 있는지에 대한 명세가 없습니다.
So here we don't have like specifications whether it is at the start
2:45:25
어딘가에 R이 있어야 합니다. 그래서 만약
or at the end Somewhere there should be an R So if
2:45:28
어떤 조건 없이 먼저 실행하면, 예를 들어 마리아는 중간 어딘가에 R이 있습니다.
you go and execute first without any where condition You can see here for example Maria we have in the middle somewhere an R
2:45:34
조지와 마틴, 그리고 피터는 끝에 있습니다. 그래서
George as well Martin and Peter at the end So
2:45:37
우리는 R이 있는 많은 이름을 가지고 있습니다. 그럼 우리는 어떻게 검색할 수 있을까요?
we have a lot of names with an R So how we can search for
2:45:40
우리는 '이름이 R과 같음'을 사용할 것입니다. 그리고 여기서 우리의 문자는 R이 될 것입니다. 그리고 그 앞과 뒤에 백분율을 넣을 것입니다. 그래서 그 앞이나 뒤가 무엇인지 상관없습니다.
that We're gonna stick with the where first name like And here our character gonna be an R And we're gonna put before it and after it a percentage So it doesn't matter what is before it or after it.
2:45:52
어딘가에 R이 있어야 합니다. 그래서 실행해 보겠습니다.
Somewhere there should be an R. So let's go and execute it.
2:45:55
그로 인해 우리는 어딘가에 R이 있는 모든 고객을 얻었습니다. 보시다시피, 매우 간단합니다.
And with that, we got all our customers where somewhere we have an R. As you can see, it's very simple.
2:46:01
앞과 뒤에 넣으면 더 많은 결과를 얻을 수 있습니다.
If you put it before and after, then you are open for more results.
2:46:05
그리고 이것은 일반적으로 데이터베이스 내에서 값을 검색하기 위해 많이 사용됩니다. 알겠습니다, 이제 재미있는 것으로 넘어가겠습니다.
And this is usually used a lot in order to search for a value inside your database. All right, now we're going to move to a funny one.
2:46:11
세 번째 위치에 R이 있는 모든 고객을 찾으라는 것입니다. 이유는 모르겠습니다.
It's going to say is find all customers whose first name has an R in the third position. For some reason, I don't know why.
2:46:18
그래서 필터 없이 여기에서 고객을 실행해 보겠습니다.
So let's go and execute our customers here without any filter.
2:46:21
그래서 우리는 세 번째 위치에 R이 있는 고객을 찾는 것이 매우 중요합니다.
So it is for us very important to find the customers where in the third position we have an R.
2:46:26
예를 들어, 마리아의 세 번째 문자에는 R이 있어서 괜찮습니다. 하지만 피터는 세 번째 문자가 아닙니다.
Like here, for example, Maria, the third character is an R, which is OK. But with Peter over here, it is not the third character.
2:46:33
그래서 조건을 충족하지 않습니다. 그럼 어떻게 작성할까요?
So it is not fulfilling the condition. So how are we going to write that?
2:46:36
이렇게 첫 번째 이름처럼 말할 것이지만, 이제 처음부터 작성해야 합니다. 첫 번째 위치는 밑줄이 될 것입니다.
It's going to say like this where the first name like, but we have to write it now from the start. So the first position is going to be an underscore.
2:46:44
두 번째 위치도 밑줄이 될 것입니다. 그리고 이제
The second position is going to be as well an underscore. and now in
2:46:47
세 번째 위치에 R이 있을 수 있으니, 이를 통해
the third position we can have an R so with that we
2:46:50
세 번째 위치와 R을 확실히 하고 그 앞에
make sure the third position and an R and before it we
2:46:53
두 개의 위치가 있고 이제 그 이후에는 상관없습니다.
have two positions and now afterward it doesn't matter what
2:46:56
그 뒤에 오는 것은 아무것도 없거나 문자일 수 있으니,
comes after that it could be nothing or characters so if
2:46:59
이렇게 실행하면 마리아와 마르틴을 얻을 수 있습니다.
you go and execute it like this we will get Maria and Martin
2:47:03
그리고 우리는 피터를 얻지 못할 것입니다. 왜냐하면 R이 세 번째에 없기 때문입니다.
and we will not get Peter because the R is not in the third
2:47:06
위치이므로, 이제 밑줄로 정확히 하지 않으면 하나를 제거하고 실행하면 아무것도 얻지 못할 것입니다.
position so now if you don't do it correctly with the underscores let's go and remove one of them and execute you will get nothing because we don't have any first name where the second position is an R.
2:47:17
그래서 이 점에 대해 매우 조심해야 합니다. 알겠죠, 친구들? 이렇게 값 안에서 검색하는 방법입니다.
So you have to be very careful with this. All right, my friends. So this is how you search inside your values.
2:47:22
그리고 이를 통해 where 절 안에서 사용할 수 있는 다양한 연산자 그룹을 다루었습니다.
And with that, we have covered all different groups of operators that you can use inside a where clause.
2:47:28
그래서 이를 통해 where 절 안에서 사용할 수 있는 여러 연산자를 사용하여 데이터를 필터링하는 방법을 배웠습니다.
So with that, you have learned how to filter your data using multiple operators that you can use inside the where clause.
2:47:34
이제 SQL에서 무엇이든 필터링할 수 있습니다. 이제 매우 흥미로운 주제로 넘어가겠습니다.
So you can filter anything now in SQL. Now we will move to a very interesting topic. You will learn how to combine your data from multiple tables.
2:47:42
여기에는 두 가지 주요 방법이 있습니다. 첫 번째는 SQL 조인입니다.
and here we have two main methods the first one is sql joins
2:47:45
두 번째는 집합 연산자이며, 이들은 정말 방대합니다.
and the second set operators and they are really big
2:47:48
주제이므로 먼저 SQL 조인에 집중할 것입니다.
topics so we're gonna first focus on the sql joins
2:47:51
여기에는 다룰 것이 많으므로 이제 SQL의 핵심에 대해 이야기하고 있습니다.
and here we have a lot of things to cover so now we are talking
2:47:54
자, 이제 두 개의 테이블, 테이블 A와 테이블 B가 있습니다.
about the core of sql so let's go all
2:48:01
여기서 큰 질문은 그것들을 어떻게 결합할 것인가입니다.
right so now we have two tables table a and table b
2:48:04
두 개의 테이블에서 정확히 무엇을 원하는지, 열을 결합하고 싶은지
and the big question here is how to combine those
2:48:08
행을 결합하고 싶은지, 이제 만약 당신이
two tables what do we want exactly do you want to
2:48:11
열을 결합하고 싶다고 말하면, 우리는 다음에 대해 이야기하고 있습니다.
combine the rows or the columns and now if you
2:48:14
열을 결합하고 싶다고 말하면 우리는
say i would like to combine the columns then we are talking about
2:48:17
테이블을 조인하는 것에 대해 이야기하고 있습니다.
joining tables so we're going to use joins in
2:48:20
테이블 A와 테이블 B를 조인한다고 가정해 보겠습니다.
sql so now let's say that we are joining the table a with
2:48:23
테이블 A의 열과 행을 가져오고 SQL
the table b and we start from the table a so it's going to
2:48:26
테이블 A에서 시작하므로 이를 왼쪽 테이블이라고 부릅니다.
take the columns and the rows of the table a and sql
2:48:29
거기서 시작하여 테이블 B와 SQL을 조인합니다.
gonna call it the left table because we started
2:48:32
두 번째 테이블을 오른쪽 테이블이라고 부르고 여기서
from there and then we join it with the table b and sql
2:48:35
발생할 수 있는 것은 오른쪽 테이블의 열과 행을 가져오는 것입니다.
gonna call the second table as the right table and here what
2:48:38
오른쪽 테이블의 열과 행을 가져와서 나란히 배치합니다.
can happen is we're going to take the columns and the rows from the
2:48:42
오른쪽 테이블의 열과 행을 테이블 A의 열과 행과 나란히 배치합니다.
right table and put it side by side with the columns
2:48:45
테이블 A의 열과 행을 결합하는 것과 같습니다.
and rows of the table a so we are like combining
2:48:48
이제 나란히 배치하고 싶지 않다고 말하면
the columns we are putting them side by side and now
2:48:51
두 테이블의 행을 결합하고 싶다고 말하면
if you say you know what i don't want to do that i would like to combine
2:48:54
여기서 왼쪽과 오른쪽이 없습니다.
the rows both of the tables having the same columns i just want to stack them so we are now talking about another method it is called the set operators so here there there is like no left and right.
2:49:05
테이블 A에서 시작하므로 SQL은 테이블 A의 열과 행을 가져와 결과에 넣습니다.
So since we started with the table A, the SQL gonna take the columns and the rows of the table A and put it in the results.
2:49:11
그런 다음 두 번째 테이블인 테이블 B로 이동하여
And then it's gonna go to the second table, table B, and it's gonna take only the rows and put it below the rows of the table A.
2:49:17
서로의 아래에 행을 배치하고 있습니다.
So we are putting the rows beneath each other's. We are doing like appending.
2:49:22
따라서 집합 연산자를 사용하면서 행을 결합하고 있습니다.
So that means as we are using the set operators, we are combining the rows.
2:49:26
우리의 테이블은 더 길어질 것이고, 열을 나란히 결합하고 있습니다.
Our table gonna be longer, but with the we are combining the columns side by side and we are getting wider table.
2:49:33
하지만 각 방법에는 다양한 유형이 있습니다.
But now for each method there are different types. So now for example in order to do the joins we have four very famous types.
2:49:40
내부 조인, 전체 조인, 왼쪽 조인, 오른쪽 조인을 수행할 수 있습니다.
We can do an inner join, full join, left join, right join. But of course there are more than that but those are the basics.
2:49:46
집합 방법에도 유형이 있습니다.
And for the set methods we have as well types. We have the union, union all, accept and intersect.
2:49:52
각 방법에는 서로 다른 규칙이 있습니다.
And for each method there are like different rules. In In order to join the tables, we have to define the key columns between the two tables.
2:49:59
걱정하지 마세요, 나중에 배울 수 있습니다.
Don't worry, you can learn about that later. But this is the requirement in order to join tables.
2:50:03
집합 연산자를 사용하여 테이블을 결합하는 요구 사항은,
And the requirement of combining tables using the set operators,
2:50:07
쿼리의 테이블은 정확히 같은 수의 열을 가져야 합니다.
the tables in your query should have the exact same number of columns.
2:50:12
하지만 여기서는 테이블을 결합하기 위해 유사한 키가 필요하지 않습니다.
But here you don't need any like key in order to combine the tables.
2:50:15
그래서 여러분, 이것을 보면 두 테이블을 결합하기 위해 먼저 열을 결합할지 행을 결합할지를 결정해야 합니다.
So guys, if you look at this, in order to combine two tables, first you have to decide, do I want to combine the columns or the rows?
2:50:22
먼저 방법을 결정해야 합니다. 그 후에 데이터를 결합하는 방법의 종류가 다릅니다.
So first you have to decide the methods. And after that, you have different types on how exactly you're going to go and combine the data.
2:50:28
물론 따라야 할 규칙이 있습니다. 이제 이 과정에서 모든 것을 다룰 것입니다.
And of course, there are rules that you have to follow. Now, of course, we're going to go and cover everything in the course.
2:50:33
하지만 이제 이 섹션에서는 SQL 조인을 사용하여 테이블을 결합하는 방법을 배울 것입니다.
But now in this section, we're going to learn how we're going to combine the tables using the SQL joins.
2:50:38
그래서 우리는 이 세계로 뛰어들 것입니다. 알겠죠.
So we're going to go and dive into this world. All right.
2:50:45
그렇다면 SQL 조인이 정확히 무엇인가요? 이제 두 개의 테이블이 있다고 가정해 보겠습니다. 왼쪽 테이블에는 고객 이름이 있습니다. 고객이 네 명 있습니다.
So now what is exactly SQL joins? Now, let's say that we have two tables. On the left table, we have the customer name. So we have four customers.
2:50:52
오른쪽 테이블에는 고객에 대한 국가 정보가 있습니다.
and on the right table we have the country informations about the customer
2:50:55
이 두 정보를 쿼리하고 싶습니다.
and now we would like to query both of those informations the
2:50:59
이 두 테이블을 하나의 쿼리로 쿼리하기 위해서는 먼저
names and the countries now in order to query
2:51:02
그들을 연결해야 합니다. 이 두 테이블을 연결하기 위해서는
those two tables in one query first we have to
2:51:05
왼쪽과 오른쪽에 존재하는 열, 즉 키가 필요합니다.
connect them and in order to connect those two tables we
2:51:08
공통 열을 보면
need a key a column that exists on the left and on
2:51:11
고객의 ID입니다. 이제 이 ID를 연결하면 쿼리할 수 있습니다.
the right side and by looking to this the common column
2:51:14
이 테이블들을 함께 연결할 수 있고, 이스라엘은 이를 매칭하기 시작할 수 있습니다.
here is the id of the customer now once we connect those ids together we will be able to query
2:51:20
ID 번호 1에 대해 이름을 가져옵니다.
those tables together and israel can start matching those
2:51:23
마리아와 국가 독일, 그리고 ID 2는
ids so for the id number one we will get the name
2:51:27
존을 미국에 연결하고 이제 볼 수 있습니다.
maria and the country germany and the id two
2:51:30
ID 3은 연결할 수 없으므로 연결할 수 없습니다.
is connecting john to usa and now you can see
2:51:33
오른쪽에 연결할 수 없지만 ID 4는 사용할 수 있습니다.
the id three is not connectable so we cannot connect
2:51:36
마르틴을 독일에 연결하기 위해서입니다. 이것이 바로
it to the right side but for the id four we can use it
2:51:39
두 테이블을 조인할 때 발생하는 일입니다. 두 테이블을 연결합니다.
in order to connect martin to germany so this is exactly
2:51:42
공통 열, 즉 ID와 같은 키를 사용하여 일치하는 값을 가지면 두 행을 함께 연결할 수 있습니다. 이것이 SQL 조인을 의미합니다.
what happens if you join two tables you connect those two tables
2:51:46
왜 조인이 필요한지 물어볼 수 있습니다. 첫 번째는
using a common column a key like the id and once we have matching value we can connect the two rows together so this is what we mean with sql joins
2:51:59
이제 여러분은 왜 조인이 필요한지 궁금할 수 있습니다. 첫 번째
now you might ask why do we need actually joins well the first
2:52:02
그리고 매우 중요한 이유는 데이터를 재조합하기 위해서입니다.
and very important reason is to recombine your data so
2:52:06
이제 일반적으로 데이터베이스에서는 어떤 것에 대한 데이터가
now usually in databases the data about something like
2:52:09
고객에 대한 데이터가 여러 테이블에 분산될 수 있습니다.
the customers could be spreaded into multiple tables
2:52:12
예를 들어 고객이라는 테이블과 고객 주소가 있는 또 다른 테이블이 있을 수 있습니다.
like we could have table called customers another one where
2:52:15
고객의 주문을 찾을 수 있는 세 번째 테이블이 있고, 아마도 또 다른
we have the customer addresses and a third table where you
2:52:18
고객의 리뷰를 찾을 수 있는 테이블이 있을 것입니다. 그래서
can find the orders of the customers and maybe another
2:52:21
보시다시피 고객의 데이터는 여러 개의 테이블에 분산되어 있습니다.
one where you can find the reviews of the customers so
2:52:25
이제 모든 데이터를 보고 싶다고 가정해 보겠습니다.
as you can see the data of the customers is spreaded into like
2:52:28
고객에 대한 모든 데이터를 하나의 결과로 보고 싶습니다.
four tables now how about i would like to see all the data
2:52:31
고객에 대한 전체적인 그림을 보고 싶습니다. 무엇을
about the customers in one results so i would like to see
2:52:34
할 수 있을까요? 우리는 그 네 개의 테이블을 연결할 수 있습니다.
the complete big picture about our customers what
2:52:37
SQL 조인을 사용하여 그렇게 할 수 있습니다. 그리고 우리가 그렇게 하면
we can do we can go and connect those four tables
2:52:40
하나의 쿼리에서 모든 것을 결합할 수 있습니다.
using the sql joins and once we we do that
2:52:44
하나의 큰 결과로 테이블을 결합할 수 있으며, 이것이 가장
in one query i will be able to combine all those
2:52:47
우리가 SQL 조인을 사용하는 가장 중요한 이유입니다.
tables in one big results and this is the most
2:52:50
특정 주제에 대한 모든 데이터를 결합하기 위해서입니다.
important reason why we use sql joins in order
2:52:53
그 큰 그림을 보기 위해서입니다. 이제 우리가 SQL 조인을
to combine all the data about specific topic in
2:52:56
사용하는 또 다른 이유는 데이터 풍부화입니다. 그것은
order to see that big picture now another reason why we
2:52:59
추가 데이터와 추가 정보를 얻고 싶을 때입니다.
use sql joins is to do data enrichment it
2:53:02
고객 테이블을 쿼리하고 있다고 가정해 보겠습니다. 이것이 주 테이블입니다.
is where i want to get an extra data and extra information
2:53:05
필요한 모든 데이터를 볼 수 있지만, 때때로 발생하는 일은
so let's say that you are querying the table customers and this is your main table the master table so you are able to see all
2:53:12
다른 테이블에서 추가 정보를 얻고 싶을 때입니다. 예를 들어
data that you need but sometimes what happens you would like to get
2:53:15
국가의 우편번호를 원할 때입니다. 그래서 도움이 필요합니다.
an extra information from another table like for example
2:53:19
다른 테이블이 필요합니다. 이를 참조 테이블이라고 하거나 때때로 조회 테이블이라고 합니다.
the zip codes of the countries so you would like the help of
2:53:22
우리가 참조 테이블이라고 부르는 또 다른 테이블
another table we call it a reference table or sometimes lookup
2:53:25
추가 정보를 포함하는 테이블
table where there is like one extra information that you would like
2:53:28
주 데이터 소스에 추가하기 위해 마스터 테이블에
to add it to your master table to the primary source of your data so now what we can do we can join those two tables in order to enhance our table so we are getting
2:53:37
고객을 위한 추가 관련 정보를
one extra relevant information for the customers and
2:53:40
데이터 보강이라고 부르는 이 과정에서
this process we call it data enrichment i'm getting an
2:53:43
주 테이블을 위한 추가 데이터를
extra data for my main table so this is another
2:53:47
두 테이블에서 데이터를 가져오기 위해 조인을 사용했습니다
reason why we use joins all right so now so far we
2:53:50
SQL 조인의 또 다른 사용 사례가 있습니다
have used joins in order to get the data from two tables
2:53:53
데이터의 존재 여부를 확인하기 위해 사용합니다
but now there is another use case for the sql joins we
2:53:56
고객이라는 테이블이 있다고 가정해 보겠습니다
use it in order to check the existence of your data
2:53:59
이 테이블로 쿼리를 수행하고 있지만
in another table or maybe as well than not existence so let's say that i have a table called customers and i'm working
2:54:06
우리 고객이 주문했는지 확인하고 싶습니다
with this table and doing queries but now i would like to check something
2:54:09
그것을 확인하기 위해 다른 테이블의 도움이 필요합니다
i would like to check whether our customers did order
2:54:12
예를 들어 주문 테이블의 도움을
something now in order to check that i need the help
2:54:16
주문 테이블만 사용하고 있다는 뜻입니다
of another table for example the table orders so
2:54:19
내 확인을 위해서만 주문 테이블을 사용합니다
that means i'm using the table orders only for
2:54:22
주문 테이블에 고객의 존재 여부에 따라
my check so i don't want to get any extra data from the orders in my final results i'm just using the table orders and we call then this table a lookup so now what we can do we can connect those two tables together
2:54:33
조인을 기반으로 데이터를 필터링하고 있습니다
And now based on the existence of the customers inside the second table, the orders, either the customer going to stay in the final results or going to be removed.
2:54:42
주문하지 않은 모든 고객을 최종 결과에서 보고 싶습니다
So that means I'm filtering the data based on the join. And of course, I can check as well the net existence.
2:54:48
나는 최종 결과에서 아무것도 주문하지 않은 모든 고객을 보고 싶습니다. 그래서 같은 시나리오입니다.
I would like to see in the final results all the customers that didn't order anything. So it is the same scenario.
2:54:54
첫째, 여러 테이블의 데이터를 하나의 큰 그림으로 결합하고 싶을 때입니다
So my friends, those are the main three reasons why we use SQL joins.
2:54:58
그래서 서로 다른 테이블에서 데이터를 가져오기 위해 조인을 사용합니다
First, if you want to combine the data from multiple tables in one big picture.
2:55:03
둘째, 하나의 테이블로 작업하지만
So I use join in order to get the data from different tables.
2:55:06
추가 정보를 다른 테이블에서 얻고 싶을 때입니다
The second use case, you are working with one table, but you would like to get an extra information from another table.
2:55:12
데이터 보강이라고 부르는 작업을 하고 있습니다.
So you are doing it like something called data enrichment. And in the third scenario, we don't want to combine the data.
2:55:18
우리는 다른 테이블과 결합하여 체크를 하고 싶습니다. 다른 테이블에서 레코드의 존재를 확인하기 위해서입니다.
We want just to join it with another table in order to do a check, to check the existence of your records in another table.
2:55:25
그래서 SQL에서 조인이 필요한 이유입니다. 테이블을 조인하는 방법에는 여러 가지 가능성이 있습니다.
So this is why we need joins in SQL. Now there is like a lot of different possibilities on how to join tables, how to join the data.
2:55:37
이해하기 쉽게 두 개의 원으로 테이블을 시각화할 것입니다. 그래서 테이블 A와 테이블 B가 있습니다.
Now in order to make it easy to understand, we're going to visual the tables as like two circles. So we have the table A and a table B.
2:55:44
테이블 A는 왼쪽에 있고, 우리는 이를 왼쪽 테이블이라고 부릅니다. 테이블 B는 오른쪽에 있으며, 우리는 이를 오른쪽 테이블이라고 부릅니다.
The table A is on the left side, we call it the left table. And the table B is going to be on the right side and we call it the right table.
2:55:51
테이블의 시각이 매우 중요합니다. 이제 이 두 개의 원을 결합하면 세 가지 다른 가능성이 생깁니다. 원이 겹칠 수 있습니다.
The sight of the tables is very important. Now, if you combine those two circles, you will get three different possibilities. The circles can overlap.
2:55:59
여기서 두 테이블 간의 일치하는 데이터를 가질 수 있는 정확한 위치입니다. 왼쪽과 오른쪽 모두에서 데이터가 사용 가능합니다.
And here exactly where we can have the matching data between the two tables. So the data is available on the left and on the right.
2:56:06
또 다른 가능성은 한 테이블의 모든 데이터를 가져오는 것입니다. 따라서 한 원에서 모든 행을 가져올 수 있습니다.
Or another possibility, you want to get all the data from one of the tables. So you can get all the rows from one circle.
2:56:12
세 번째 가능성은 한 테이블에서 일치하지 않는 데이터만 가져오는 것입니다.
And the third possibility, you want to get only the unmatching data from one table.
2:56:18
하나의 테이블에 존재하지만 다른 테이블에는 존재하지 않는 경우, 이를 일치하지 않는 데이터라고 부릅니다.
So if something exists in one table but not in the other table, then we call it unmatching data.
2:56:23
이것이 테이블을 결합할 때 스스로에게 물어봐야 할 세 가지 시나리오입니다. 그리고 이것은 많은 조인 유형을 생성할 수 있습니다.
So those are the three scenarios that you have to ask yourself once you are combining tables. And this can generate a lot of join types.
2:56:30
여기에는 기본 SQL 조인이 있습니다. 이것들은 고전적인 것입니다.
So here we have like basic SQL joins. Those are the classical one.
2:56:34
시나리오에 따라 왼쪽 또는 오른쪽에서 모든 행을 일치시키고 싶은지 여부가 달라집니다.
And it depends on the scenario whether you want only matching all the rows from either left or right.
2:56:40
우리는 일치하지 않는 데이터에 초점을 맞춘 고급 SQL 조인을 가지고 있습니다. 이제 이러한 유형을 하나씩 다룰 것입니다.
And we have advanced SQL joins where we focus on the unmatching data. Now we're going to go and cover all those types one by one.
2:56:47
기본부터 시작할 것이며, 첫 번째 옵션은 테이블을 조인하지 않고 모든 데이터를 가져오는 것입니다. 이것이 의미하는 바를 살펴보겠습니다.
so we're gonna start first with the basics and the first option that you have is to get all the data without joining tables so let's see what this means
2:56:58
조인이 없다는 것은 무엇을 의미할까요? 우리는 반환하고 싶습니다.
so what do we mean with no join well we want to return
2:57:02
두 테이블의 데이터를 결합하지 않고 반환하고 싶습니다.
the data from two tables without combining them so
2:57:05
사실 이것은 조인 유형이 아닙니다. 우리는 결합하지 않기 때문입니다.
actually this is not a join type because we are not combining
2:57:08
우리는 단지 두 테이블에서 데이터를 쿼리하고 싶습니다. 즉, 테이블 A에서 모든 행을 보고 싶습니다.
anything we just want to query the data from two tables so that means from the table a we want to see all the rows everything
2:57:15
그리고 테이블 B에서도 모든 것을 보고 싶습니다.
and from the table b we want to see everything as well all
2:57:18
모든 행을 원하므로 두 개의 결과를 보고 싶습니다.
the rows so that means we want to see two results and there
2:57:21
결합할 필요가 없으므로 그 구문을 살펴보겠습니다.
is no need to combine them so let's see the syntax of that so
2:57:25
해야 할 일은 매우 간단합니다. 테이블에서 모든 것을 선택합니다.
what you have to do is very simple select star from table
2:57:28
A에서 세미콜론을 입력한 후 다른 쿼리를 시작합니다.
a and then semicolon and then start another query
2:57:31
테이블 B에서 모든 것을 선택합니다. 그게 전부입니다.
select star from table b so that's it and of
2:57:34
데이터를 결합하지 않기 때문에 구문에 조인이 없습니다. 그게 전부입니다.
course since we are not combining the data there will be no join in the syntax so that's it let's go to SQL in order to do that okay so now we have the film
2:57:42
고객으로부터 모든 데이터를 검색하라는 작업입니다.
task it says retrieve all data from customers and
2:57:45
주문을 두 개의 다른 결과로 나누는 것입니다.
orders in two different results so that sounds that
2:57:49
테이블을 결합할 필요가 없습니다.
we don't have to go and combine the tables together and all what you can
2:57:52
다음과 같은 방식으로 첫 번째 테이블에서 데이터를 선택할 수 있습니다.
do is the following we can go and select the data from the first table
2:57:55
이렇게 하고 나서 우리는
like this and then we make
2:57:58
두 번째 테이블에 대한 또 다른 쿼리를 만듭니다.
another query for the second table the
2:58:01
주문을 하고 우리는 그것들을 하나로 결합할 필요가 없습니다.
orders and we don't have to go and combine them in one
2:58:04
큰 쿼리에서 우리는 데이터를 검색하기 위해 매우 간단한 선택 문을 사용합니다. 그래서 실행하면
big query we just use a very simple select statement in order to retrieve the data so if you go and execute it since you
2:58:11
두 개의 별도 쿼리가 있으므로 두 개의 결과를 얻습니다.
have two separate queries you will get two results and with
2:58:14
그 중 하나의 결과에는 모든 고객이 포함되고
that in one result you will get all the customers and in
2:58:17
다른 결과에는 모든 주문이 포함되며 데이터는 전혀
the other results you will get all the orders and the data is not
2:58:20
결합되지 않습니다. 그래서 이것이 두 개의
combined at all so this is how you query two
2:58:23
테이블을 결합하지 않고 쿼리하는 방법입니다. 이제 우리는 첫 번째 조인 유형인 내부 조인에 대해 이야기할 것입니다. 여기서 우리는 두 테이블의 데이터를 결합하기 시작합니다. 자, 시작합시다.
tables without combining them so with that you are getting all the data without joining the tables now we're going to start talking about the first type of join the inner join where we start combining the data from two tables so let's go
2:58:39
좋아요, 그럼 내부 조인이 정확히 무엇인가요? 이 유형은 두 테이블에서 일치하는 행만 반환합니다.
Okay, so now what is exactly an inner join? So this type gonna return only the matching rows from both tables.
2:58:46
즉, 출력에서 일치하는 행만 볼 수 있습니다. 그럼 왼쪽 테이블에서 무엇이 필요할까요?
So that means we will see in the output only matching rows. So now what do we need from the left table?
2:58:51
우리는 일치하는 데이터만 원합니다. 그래서 A의 전체 원을 얻지 않을 것입니다.
We want only the matching data. So we will not get the whole circle of A.
2:58:55
우리는 테이블 B와 겹치는 부분만 얻습니다.
We will get only where we have an overlapping with the table B.
2:58:59
그래서 A의 데이터는 테이블 B에 존재할 때만 보고 싶습니다. 그럼 테이블 B에서 무엇이 필요할까요?
So we want to see the data from A only if it exists in the table B. And now what do we need from the table B?
2:59:06
정확히 같은 것, 일치하는 데이터만. 즉, B의 모든 데이터를 보고 싶지 않습니다.
Exactly the same thing, only the matching data. So that means I don't want to see all the data from B.
2:59:11
A 테이블과 일치하는 B의 데이터만 보고 싶습니다, 왼쪽 측면에서.
I want to see only the data in B that has a match from the table A, from the left side.
2:59:16
그렇게 하면 두 테이블에서 일치하는 데이터만 얻을 수 있습니다. 이제 SQL에서 그것을 어떻게 작성할 수 있는지 봅시다.
And with that, you will get only the matching data from both tables. Now let's see how we can write that in SQL.
2:59:23
그래서 일반적인 쿼리입니다. 항상 선택으로 시작합니다. 예를 들어, 모든 열을 선택합니다.
So it is a usual query. And always we start with a select. So we select, for example, all the columns from.
2:59:28
그리고 여기에서 테이블 이름을 지정합니다. 그래서 A가 될 것입니다. 지금까지는 새로운 것이 없습니다.
And here we specify the table name. So it's going to be A. So, so far, nothing new.
2:59:33
하지만 이제 같은 쿼리에서 테이블 B도 추가하고 싶습니다.
But now we want to add as well the table B in the same query.
2:59:35
그렇게 하려면 조인이라는 키워드를 사용하고 테이블 B, 즉 테이블 이름을 말합니다.
In order to do that, we use the keyword join and then we say table B, the name of the table.
2:59:41
SQL에는 다양한 조인 유형이 있으므로, 조인 키워드 앞에 조인 유형을 지정할 수 있습니다.
And since we have like different types of joins in SQL, you can specify the type of the join before the keyword join.
2:59:49
아무것도 지정하지 않으면 기본 유형은 내부 조인입니다.
And if you don't specify anything, the default type is inner join.
2:59:52
기본값을 건너뛰는 것을 좋아하지 않는데, 프로젝트에서는 그렇지 않을 수 있습니다.
But my friends, the best practices is always mention the type.
2:59:56
모두가 기본값을 알고 있는 것은 아니므로 건너뛰지 마세요.
I don't like to skip the defaults because in projects maybe not
3:00:00
항상 유형을 지정하세요. 이제 우리가 할 일은
everyone is aware of the defaults so don't skip that
3:00:03
조인 앞에 내부 키워드를 넣는 것입니다.
always specify the type so now what we're gonna do we're gonna put the
3:00:06
그렇게 하면 두 테이블 간의 행을 처리하는 방법을 알게 됩니다.
keyword inner before the join and with that sql
3:00:09
아직 끝나지 않았습니다. SQL에 방법을 알려줘야 합니다.
gonna know how to deal with the rows between two tables but
3:00:12
테이블을 결합하는 방법과 함께 키워드 'on'을 사용합니다.
still we are not done there we have to tell sql how to
3:00:16
그 후 조인 조건을 지정하고, 두 테이블을 조인하기 위해서는 일치시킬 공통 열을 찾아야 합니다.
combine the tables and with that we use the keyword on
3:00:19
데이터를 올바르게 맞추기 위해서이며, 일반적으로 SQL에서는 키 또는
and after that you specify the join condition and as we learned in order to join two tables we have to find out a common column in order to match
3:00:27
ID입니다. 따라서 조건은 이와 같을 수 있습니다.
the data right and usually in sql they are the keys or
3:00:31
테이블 A의 키는 테이블 B의 키와 같아야 합니다.
ids so the condition can be like this the key from
3:00:34
이것이 조인 조건이며, 이를 사용하여
the table a must be equal to the key from
3:00:37
SQL은 데이터를 일치시키기 시작할 수 있습니다.
the table b so this is the join condition and using
3:00:40
왼쪽 테이블과 오른쪽 테이블에서 하나의 사항이 있습니다.
this join sql can go and start matching the data
3:00:43
테이블을 조인할 때 매우 중요한 점이 있습니다.
from the left table and the right table and there is one thing
3:00:46
쿼리에서 테이블의 순서를 이해해야 합니다.
that is very important while you are joining the tables you
3:00:49
내부 조인에서는 테이블의 순서가 중요하지 않습니다.
have to understand about the order of the tables in your query
3:00:53
A에서 시작하든 B에서 시작하든 상관없습니다.
now in the inner join the order of the tables doesn't
3:00:56
결과는 동일하게 나오기 때문입니다.
really matter so whether you start from a or you start from
3:00:59
두 테이블 모두 동일한 우선순위를 가지며, 어디서 시작하든 상관없습니다.
b it doesn't matter because you will get the same results both
3:01:02
A 조인 B 또는 B 조인 A에서 시작하든 상관없습니다.
of the tables has the same priority and it doesn't matter where
3:01:05
정확히 동일한 결과를 얻을 것입니다.
we start whether we say from a join b or we say
3:01:09
내부 조인에서는 순서에 대해 걱정할 필요가 없습니다.
from b join a we will get the exact same results
3:01:12
내부 조인에서는 순서에 대해 걱정할 필요가 없습니다
so in the inner join you don't have to worry about the order
3:01:15
이제 내부 조인에 대한 모든 것을 다뤘으니
of the tables so that's all about the inner join now let's
3:01:18
연습을 위해 스케일로 돌아가겠습니다. 자, 이제 다음
go back to scale in order to practice okay so now we have the following
3:01:21
작업이 있으며 모든 고객과 그들의 주문을 포함합니다
task and it says all customers along with their orders
3:01:24
주문을 한 고객만 해당됩니다
but only for customers who have placed an order
3:01:27
즉, 고객의 데이터가 필요하다는 뜻입니다
so my friends that means we need the data from the customers
3:01:31
두 테이블에서 주문 데이터를 가져와서 모든 것을
and from the orders from two tables and we have to put everything
3:01:34
하나의 결과로 만들어야 합니다. 즉, 두 테이블을 조인해야 합니다
in one results that means we have to join two tables now
3:01:38
단계별로 진행해 보겠습니다. 먼저 select star를 입력하겠습니다
let's go and do it step by step so we're gonna go and say select star
3:01:41
고객 테이블에서 가져오고, 이제 주문과 조인해야 합니다
from customers and then we have to go and
3:01:44
조인 유형을 지정해야 합니다. 어떤 조인인가요?
join it with the order so we're gonna say join orders now
3:01:47
내부, 왼쪽, 전체 등입니다. 이는
you have to go and specify the joint type is it
3:01:50
작업에 따라 다릅니다. 모든 고객을 원하지만
inner left full and so on well that's depend on
3:01:53
주문을 한 고객만 해당됩니다. 따라서
the task it says we want all customers but
3:01:56
조건이 필요합니다. 모든 고객의 데이터를 원하지 않습니다
only for customers who have placed an order so there
3:02:00
고객의 일치하는 데이터만 보고 싶습니다
is like condition right here we don't want to see everything from the
3:02:03
고객이 주문이 있을 경우에만
customer we just want to see only the matching data
3:02:06
주문 테이블에서 확인할 수 있습니다. 이를 위해 내부
only if the customers has an order in the
3:02:09
조인을 사용할 수 있습니다. 물론 이렇게 두면 같은 효과를 얻을 수 있지만
orders table and for that we can go and use the inner
3:02:12
내부 조인을 이렇게 지정하겠습니다. 명확하게 하기 위해서입니다
join of course if you can leave it like this you will get the same effects but
3:02:15
내부 조인에 대해 이야기하고 있다는 것을 분명히 하기 위해서입니다
i'm gonna go and specify it like this inner join just to make
3:02:18
조인 조건을 지정해야 하므로
it clear we are speaking about the inner join and after that
3:02:21
고객과 주문 간의 공통 열을 찾아야 합니다
we have to go and specify the join condition so we have to
3:02:24
보통 이렇게 합니다. 두 테이블을 탐색합니다
go and find a common column between the customers and the orders
3:02:27
그래서 고객 테이블에서 모든 것을 선택하겠습니다
so how i usually do it i go and explore both of the tables
3:02:31
그래서 저는 고객으로부터 모든 것을 선택할 것입니다.
so i'm gonna go and select everything from customers and
3:02:34
주문으로부터 모든 것 또한 선택할 것입니다.
as well everything from the orders so let's go and excuse now we're gonna start searching where do we have a common column
3:02:42
이 두 테이블 간의 공통 열을 검색할 것입니다.
between those two tables so we have the from the first table
3:02:45
첫 번째 테이블에서
first name country score and you don't find any of those
3:02:49
이름, 국가, 점수와 같은 정보는 찾을 수 없습니다.
informations in the second table the only one is the
3:02:52
두 번째 테이블에서 유일한 정보는
id so the id of the customer and the id of
3:02:55
고객의 ID입니다.
the customer you can find it in the orders the second column
3:02:58
여기서 이 두 테이블 간의 공통 열입니다.
here so this is the common column between those two tables
3:03:01
데이터베이스에서 우리는 정확히 ID를 생성합니다.
and usually in databases we create ids exactly for
3:03:04
테이블을 연결하기 위해서입니다.
this in order to connect tables so it's really rarely that we're going to use like a country or score or first name
3:03:11
테이블을 결합하기 위해 우리는 일반적으로 ID를 사용합니다.
order to join tables we usually use the ids so
3:03:14
우리의 쿼리로 돌아가서 이 두 열을 사용합시다.
let's go back to our query and use those two columns so
3:03:17
고객의 ID와 같을 것입니다.
it's going to be the id from the customers equal to
3:03:20
그것으로 조건이 설정되었습니다.
the customer id so that's it with that we have the condition
3:03:23
우리는 유형을 결정했고 실행할 수 있습니다.
we have decided on the type and we can go and execute
3:03:27
지금 우리는 세 명의 고객만 얻고 있습니다.
it now you can see we are getting only three customers
3:03:30
내부 조인을 적용하지 않으면
right if you don't apply the inner join we can
3:03:33
우리는 다섯 명의 고객이 있다는 것을 볼 수 있습니다.
see that we have five customers so that means actually we have two customers without any orders any matching data
3:03:40
이제 고객의 열뿐만 아니라
from the other table and as well you can see very nicely we
3:03:43
주문 측의 모든 열도 있습니다.
have now not only the columns from the customers but
3:03:46
그것으로 데이터를 결합했습니다.
as well all the columns from the orders side by side
3:03:49
이렇게 하면 작업을 해결했습니다.
so with that we have combined the data and as well with that we have solved
3:03:53
좋은 관행이 아닙니다.
the task but we will not leave our query like this because it is
3:03:56
선택해야 할 것은 정말 의미 있는 열입니다.
not really good practices what you have to do is to go and select
3:03:59
필요 없는 많은 열이 있을 것입니다.
only the columns that really make sense in our query because
3:04:02
우리의 쿼리에서 정말 의미 있는 열만 사용하세요. 왜냐하면
in many cases in your tables you will have a lot of columns that is not needed like for example if you check here you see we have the customer id here
3:04:09
여러분의 테이블에는 필요 없는 열이 많기 때문입니다. 예를 들어, 여기에서 고객 ID가 있습니다.
and as well the customer id over here so it's like repetition
3:04:12
그리고 여기에도 고객 ID가 있어서 반복됩니다.
and it's enough to see it only once so what you have to do is
3:04:15
한 번만 보면 충분하니, 여러분이 해야 할 일은
to go and pick few columns that you want for example
3:04:18
원하는 몇 개의 열을 선택하는 것입니다. 예를 들어,
i'm going to start with the id maybe the first name and that's
3:04:22
먼저 ID와 이름을 시작하겠습니다. 그리고 그게
all from the first table let's go and get the order id and
3:04:25
첫 번째 테이블에서 가져온 모든 것입니다. 이제 주문 ID를 가져오고
i don't want the customer id again so from the second table i'll get as well the sales so let's go and execute it and with that you can see very nicely the customer's name and their orders with the sales.
3:04:36
다시 고객 ID는 원하지 않으니, 두 번째 테이블에서 매출도 가져오겠습니다. 이제 실행해 보세요.
And now comes something very important. Sometimes if you have two tables, you might have columns that having the same names.
3:04:42
그렇게 하면 고객의 이름과 그들의 주문 및 매출을 아주 잘 볼 수 있습니다.
Like imagine the order ID in the table orders, it's called ID. So that means we have the same name in both tables.
3:04:49
이제 매우 중요한 것이 있습니다. 두 개의 테이블이 있을 경우, 같은 이름의 열이 있을 수 있습니다.
And this can make SQL very confused. And you will get an error tells you, I really don't know what do you mean with the ID?
3:04:54
이것은 고객 테이블에서 온 것인가요, 아니면 주문에서 온 것인가요?
Is it from the table customers or from the orders?
3:04:57
그래서 우리는 SQL에게 이 열이 어떤 테이블에서 왔는지 정확히 알려줘야 합니다.
So we have to tell SQL exactly from which table did this column come from.
3:05:02
그래서 SQL에서는 그렇게 하려면, 열 이름 앞에 테이블 이름, 즉 고객을 다시 쓰고 점을 찍습니다.
So in SQL, in order to do that, what we do before the column name, you write again the table name, the customers, and then you make a dot.
3:05:10
이제 우리는 SQL에게 이 열, 즉 ID가 고객 테이블에서 왔음을 알려주고 있습니다.
And now we are telling SQL this column, the ID, it comes from the table customers.
3:05:15
SQL은 혼란스러워하지 않을 것입니다. 그리고 고객 테이블에서 ID를 가져올 것입니다.
And SQL will not be confused about it. And it's going to go and get the ID from the customers.
3:05:20
두 번째 ID의 경우, 여기로 가서 주문. ID라고 말하기 전에 역시 그렇게 할 수 있습니다.
And for the second ID, you can go over here and as well before you say orders dot ID.
3:05:25
그래서 SQL은 알 수 있습니다, 알겠어요, 이 ID는 주문에서 오고 다른 하나는 고객에서 온 것입니다.
So that SQL knows, okay, this ID come from the orders and the other one comes from the customers.
3:05:31
특히 테이블을 조인할 때는 각 열에 테이블을 항상 지정하는 것이 좋은 습관입니다.
And it is always good practice, especially if you are joining tables to always assign for each column a table.
3:05:37
왜냐하면 시간이 지나면 쿼리를 열었을 때, 판매가 고객에서 오는 것인지 주문에서 오는 것인지 알 수 없기 때문입니다.
Because after a while, if you open your query and you see, okay, the sales, does the sales come from the customers or the orders?
3:05:43
열 목록이 길면 정말 혼란스러워질 것입니다.
And if you have a long list of columns, it's going to be really confusing.
3:05:46
그래서 항상 각 열에 테이블 이름을 지정하는 것이 최선의 방법으로 간주됩니다, 특히 조인을 할 때는 더욱 그렇습니다.
So that's why we consider it best practices if you always assign for each column the table name, especially if you are doing joins.
3:05:54
이렇게 될 수 있습니다. 하지만 물론 하나의 테이블만 있다면 모든 열과 선택이 이 테이블에서 온 것이라는 것은 분명합니다.
So it can be like this. But of course, if you have like only one table, it's clear that all the columns and the select comes from this table.
3:06:01
하지만 여기서는 여러 테이블을 다루고 있으므로 이렇게 보여주는 것이 좋습니다. 그리고 물론 여기에는 ID가 없습니다. 우리는 주문 ID가 있습니다.
But since here we are dealing with multiple tables, it is good to show it like this. And of course, here we don't have the ID. We have the order ID.
3:06:06
조인 조건에서도 마찬가지입니다. 여기서의 ID는 고객에서 오고 고객 ID는 주문에서 옵니다.
And the same thing for the join condition. So the ID from here comes from the customers and the customer ID come from the orders.
3:06:15
그래서 이제 모든 사람이 어떤 열이 어떤 것에서 왔는지 명확해졌습니다.
so now it is clear for everyone which column come from which
3:06:18
이제 모든 사람이 어떤 열이 어떤 테이블에서 왔는지 명확해졌습니다.
table but now you might say you know what each time i have to write the customers
3:06:21
이것은 매우 긴 이름이며, 실제 프로젝트에서는
this is very long name and sometimes in real projects you're
3:06:25
정말 긴 이름을 가진 테이블을 보게 될 것입니다.
gonna see tables that has really long name and it's
3:06:28
각 열 앞에 추가하는 것이 정말 귀찮을 것입니다.
gonna be really annoying to add it each time before each column right so
3:06:31
그 대신에 우리는 별칭을 지정할 수 있습니다.
instead of that we can go and assign aliases for
3:06:35
테이블뿐만 아니라 열에도 별칭을 지정할 수 있습니다.
the tables not only for the columns so usually we go over here and say as and maybe you can go and use only one
3:06:41
첫 번째 문자 C와 같은 문자로 바꿀 수 있습니다.
character like the first character C and now instead of
3:06:44
고객을 말하는 대신 여기서 C라고 말할 수 있습니다.
saying customers you can go over here and say C the same thing
3:06:47
두 번째 열에서도 같은 방식으로 사용할 수 있습니다.
for the second column and as well over here and you can use
3:06:50
이제 쿼리의 모든 곳에서 C를 사용할 수 있습니다.
now the C in everywhere in your query the same thing
3:06:53
주문에 대해서는 여기서 '모두'라고 말할 수 있습니다.
for the orders you can go over here and say as all and now instead
3:06:56
주문에 대해 당신이 말하는 모든 것
of orders you say all on
3:07:00
여기서 지금 이 두 열이 고객을 의미하는 C에서 온 것임을 쉽게 볼 수 있습니다. 그리고 이 두 열은 주문을 의미하는 O에서 온 것입니다. 이것들은 SQL에서 테이블을 함께 조인할 때의 모범 사례입니다.
here and now it is very easily to see those two columns comes from the C that means the customers and those two columns comes from the O the orders Those are the best practices as you are joining tables together in SQL.
3:07:12
물론, 그렇게 해서 우리는 작업을 해결했습니다. 테이블의 순서에 대해서는 어디서 시작하든 상관 없습니다.
And of course, with that, we have solved the task. And about the order of the tables, it doesn't matter where do you start.
3:07:17
예를 들어, 여기서 주문을 가져와서 조인에 넣고 from에서 주문을 가져옵니다.
So, for example, if you take the orders here and put it in the join and get the orders in the from.
3:07:23
그래서 저는 테이블을 전환하고 실행했습니다. 그러면 정확히 동일한 결과를 얻을 수 있습니다.
So I just switch the tables and execute it. You will get the exact same results.
3:07:28
따라서 두 테이블 간의 내부 조인을 수행할 때 테이블의 순서에 대해 걱정하지 마십시오.
So if you are doing inner join between two tables, don't worry about the order of the tables.
3:07:32
좋습니다. 이제 SQL이 내부 조인을 정확히 어떻게 실행하는지 이해해 봅시다. 좋습니다. 다시 여기 우리의 쿼리가 있습니다.
OK, so now let's go and understand exactly how SQL executed the inner join. OK, so now again, here we have our query.
3:07:39
그런 다음 고객과 주문이라는 두 개의 테이블이 있습니다. 그리고 여기에서 데이터를 조인하는 ID가 있습니다. 이것은 고객 테이블의 ID입니다.
Then we have the two tables, customers and orders. And here we have the ID where we are joining the data. So this is the ID from the table customers.
3:07:46
그리고 이것은 주문에서 우리가 가진 고객 ID입니다. 이제 SQL이 이것을 어떻게 실행할 수 있는지 봅시다.
And this is the customer ID that we have in the orders. Now let's see how SQL can execute this.
3:07:51
그래서 우리는 ID와 이름을 보고 싶다고 말하고 있습니다. 따라서 고객 테이블에서 ID와 이름을 가져올 것입니다.
So we are saying I would like to see the ID and the first name. So we will get the ID, the first name from the table customers.
3:07:58
그리고 우리는 주문 테이블에서 주문 ID와 판매도 가져오고 싶습니다.
And we would like to get the order ID and as well the sales from the table orders.
3:08:04
따라서 우리의 결과는 이 네 개의 열에 초점을 맞출 것입니다. 이제 데이터는 내부 조인을 사용하여 이 두 테이블 간에 조인되어야 합니다.
So our result is going to focus on those four columns. Now the data should be joined between those two tables using the inner join.
3:08:10
SQL은 고객 테이블의 왼쪽 테이블에서 시작할 것입니다. 왜냐하면 우리는 고객에서부터라고 말했기 때문입니다.
And SQL gonna start from the left table from the customers. Because we say from customers.
3:08:15
그래서 왼쪽 테이블의 ID를 오른쪽 테이블과 일치시키기 시작할 것입니다.
So it's gonna start matching the ID from the left table with the right table.
3:08:19
그래서 왼쪽 테이블의 ID와 오른쪽 테이블의 ID를 매칭하기 시작할 것입니다.
So it's gonna say okay is there a match from the first record from the first order? Well yes it is the same ID.
3:08:26
그리고 SQL은 그 조건이 충족되었다고 말할 것입니다. 우리는 데이터를 볼 수 있습니다.
And then SQL gonna say okay that condition is fulfilled. And we are allowed to see the data.
3:08:31
그래서 데이터가 출력에 표시될 것입니다.
So the data will be presented in the output.
3:08:34
그래서 당신은 마리아의 ID와
so you can have the id maria and the
3:08:37
마리아의 주문 ID와 이 주문의 판매를 가질 수 있습니다.
order id from maria and the sales of this order
3:08:40
그래서 매칭이 이루어지면 두 번째 레코드로 넘어갈 것입니다.
so there is a match then is going to go to the second record
3:08:44
우리는 세 번째에서 매칭이 없으므로 별로 없습니다.
well we don't have a match the third we don't have much
3:08:47
마지막 것에 대해서도 마찬가지로 우리는
and so on for the last one so we have only one match for
3:08:50
이 ID는 다시 고객에게 가서
this id then is going to go again to the customers and
3:08:53
두 번째 것을 선택하고 첫 번째 주문과 다시 매칭을 시작합니다. 매칭이 있는지 확인하고 두 번째로 넘어갑니다.
pick the second one and start matching again with the first order do we have a match we'll know then we'll go to the second well now we have a match so is going to be
3:09:02
조건이 충족되어 기쁩니다. 우리는
happy the condition is fulfilled and we will see the
3:09:05
결과를 볼 것입니다. 우리는 첫 번째 이름과 주문도 볼 것입니다.
results so we're gonna see the first name and as well the order
3:09:08
이 고객에 대한 정보를 출력에서 볼 것입니다.
information for this customer in the output it's gonna
3:09:11
계속 검색할 것입니다. 여기서도 매칭이 없습니다.
keep searching so we don't have a match as well here so
3:09:15
이제 세 번째 고객에 대해서도 마찬가지입니다.
that's it now for the third customer as well from the
3:09:18
두 번째와 세 번째로 매칭을 시작합니다.
start their match no to the second to the third
3:09:21
여기에서 매칭이 이루어지므로 이 정보를 보여줄 것입니다.
and here we have a match so it's gonna go and show this informations since
3:09:25
세 번째 고객 조지와 이 고객의 주문 ID와의 매칭이 있습니다.
there is a match so the customer three george with the order from this customer order id and the
3:09:32
출력에서 판매도 포함됩니다. 이제 계속 진행할 것입니다.
sales as well in the output now it's gonna go and keep continuing
3:09:35
검색을 진행하는데, 이스라엘에서는 매칭이 없습니다.
the search well we don't have any match then israel
3:09:38
네 번째 고객에게 가서 매칭을 시작합니다.
gonna go to the fourth customer and start matching do we have
3:09:41
여기 ID가 있습니다. 매칭이 있습니까? 아니요, 그러면
here an id do we have here a match well no then the
3:09:44
두 번째, 세 번째, 네 번째 주문이 없습니다.
second third and fourth we don't have any order
3:09:47
이 ID에 대해서는 매칭이 전혀 없으며, 우리는
for this id there is no match at all and since we are
3:09:50
내부 조인을 말하고 있으므로 이스라엘은 이 고객의 데이터를 결과에 표시하지 않습니다.
saying inner join then israel will not allow to show the data of this customer in the results there is no match and israel gonna totally ignore this customer
3:10:00
마지막으로 가서 이것을 일치시키기 시작할 것입니다.
we're going to go to the last one and start as well matching this
3:10:03
주문과 일치하는 ID가 없으므로
id with the orders well there is no match as
3:10:06
SQL은 이 사용자를 결과에서 제외할 것입니다.
well sql gonna go and exclude this user from the results
3:10:09
내부 조인이 어떻게 작동하는지 정확히 보여줍니다.
so this is exactly how the inner join works it
3:10:12
왼쪽에서 시작하여 데이터와 일치시키기 시작합니다.
starts on the left side and start matching the data on the
3:10:15
오른쪽에서만 일치하는 경우 결과가 표시됩니다.
right side and only if there is much the result gonna be presented
3:10:19
출력에서 이러한 결과를 얻는 이유입니다.
in the output and this is exactly why we are getting these results
3:10:22
테이블을 조인하는 이유를 보면
and how the inner join works so now if you look again to
3:10:25
여러 테이블을 재조합하기 위해 내부 조인을 사용할 수 있습니다.
the reasons why we are joining tables we can say we can use
3:10:28
여러 테이블을 하나의 큰 그림으로 만들기 위해
the inner join in order to recombine the multiple
3:10:31
내부 조인을 사용하여 데이터를 필터링할 수 있습니다.
tables into one big picture so the first use case
3:10:34
일치하는 데이터만 표시한다고 말하고 있습니다.
and as well we can use the inner join in order to filter
3:10:37
데이터를 필터링하고 존재 여부를 확인합니다.
the data so since we are saying only the matching data that
3:10:41
다른 테이블의 레코드 존재 여부를 확인합니다.
means we are filtering the data we are checking the existence
3:10:44
여러 테이블의 데이터를 결합하기 위해 내부 조인을 사용할 수 있습니다.
of the records in another table so you can use
3:10:47
필터링 목적으로만 사용할 수 있습니다.
inner join either to combine data from multiple tables or
3:10:50
행의 존재 여부를 확인하기 위해 사용됩니다.
you can use it as well only for filtering purposes only to
3:10:53
내부 조인의 두 가지 사용 사례입니다.
check the existence of your rows so this is usually the two
3:10:56
내부 조인에 대한 모든 것입니다.
use cases of inner all right so that's all about the first type
3:10:59
다음은 왼쪽 조인에 대해 이야기할 것입니다.
the inner join next we're going to talk about the left join
3:11:03
왼쪽 테이블의 모든 행을 반환합니다.
so we're going to focus on the left side so let's go okay
3:11:09
오른쪽 테이블에서 일치하는 행만 반환합니다.
so now what is exactly left join this type gonna return
3:11:13
왼쪽 테이블에서 필요한 것을 다시 살펴보면
all the rows from the left table and only
3:11:16
왼쪽 테이블에서 필요한 것을 확인합니다.
the matching from the right table so now if you look again to
3:11:19
모든 행을 보고 싶습니다.
our two circles a and b what do we need from the left table
3:11:22
모든 것을 보고 싶습니다. 모든 행을
we want to see everything all the rows all
3:11:25
데이터를 보려면 전체 원을 얻어야 합니다.
the data so that means we will get a full circle and
3:11:28
이제 오른쪽 테이블에서 일치하는 것만 가져오고 싶습니다.
now from the right table we want to get only the matching
3:11:32
테이블 B의 모든 것을 보고 싶지 않습니다. 테이블 A와 일치하는 레코드만 보고 싶습니다.
data so that means we don't want to see everything from the table b we want to see only the records that has matched to the table a so that means my friends
3:11:41
왼쪽 테이블이 더 우선합니다. 이것이
the left table has here more priority this is the
3:11:44
데이터의 주요 출처입니다. 우리는 아무것도 놓칠 수 없습니다.
primary source of your data the main source we cannot
3:11:47
모든 데이터를 보고 싶지만
miss anything this is very important we want to see all the data but
3:11:50
테이블 B는 데이터의 보조 출처입니다.
from the table b it is a secondary source of data and
3:11:53
추가 데이터를 얻기 위해서만 조인하고 싶습니다.
we are joining it only to get an additional data so i don't
3:11:57
모든 것을 원하지 않습니다. 왼쪽 테이블과 일치하는 데이터만 원합니다.
want everything i want only the data that has matched to the left table so this is what we mean with a left join now if you look to the syntax it's going to be very similar to the inner
3:12:06
왼쪽 테이블 A에서 시작합니다.
join so we start from the left table the a then we
3:12:09
오른쪽 테이블 B를 왼쪽 조인이라고 말하고
say left join the right table b and then the same
3:12:12
키를 사용하여 조건을 설정합니다.
condition using keys so here we just switch the type
3:12:15
여기서 테이블의 순서에 매우 주의해야 합니다.
instead of inner we have now left but now here with the syntax
3:12:18
이제 올바른 테이블에서 시작해야 합니다.
we need to be very careful the order of the tables
3:12:21
왼쪽 테이블을 정확히 언급해야 합니다.
now is very important you have to start from the correct
3:12:24
FROM 절에서 왼쪽 테이블을 언급하고 오른쪽 테이블과 조인합니다.
table so you have to mention the left table exactly in
3:12:28
이렇게 하지 않으면 모든 데이터를 얻지 못합니다.
the from clause and then you join it with the right table so in the join you have to specify the right table if
3:12:34
A에서 모든 데이터를 얻지 못하고 예상한 결과를 얻지 못합니다.
don't do it like this then you will not get all the data from
3:12:38
이것이 왼쪽 조인을 의미합니다. 다시 스케일로 돌아갑니다.
a and you will not get the results that you are expecting so
3:12:41
연습을 위해 이제 다음 작업이 있습니다.
this is what we mean with the left join let's go back to scale in order to
3:12:44
모든 고객과 그들의 주문을 가져오고
practice all right so now we have the following task it says get
3:12:47
주문이 없는 고객도 포함해야 합니다.
all customers along with their orders including those
3:12:51
모든 것을 보고 싶습니다. 고객 테이블에서 일치하는 데이터와 일치하지 않는 데이터를.
without orders so again here we need the data from two tables the customers and orders and we want everything in one result so that means we have to go and join the data and And now the task says includes those without orders.
3:13:03
이것이 고객 테이블에서 모든 것을 보고 싶다는 의미입니다.
So that means I want to see everything, the matching data and unmatching data from the table customers.
3:13:09
우리의 쿼리를 보면, 모든 데이터를 얻지 못하고 있으니 작동하지 않습니다, 맞죠?
And by looking to our query, this is not working because we are not getting everything, right?
3:13:13
우리는 주문 테이블과 일치하는 고객만 얻고 있습니다. 그리고 이것은 물론 작업을 수행하지 못하고 있습니다.
We are getting only the customers that has match in the table orders. And this is not, of course, fulfilling the task.
3:13:20
이제 작업을 읽으면, 여기서 주요 테이블은 고객이라는 것을 이해할 수 있습니다.
So now if you read the task, you can understand the main table here is the customers.
3:13:25
우리는 모든 주문을 보고 놓치는 것이 아닙니다.
We are not speaking about to see all the orders and not missing any order.
3:13:29
그리고 여기서의 주문은 추가 정보를 위한 것이므로 이제
and the orders here is only for additional informations so now in
3:13:32
고객 데이터가 손실되지 않도록 우리는 고객 테이블에서 시작합니다.
order to not lose any data for the customers we make sure
3:13:35
즉, 이제 고객은 왼쪽에 있고 그 후에는
we start from the table customers so that means now
3:13:38
내부 조인을 사용하는 것은 이 작업에 좋지 않으므로 우리는 말할 것입니다.
the customers on the left side and now after that instead of
3:13:41
왼쪽 조인으로, 이를 통해 고객의 모든 데이터를 얻을 수 있습니다. 이제 우리는 주문을 라이브 조인하고 조건은 이렇게 유지됩니다.
inner join this is not good thing for this task we're gonna say
3:13:45
이것이 두 테이블을 연결하는 방법입니다. 그래서 사실 그것은
left join and with that we guarantee we will get all the data from the customers now we say live join orders and of course the condition gonna stay like this this
3:13:53
이제 실행해 보겠습니다. 그리고 이제 결과를 보면
is how we are connecting the two tables so actually that's
3:13:57
우리는 이제 다섯 명의 고객이 있다는 것을 알 수 있습니다.
it let's go and execute it and now by looking to the
3:14:00
주문을 하지 않은 고객들도 보이니 마틴을 볼 수 있습니다.
result you can see that we have now five customers even
3:14:03
그리고 피터는 주문 ID가 없습니다.
the customers that didn't place any orders so you can see martin
3:14:06
즉, 그들은 아무것도 주문하지 않았습니다. 그리고 보시다시피
and peter they don't have any order id so
3:14:09
그것은 그들이 아무것도 주문하지 않았다는 것을 의미하며, 보시다시피
that means they didn't order anything and as you can see
3:14:12
isql은 일치하는 것이 없을 때 null을 보여주고 있습니다. 그래서 우리는 이제 이 작업을 해결했습니다. 친구들, 제가 말씀드린 것처럼 테이블의 순서가
isql is showing us nulls when there is no match so with that we have solved the task now my friends one more thing as i told you the order of the tables
3:14:20
매우 중요합니다. 왜냐하면 고객이 이제
is very important because the customer is now the
3:14:23
왼쪽 테이블이기 때문입니다. 왜냐하면 거기에서 시작하고 두 번째 테이블은
left table because you start from it and the second table
3:14:26
주문이 오른쪽 테이블입니다. 이제 만약 당신이 그것들을 바꾸면
the orders is the right table now if you go and switch them
3:14:30
이렇게 시작하므로 우리는 주문에서 시작하고
like this so we start from the orders and
3:14:33
그런 다음 고객과 조인하고 실행하면
then join it with the customers and you go execute it you
3:14:36
모든 고객을 얻지 못할 것이며, 물론 작업은 이제
will not get all the customers and of course the task is now not
3:14:39
해결되지 않았습니다. 그래서 보시다시피 테이블을 바꾸면 완전히 다른 결과를 얻고 있습니다. 시작하는 위치와 테이블을 조인하는 방법에 주의하여 원하는 효과를 얻으세요.
solved so as you can see you are getting now completely different results if you go and switch the tables so be careful where you start and how you join the tables in order to get the effects that you want.
3:14:49
좋습니다, 이제 모든 것을 예전처럼 되돌리겠습니다. 이제 SQL이 이 쿼리를 정확히 어떻게 실행했는지 이해해 봅시다.
Alright, so now I'm going to put everything back like before. Now let's go and understand how SQL exactly executed this query.
3:14:56
좋아요, 이제 모든 것을 이전처럼 되돌리겠습니다. 이제 SQL이 이 쿼리를 어떻게 실행하는지 이해해 봅시다.
Okay, so now again we have the data from customers and orders and this time we are doing
3:15:00
좋아요, 이제 다시 고객과 주문의 데이터를 가지고 있고 이번에는
the left join so now let's see how isql gonna do it so we're
3:15:03
왼쪽 조인을 하고 있으니 이제 isql이 어떻게 할지 봅시다.
gonna say okay we need the id and the first name and we will
3:15:07
좋아요, 우리는 ID와 이름을 필요로 하고
get that as well in the results and from the right table we need only
3:15:10
그것을 결과에 포함시킬 것입니다. 오른쪽 테이블에서는
those two informations the order id and the sales in
3:15:13
두 가지 정보, 즉 주문 ID와 판매량이 필요합니다.
the output so those are the columns that we need so now isql
3:15:16
출력에서 필요한 열이므로 이제 isql
in the left join can do it a little bit differently it can start as
3:15:19
왼쪽 조인에서는 조금 다르게 할 수 있습니다. 왼쪽 테이블인 고객에서
well from the left table from the customers but this time isql
3:15:23
시작할 수 있지만 이번에는 isql이
gonna go and immediately put the result in
3:15:26
결과를 즉시 출력에 넣을 것입니다.
the output without like trying to match anything and
3:15:29
매칭을 시도하지 않고
to check whether the data exists or not because it doesn't matter
3:15:32
데이터가 존재하는지 확인할 것입니다. 왜냐하면 상관없기 때문입니다.
scale not doing any validation whether the customer exists
3:15:35
고객이 존재하는지에 대한 검증을 하지 않기 때문에
in the orders since it's left join is going to show all the
3:15:38
왼쪽 테이블의 모든 데이터를 보여줄 것입니다. 그래서 체크는 없습니다.
data from the left table so there will be like no check
3:15:41
이제 다음 단계로 주문 ID와 판매량을 얻기 위해
but now as a next step in order to get the order id and the sales
3:15:45
isql이 검색을 시작할 것입니다. 여기서
is skill will start searching so it's going to go over here
3:15:48
이 ID를 가진 고객이 어디에 있는지 검색을 시작할 것입니다.
and start searching where do we have a customer with this
3:15:51
첫 번째 주문이 될 것이고 우리는
id well it's gonna be the first order we're gonna get the
3:15:54
주문 ID와 판매 정보를 얻을 것입니다.
order id and as well the sales informations and
3:15:57
그것을 출력에서 볼 수 있을 것입니다. 첫 번째는 여기까지입니다.
we will see that in the output so that's it for the first one
3:16:00
이제 두 번째 행으로 가고 같은 일이 일어날 것입니다.
now it's gonna go to the second row and the same thing gonna happen
3:16:03
즉시 SQL이 결과를 출력에 넣을 것입니다.
immediately the sql gonna go and put the result in
3:16:06
체크 없이 그리고 주문 데이터를 얻기 위해 이 ID를 검색할 것입니다. 두 번째 행에 주문 ID와 판매량이 있습니다.
the output without checking anything and then in order to get the order data it will start searching for this id so we have it here in the second row we have the order id and the sales
3:16:17
그 결과를 출력에 넣을 것이므로
and it's going to put those results to the output so that's
3:16:21
세 번째는 즉시 모든 것을 출력에 넣을 것입니다.
it for the third one immediately gonna put everything
3:16:24
출력에 넣고 검색을 시작할 것입니다.
in the output and then start searching for
3:16:27
이 주문은 사용자 ID 번호 3에 속합니다.
orders with this id we have it over here
3:16:30
지금까지 내부 조인과 같은 결과를 얻고 있지만,
so this order belongs to the user id number three so
3:16:34
아직 끝나지 않았습니다. 차이를 정확히 계산해 보겠습니다.
far we are getting the same result as the inner join but we are not
3:16:37
우리는 아무것도 없습니다. 이번에는 SQL이 ID 번호 4를 제외하지 않을 것입니다.
done yet now exactly count the difference so i'm gonna go and get martin and put it immediately in the output and start searching for an order with this id so So do we have any order with the ID number four?
3:16:48
그것을 남겨둘 것입니다. 하지만 SQL에서는 일치하는 것이 없으면 출력에 무언가가 있어야 합니다.
Well, we don't have anything. This time SQL, of course, will not go and exclude the ID number four.
3:16:54
SQL은 이렇게 출력이 null이 될 것이라고 말할 것입니다. 우리는 모릅니다.
It's going to leave it. But in SQL, if there is no match, we still have to have something in the output.
3:16:59
판매에 대해서도 같은 일이 발생합니다. 왼쪽 조인에서는 일치하지 않으면 null을 볼 수 있습니다.
So SQL going to go and say the output going to be null like this. We don't know. It is unknown.
3:17:06
SQL은 결과를 즉시 출력에 넣고 주문을 검색하기 시작할 것입니다.
And the same thing for the sales. So in the left join, if there is no match, you will see nulls. Same thing for the next customer for better.
3:17:14
ID 번호 5에 대한 것이 있습니까? 우리는 아무것도 없습니다.
So SQL will go and put the result immediately in the output and then start searching the orders.
3:17:20
그래서 ID 번호 5에 대한 것이 있습니까? 우리는 아무것도 없습니다.
So do we have anything for the ID number five? We don't have anything.
3:17:24
그래서 SQL은 출력에 null을 표시할 것입니다.
That's why SQL is going to go and present nulls as well in the output.
3:17:28
그래서 출력에서 null을 보았던 이유는 그 고객들이 주문이 없기 때문입니다.
And that's why you saw nulls in the output because those customers don't have any orders. So this is exactly the effect of the left join.
3:17:35
왼쪽 테이블의 모든 것을 얻고 오른쪽에서 일치하는 것만 얻습니다.
You will get everything from the left table and only the matching stuff on the right side. And if there is something not matching, you will get nulls.
3:17:42
그래서 그게 전부입니다. 이것이 왼쪽 조인을 실행하는 방법입니다.
So that's it. this is how scale execute the left
3:17:45
조인에 대한 이러한 사용 사례로 돌아가겠습니다.
join okay so now back to these use cases of joins if
3:17:48
왼쪽 조인에 대해 생각하면 재조합하는 데 사용할 수 있습니다.
i think about left join i can use it in order to recombine
3:17:51
이 큰 그림을 만들기 위해 데이터를 재조합하는 데 사용할 수 있습니다.
data in order to build this big picture and as well in the
3:17:54
추가 정보를 얻기 위해 다른 테이블을 사용합니다.
second use case where we use it in order to get an extra
3:17:58
주 테이블과 보조 테이블이 있습니다.
information from another table so we have a main table and
3:18:01
두 가지 사용 사례 모두에 대해 사용합니다.
secondary table so we use it for both use cases and
3:18:04
세 번째 사용 사례에서도 사용합니다.
as well in the third use case only with a twist that we're
3:18:07
왼쪽 조인의 정반대인 또 다른 유형이 있습니다.
gonna learn later so that's all about the left join now we have
3:18:10
우리는 오른쪽 조인을 가지고 있습니다.
another type that is exactly the opposite of the left join
3:18:13
이것이 의미하는 바를 이해해 보겠습니다.
we have the right join so now let's understand
3:18:16
이게 무슨 뜻인지 알겠어요
what this means okay
3:18:21
그래서 이제 정확히 오른쪽 조인이란 무엇인가요? 이것은
so now what is exactly right join this is the total opposite of
3:18:25
왼쪽 조인의 완전한 반대입니다. 그래서 이 유형은 모든 행을 반환합니다.
the left join so this type gonna returns all the rows
3:18:28
오른쪽 테이블에서 왼쪽 테이블의 일치하는 행만 반환합니다. 그래서 여기서 주요 테이블, 주요 초점은 오른쪽 테이블입니다. 그래서 SQL은 당신에게
from the right table and only the matching from the left table so here the main table the main focus is the right table so sql gonna get you
3:18:37
테이블 B, 즉 오른쪽 테이블의 모든 행을 가져올 것입니다.
all the rows everything from the table b the right
3:18:40
하지만 왼쪽에서는 일치하는 데이터만 가져옵니다.
table but from the left side we will get only the matching
3:18:43
즉, 왼쪽에서는 오른쪽에 일치하는 데이터만 가져옵니다.
data so that means on the left side you will get only the
3:18:46
그리고 오른쪽 테이블이 주요 데이터 소스가 될 것입니다. 그래서 매우 중요한 테이블입니다. 하지만
data that has a match on the right side and
3:18:49
왼쪽 테이블은 그렇게 중요하지 않습니다. 당신은 단지 추가 데이터를 얻기 위해 그것을 조인하고 있습니다.
with that the right table gonna be the primary the main
3:18:53
그래서 다시 구문에 대해 말하자면, 그렇게 복잡하지 않습니다. 당신이 해야 할 일은
source of your data so it is very important table but the
3:18:56
조인 유형을 변경하는 것입니다. 그래서 왼쪽 대신 오른쪽 조인이라고 말합니다.
left table is not that important you are just joining it in
3:18:59
그리고 여기서 테이블의 순서가 매우 중요합니다.
order to get additional data so again about the syntax it's not that crazy all what you have to do is to change
3:19:05
왜냐하면 여기서 측면이 차이를 만들기 때문입니다. 그래서 우리는
the join type so instead of left you say right join
3:19:08
왼쪽 테이블 A에서 시작하고 그 다음에 오른쪽 조인으로
and again here the order of the tables is very important
3:19:12
테이블 B에 연결합니다. 그래서 왼쪽 조인과 매우 비슷하게 들립니다. 우리는
because the side here makes a difference so we start
3:19:15
단지 모든 것을 바꾸고 있습니다. 이제 연습하기 위해 스케일로 돌아가 보겠습니다. 알겠죠, 친구들? 그래서 이제 다음 작업이 있습니다. 그리고 그것은 모든 고객과 그들의 주문을 가져오라는 것입니다. 일치하지 않는
from the left table a and then right join it to
3:19:18
고객이 포함된 주문도 포함됩니다. 그래서 다시 고객과 주문이 있고 우리는 조인을 하고 있습니다. 하지만 여기 조건이 다릅니다.
the table b so it sounds very similar to the left join we are
3:19:21
우리는 모든 주문을 보고 싶습니다. 비록 일치하는 고객이 없더라도요.
just switching things now let's go back to scale in order to practice okay my friends so now we have the following task and it says get all customers along with their orders including orders without
3:19:32
그래서 저는 주문 테이블의 모든 것을 보고 싶습니다.
matching customers. So again we have the customers and the orders and we are doing the join. But here the condition is different.
3:19:39
그리고 고객 테이블은 여기서 단지 지원하고 돕는 역할만 합니다. 그래서 우리가 초점을 맞추고 있는 주요 테이블은 주문입니다.
We want to see all the orders even if they don't have a matching customer.
3:19:43
우리는 모든 것을 보고 싶고 고객에서는 일치하는 것만 보고 싶습니다. 그리고 현재 결과를 보고 있다면,
So that means I would like to see everything from the table orders.
3:19:46
우리는 단지 세 개의 주문만 보고 있죠? 맞죠? 하지만 원래 테이블로 돌아가면, 여기에서 네 개의 주문이 있다는 것을 볼 수 있습니다.
And the customers table here is only like supporting and helping. So the main table that we are focusing on is in the orders.
3:19:53
그래서 우리는 현재 이 쿼리를 사용하고 있으며, 모든 주문을 보지 못하고 있습니다. 그래서 이제 이 문제를 어떻게 해결할까요?
We want to see everything and from the customers only the matching. And if you are looking currently to the results.
3:20:00
You can see we are seeing only three orders, right? But in the original table, if you go back over here, you can see that we have four orders.
3:20:08
So we are currently using this query, not seeing all the orders. So now how are we going to solve it?
3:20:13
고객 테이블에서 시작하면, 왼쪽 조인 대신 오른쪽 조인을 사용할 것이라고 말할 수 있습니다.
If you start from the table customers, you can say, you know what, instead of left join, we're going to say right join.
3:20:19
그렇게 하면 주문 테이블의 모든 데이터를 보장할 수 있습니다.
And with that, you're going to guarantee you will get everything from the table orders.
3:20:24
하지만 이제 왼쪽 테이블인 고객은 그리 중요하지 않습니다.
But now the left table, the customers is not that important.
3:20:27
고객 데이터는 일치하는 경우에만 볼 수 있으므로 이렇게 오른쪽 조인을 수행합니다.
and you will see the data of the customers only if there is a match so doing the right join like this
3:20:32
일치 여부와 관계없이 모든 것을 볼 수 있습니다.
guaranteed to see everything whether there is match or no
3:20:35
이제 실행하면 오른쪽에서 주문 ID와 판매를 볼 수 있습니다.
match now if you go and execute it you can see on the
3:20:38
모든 주문과 왼쪽에서 ID와 첫 번째
right side the order id and the sales and we can see now all
3:20:41
이름을 보고 있으며 고객이 무엇인가를 주문한 경우에만 볼 수 있습니다.
the orders and on the left side the id and the first
3:20:44
알려지지 않은 고객의 주문에 대해서는
name we are seeing only the customers if they did order something
3:20:48
널 값이 나오므로 오른쪽 조인을 사용하여 작업을 해결했습니다.
and for the orders without a known customer we
3:20:51
이제 친구들, 이 작업을 해결하여 동일한 결과를 얻어야 합니다.
are getting nulls so with us you solved the task using the right join
3:20:54
정확히 같은 결과를 얻지만 왼쪽 조인만 사용할 수 있습니다.
so now my friends you have to go and solve this task to get the
3:20:57
이제 친구들, SQL에서는 항상 대안이 있습니다.
exact same results but you are allowed to use only the left join so you are not allowed to use the right join so now go pause the video solve the task and meet you soon
3:21:12
작업을 해결하는 방법이 있으므로 B에서 모든 데이터를 가져오고
now my friends in sql there is always alternatives on how
3:21:15
A에서 일치하는 것만 가져오고 싶다면 이렇게 할 수 있습니다.
to solve a task so now if you want to get all the data from b and
3:21:19
오른쪽 조인을 사용하여 우리가 했던 것처럼.
only the matching from a you can do it like we have done using
3:21:22
하지만 측면을 바꾸면
the right join but if you go and switch the sides
3:21:25
테이블 B를 왼쪽 테이블로 만들고 테이블 A를 오른쪽 테이블로 만들 수 있습니다.
and you make the table b as a left table and the table
3:21:28
물론 SQL에서 그렇게 할 수 있지만
a as a right table you can do that of course in sql but
3:21:31
조인 유형을 바꿔야 하므로 오른쪽 대신
you have to switch the join type so instead of right we
3:21:34
왼쪽을 사용해야 합니다. 이제 B 테이블이 왼쪽에 있으므로
have to use left now since the b table now on the
3:21:38
왼쪽에 있으며 순서를 바꿔야 하므로 B 테이블에서 시작하고
left sides and as well you have to switch the order so you start from the b table and then you say left join the a table and of course
3:21:46
A 테이블과 같은 조인 조건을 사용해야 합니다.
the same join condition and if you do that you will get the exact
3:21:49
그렇게 하면 정확한 결과를 얻을 수 있습니다.
same result as the left query so if you just switch
3:21:52
테이블을 바꾸고 조인 유형도 바꿉니다.
the tables and as well switch the join type
3:21:55
같은 결과를 얻을 수 있고 솔직히 말해서 친구들아
you can get the same results and to be honest my friends
3:21:58
오른쪽 조인을 좋아하지 않아, 지난 10년 동안 그랬어
i don't like the right join it's just in the less 10 years
3:22:02
나는 항상 테이블에서 시작한 다음
i always tend to start from a table and then use a
3:22:05
왼쪽 조인을 사용하고 내 관점에서 왼쪽 조인은 훨씬
left join and from my point of view the left join is way
3:22:08
오른쪽 조인보다 더 유명하고 나는 절대
more famous than the right join and i think i never
3:22:11
오른쪽 조인을 사용하는 쿼리를 사용한 적이 없어, 그래서 내 조언은
used a query where i'm using a right join so my advice
3:22:14
너는 항상 오른쪽 조인을 건너뛰고
for you always try to skip the right join and stick
3:22:17
왼쪽 조인에 집중해, 테이블의 순서와 쿼리를
with the left join just get the order of the tables and the query
3:22:20
올바르게 설정하면 같은 결과를 얻을 수 있어, 그래서 그걸로 대안을 알게 돼
correct and you will get the same results so with that you know an alternative
3:22:23
오른쪽 조인에 대해 이제 너가 해야 할 일은 가서
for the right join now all what you have to do is to go and switch the
3:22:27
왼쪽으로 바꾸는 거야, 이건 충분하지 않아 왜냐하면
right to left this is not enough because if
3:22:30
내가 실행하러 가면 이제 내가 해야 할 일은 가서
i go and execute it so now all what i have to do is to go and
3:22:33
테이블을 이렇게 바꾸는 거야, 그래서 우리는
switch the tables like this so we start from the
3:22:36
주문 테이블에서 시작해, 나는 모든 주문을 보고 싶어
table orders because i want to see everything from the orders
3:22:39
그리고 고객과 왼쪽 조인하고
and then left join it with the customers and
3:22:42
물론 여기서 아무것도 바꿀 필요 없어, 순서는 중요하지 않아 왜냐하면
of course we don't have to change anything here it doesn't matter the order because
3:22:45
여기서 중요한 것은 같은 연산자가 있다는 거야
we have an equal operator here what is very important here is
3:22:49
어디서 시작하느냐, 어떤 테이블인지
where you start from which table and what is the table
3:22:52
너가 조인하고 있는 테이블이야, 그래서 가서 실행하면
that you are joining with so if you go and execute it
3:22:55
정확히 같은 결과를 얻을 수 있어, 그래서 이제 모든 것을 보고 있어
you will get the exact same results so now i'm seeing all
3:22:58
주문을 놓치지 않고 오직
the orders i'm not missing anything and only the
3:23:01
일치하는 고객만 보고 있어, 나는 이 방법으로 해결하는 걸 선호해
matching customers and i prefer this way solving this
3:23:04
오른쪽 조인을 사용하는 대신, 좋아, 그래서 이게 전부야
task instead of using the right join all right so that's all about
3:23:07
오른쪽 조인에 대해 다음에는 모든 것을 결합할 거야, 우리는
the right join next we're gonna combine everything we're gonna
3:23:11
전체 조인에 대해 이야기할 거야, 그러니까 가자, 좋아
talk about the full join so let's go okay
3:23:17
그렇다면 풀 조인이란 정확히 무엇인가요?
so now what is exactly a full join if you use it sql
3:23:20
다시 말해 두 테이블의 모든 행을 반환합니다.
again returns everything all the rows from both tables
3:23:24
이제 왼쪽 테이블의 원을 다시 확인해 보겠습니다.
so now if you check again our circles from the left table
3:23:27
모든 행을 가져오고 전체 원을 얻고 싶습니다.
we want to get everything all the rows so you will get the whole
3:23:30
오른쪽 테이블에서도 모든 것을 가져오고 싶습니다.
circle and as well from the right table you want to get everything
3:23:33
모든 행, 전체 원을 가져오고 싶습니다.
all the rows the whole circle so with that you want to
3:23:36
일치하는 것과 일치하지 않는 모든 데이터를 가져옵니다.
get everything the matching the unmatching all
3:23:39
왼쪽과 오른쪽의 데이터, 이제 구문을 확인해 보겠습니다.
the data from left and right now let's check the syntax it's
3:23:42
매우 간단할 것입니다. 여기서 조인 유형은 풀 조인이 됩니다.
gonna be very simple the join type here gonna be a full join
3:23:45
풀 조인은 내부 조인과 매우 유사합니다.
and the full join it is very similar to the inner join you remember
3:23:49
테이블의 순서는 전혀 중요하지 않습니다.
the order of the tables is not important at all
3:23:52
여기에는 주 테이블과 보조 테이블이 없습니다.
so there is here no main table and secondary table both
3:23:55
테이블의 중요성과 쿼리에서 시작하는 위치는 상관없습니다.
of the tables are important and it doesn't matter in your query where you start you can start from a full join b
3:24:01
b에서 시작하든 a에서 풀 조인하든 동일한 결과를 얻습니다.
or you can start from b then full join a you will get
3:24:04
정확히 같은 결과를 얻습니다. 간단해 보이네요.
the exact same results it sounds simple let's go to sql
3:24:08
SQL로 가서 풀 조인을 연습해 보겠습니다.
and practice the full join all right so now we have the following task
3:24:11
모든 고객과 모든 주문을 가져오라고 합니다.
and it says get all customers and all orders
3:24:14
일치하는 것이 없어도 됩니다.
even if there is no match so now again we need the data from customers
3:24:17
일치하지 않는 경우라고 했지만, 말하지 않았습니다.
and orders but now of course which type we're gonna use
3:24:21
주문이나 고객에서 일치하지 않는 것이라고는 하지 않았습니다.
it says even if there is no match but it didn't say
3:24:24
이 작업에서 우리는 주문이나 고객에만 집중하지 않습니다.
no match from orders or customers so you can understand
3:24:27
두 가지 모두 똑같이 중요하며, 우리는 모두 필요합니다.
from this task we are not focusing only on the orders or the customers
3:24:30
데이터가 필요하다는 의미입니다. 왼쪽의 모든 데이터를 필요로 합니다.
both of them are equally important and we need all
3:24:33
오른쪽의 데이터도 필요하며, 이제 풀 조인을 사용할 수 있습니다.
the data so that means we need all the data from left all
3:24:37
여기에서 이 쿼리를 시작하고 있습니다.
the data from right and we can go and use that full join so now
3:24:40
우리는 여기서 고객을 시작으로 하는 이 쿼리를 가지고 있습니다.
we have this query over here we are starting from customers and
3:24:43
그런 다음 주문과 조인하지만 이제 왼쪽 대신 전체 조인이라고 말할 것입니다.
then joining to orders but now instead of having left we're gonna say full join so now let's go and just execute it now if you are looking to the left side you can see we are getting all the customers right so we we have our five customers.
3:24:55
이제 왼쪽을 보면 모든 고객을 얻고 있다는 것을 알 수 있습니다.
And if you are looking to the right, you can see all our orders.
3:24:59
그래서 우리는 왼쪽에서 모든 것과
so with that we have everything from left and everything
3:25:02
오른쪽에서 모든 것을 가지고 있으며 일치하는 데이터는 나란히 있습니다.
from right and the matching data is just side by side
3:25:05
결과에서 일치하는 데이터가 없으면 null을 얻습니다.
in the results and if there is no match we are getting nulls
3:25:08
그래서 실제로 우리는 작업을 해결했습니다.
so actually with that we have solved the task and again it doesn't matter
3:25:11
시작하는 방법은 상관없습니다. 주문에서 시작한 다음
how you start you can start from the orders and then join
3:25:14
고객과 조인하면 정확히 같은 결과를 얻을 수 있습니다.
it to the customers and you will get the exact same results so you are getting exactly the same data Now let's go and understand exactly how SQL executed the full join.
3:25:24
좋습니다. 다시 고객과 주문의 데이터와 전체 조인이 있습니다.
Okay, again, we have the data of the customers and the orders and our full join. So now SQL can identify those columns that we want to see in the results.
3:25:31
따라서 ID와 이름, 주문 ID 및 판매 정보를 출력으로 보냅니다.
So the ID and the first name, the order ID and the sales informations to the output.
3:25:37
이제 SQL은 왼쪽 테이블에서 시작할 수 있습니다.
Now SQL can start from the left table since it is started with the customers.
3:25:40
왼쪽 테이블의 모든 것을 가져와서 출력에 표시합니다.
SQL can take simply everything from the left table and present it in the output.
3:25:45
전체 조인이기 때문에 왼쪽에서 모든 데이터를 보고 싶습니다.
Since it is full join, we want to see all the data from the left side. and
3:25:48
이제 오른쪽 테이블에서 일치를 찾기 시작합니다.
now start searching for matches from the right table so let's
3:25:51
첫 번째 고객부터 시작하고 평소처럼
start with the first customer and as usual we will get the
3:25:55
첫 번째 고객의 주문을 얻습니다.
order from the customer number one and
3:25:58
두 번째 고객에 대해서도 같은 방식으로 진행합니다.
the same thing for the second customer we have as well here match
3:26:01
세 번째 고객에 대해서도 일치가 있으며
so we'll get as well it's like that left join and
3:26:04
주문이 없는 두 고객에 대해서는 null을 출력에서 얻습니다.
for the third one we have as well a match and we're gonna have
3:26:07
여기서도 같은 일이 발생하며 마지막 고객에 대해서도
it like this and since we don't have orders for those two customers we will get as well nulls in the outputs so SQL gonna market with null the same
3:26:16
두 고객에 대해 null을 얻고 이제
thing over here and as well for the last customer
3:26:19
물론 SQL은 여기서 멈추지 않을 것입니다.
so we will get nulls for those two customers and now
3:26:22
왼쪽 조인 효과가 발생합니다.
of course will sql will not stop here otherwise we will get a
3:26:25
이제 SQL은 오른쪽을 살펴보며 출력에 없는 주문을 찾기 시작합니다.
left join effect now sql gonna start looking at the right
3:26:28
출력에 없는 주문을 찾기 위해 오른쪽을 살펴보겠습니다.
side to find any order that is not in the output
3:26:31
SQL은 첫 번째 주문이 출력에 있는지 확인할 것입니다.
so sql gonna see okay the first order is in the output
3:26:34
두 번째 주문도 출력에 있으며 세 번째와
the second one is as well in the output the third and
3:26:38
네 번째 주문은 결과에 없으므로 SQL은 이 결과를 출력에 넣을 것입니다.
the fourth one is not in the results so sql gonna take this result and put it in the output so this order has no match at all from the left side and with that if you are looking to the right side you can see
3:26:49
SQL은 모든 주문을 가지고 있기 때문에 기쁠 것입니다.
SQL gonna be happy because we have all the orders from
3:26:52
오른쪽 테이블에서 SQL은 이렇게 두지 않을 것입니다.
the right table and of course SQL will not leave it like this
3:26:55
대신 SQL은 왼쪽에 null을 표시할 것입니다.
instead of that SQL gonna show nulls on the left side
3:26:59
그래서 ID가 없고 이름도 없으므로
so there is no id and there is no first name so this
3:27:02
이것이 우리가 이 결과를 얻은 정확한 이유입니다.
is exactly why we got this result and this is how
3:27:05
SQL이 전체 조인을 실행했습니다. 이제 사용 사례를 살펴보겠습니다.
SQL executed that full join okay so now if you are looking for the use cases I can say you can use the full join in
3:27:11
여러 테이블의 데이터를 재조합하기 위해 전체 조인을 사용할 수 있습니다.
order as well to recombine the data from multiple tables
3:27:14
모든 네 개의 테이블에서 누락된 것이 없기를 원한다면
if you don't want to miss anything from all four tables
3:27:18
모든 데이터, 일치하는 데이터와 일치하지 않는 데이터이지만
all data the matching and unmatching data but i
3:27:21
두 번째 사용 사례를 위해 데이터 보강에는 일반적으로 사용하지 않습니다.
don't use it usually for data enrichment for the second use case
3:27:24
전체 조인을 사용할 수 있는 곳은 마지막 사용 사례입니다.
and where we can use the full join is in the last use case
3:27:27
여기서 전체 조인을 사용할 수 있습니다. 기본 조인 유형을 다루었습니다.
as well but with a little twist that we can learn later so
3:27:30
이제 고급 SQL 조인에 대해 이야기할 것입니다.
this is mainly where we can use the full join all right so with that we have covered the basic types of joins inner left right and full join those are the classical joins on how to combine two tables.
3:27:42
이제 첫 번째 부분인 왼쪽 반조인에 대해 다룰 것입니다.
Now we're going to start talking about the advanced SQL joins and now we're going to cover the first part the left anti-join.
3:27:51
이것이 의미하는 바를 살펴보겠습니다. 왼쪽 반조인이란 무엇인가요?
So let's see what this means. Okay so now what is exactly a left anti-join?
3:27:59
이 메커니즘에서는 오른쪽 테이블에 일치하지 않는 왼쪽 테이블의 행을 반환하고자 합니다.
Now in this mechanism we want to return rows from the left side the left table that has no match in the right table.
3:28:07
왼쪽 테이블의 두 원을 살펴보겠습니다.
So now by looking to two circles from the left table we
3:28:10
일치하지 않는 행만 보고 싶습니다.
want to see only the unmatching rows so only
3:28:13
테이블 A에 존재하지만 테이블 B에는 존재하지 않는 행입니다.
rows that exist in table a but it don't exist
3:28:16
일치하는 데이터가 있다면 보고 싶지 않습니다.
in the table b so if there is like matching data we
3:28:19
오른쪽 테이블에서 아무 데이터도 원하지 않습니다.
don't want to see it and now from the right table we don't want anything
3:28:23
우리는 어떤 데이터도 원하지 않으므로, 이는 유일한 출처를 의미합니다.
we don't want any data so that means the only source
3:28:26
당신의 데이터는 왼쪽 테이블과 오른쪽 테이블에서 올 것입니다.
of your data gonna be the left table and from the right table we
3:28:29
데이터가 필요하지 않으므로, 우리는 단지 테이블을 결합하여
don't need any data we are just joining the tables to do
3:28:32
데이터를 필터링하는 체크를 수행할 것입니다. 이제 구문에 대해
a check to filter the data so now for the syntax this this can
3:28:35
흥미로울 수 있습니다. 우리는 왼쪽 안티 조인이라는 특별한 유형이 없습니다.
be interesting we don't have a special type called left anti-join
3:28:38
최소한 SQL 서버에서는 여전히 이 효과를 만들 수 있습니다.
at least in the sql server we still can create this effect
3:28:41
왼쪽이라고 말하고 있으므로 왼쪽 조인 유형을 사용할 수 있습니다.
since we are saying left we can use the type left join and
3:28:45
그런 다음 일반적으로 키와 함께 조인 조건을 사용하지만, 이제
then as usual the join condition with the keys but now if you
3:28:48
이렇게 두면 왼쪽 조인의 효과를 얻을 수 있습니다.
leave it like this you will get the effect of the left join and
3:28:51
우리는 그것을 원하지 않습니다. 왼쪽 조인으로 전체 원을 얻을 수 있기 때문입니다.
we don't want that because with the left join you will get the complete circle
3:28:55
왼쪽 테이블에서 그러나 이제 일치하는 데이터를 제거하기 위해
from the left table but now in order to remove the matching
3:28:58
중간에 겹치는 데이터가 있습니다. 우리가 할 수 있는 것은 필터를 사용하는 것입니다.
data this overlapping in the middle what we can do we can use a filter and in order to filter the data we use the where
3:29:04
데이터를 필터링하기 위해 WHERE 절을 사용합니다.
clause so now in order to get rid of the matching data we
3:29:08
따라서 이제 일치하는 데이터를 제거하기 위해
can take the key from the right table and we
3:29:11
오른쪽 테이블에서 키를 가져올 수 있습니다.
say the key must be null so if the key is
3:29:14
키는 null이어야 하므로, 키가
null so that means there is no match on the right
3:29:17
null이라는 것은 오른쪽에 일치하는 것이 없음을 의미합니다.
side and if you do it like this you will get the effect of
3:29:20
이렇게 하면 왼쪽 안티 조인의 효과를 얻을 수 있습니다.
the left anti-join only the data in the left that
3:29:23
오른쪽에 일치하지 않는 왼쪽의 데이터만 있습니다.
has no match on the right so now let's go in square and
3:29:27
이제 사각형으로 가서 이 효과를 만들어 봅시다.
create this effect okay so now we have the following task and it says
3:29:30
모든 고객을 가져오세요. 주문을 하지 않은 고객입니다.
get all customers who haven't placed any order so
3:29:33
이 쿼리를 보면 우리는 테이블에 집중하고 있습니다.
now by looking to this query clearly we are focusing on the table
3:29:36
고객이지만, 우리는 주문을 하지 않은 고객을 보고 싶습니다.
customers but we want to see the customers that didn't
3:29:39
그들은 우리의 데이터베이스에 있지만 고객은
order anything so they are in our database but the customers
3:29:43
비활성 상태입니다. 이제 이를 해결하는 방법은 여러 가지가 있습니다.
are inactive now there are like different ways on how to solve this
3:29:46
작업이지만 이제 조인을 사용하여 해결할 것입니다.
task but we're gonna solve it using the joins now let's
3:29:49
고객 테이블에서 모든 것을 선택하는 매우 간단한 쿼리를 작성해 보겠습니다.
go and start by just writing a very simple query where
3:29:53
이것이 우리의 다섯 고객이며, 이제 그 중 어떤 고객이
we are selecting everything from the table customers now you can see this is our five customers and now i want to check which of those
3:29:59
아직 아무것도 주문하지 않았는지 확인하고 싶습니다.
customers didn't order anything yet now since we are talking
3:30:02
주문에 대해 이야기하고 있으므로 주문 테이블과 조인할 수 있습니다.
about the orders we can go and join it with the table orders
3:30:05
주문 테이블을 왼쪽 조인하겠습니다.
so we're gonna say left join the table orders as
3:30:09
그런 다음 ID를 사용하여 테이블을 연결하겠습니다.
oh and then we're gonna go and connect the tables using the ids
3:30:12
고객 ID로 연결하겠습니다. 이제
with the customer id so now if
3:30:15
이제 실행하면 모든 고객이 여전히 보입니다.
you go and execute it now we are still seeing all the customers
3:30:18
왼쪽 조인을 사용하고 있으므로 이제 주문을 볼 수 있습니다.
because we are using the left join and now we can see the orders
3:30:21
각 고객의 정보이며 즉시 확인할 수 있습니다.
informations of each customer and you can see immediately
3:30:24
이 두 고객은 아무것도 주문하지 않았습니다.
those two customers they didn't order anything because
3:30:28
여기서 널 값이 보이므로 그들은 비어 있습니다.
we are seeing here nulls right so they are empty there
3:30:31
주문이 없으므로 이 정보를 사용할 수 있습니다.
is no orders now we can use this information in
3:30:34
데이터를 필터링하기 위해 마틴을 보고 싶습니다.
order to filter the data i just want to see martin
3:30:37
더 나은 방법은 여기에 있는 키를 사용하여
and better so what you can do we can go and say where
3:30:40
테이블을 조인하기 위해 이 키를 가져와야 합니다.
and all what you have to do is to take the key that we are using in
3:30:43
이것은 널이어야 하므로 널입니다. 이렇게 보이면 고객 ID가 널인 경우 데이터를 보고 싶다는 의미입니다.
order to join the tables this is this one over here and say this must be null so is null so if If you see it like this, that means you want to see the data if the customer ID is null.
3:30:55
이제 실행해 보겠습니다. 완벽합니다. 이제 아무것도 주문하지 않은 고객을 얻고 있습니다.
So let's go and execute it. Perfect. Now you are getting the customers who haven't ordered anything.
3:31:01
이것이 우리가 원했던 정확한 효과입니다. 왼쪽 반조인입니다.
And this is exactly the effect that we wanted. The left anti-join.
3:31:04
우리는 오른쪽에 일치하는 항목이 없는 왼쪽 측의 데이터를 얻고 있습니다.
We are getting the data from the left side where there are no match on the right side.
3:31:10
항상 두 단계로 수행해야 합니다. 먼저, 클래식 조인을 사용하여 데이터를 조인합니다.
So you have always to do it in two steps. First, join the data as you normally do using the classical joins, the left join.
3:31:17
그런 다음 두 번째 단계에서는 WHERE 절을 사용하여 필터를 사용합니다.
And then the second step, you go and use a filter using the where clause. If you do it like this, you can check for not existence.
3:31:24
그렇게 하면 존재하지 않음을 확인할 수 있습니다.
And with that, we are getting the effect of the left anti-join. So that's it.
3:31:28
그렇게 하면 왼쪽 반조인의 효과를 얻습니다.
Okay, so now if you are looking to this picture, I think you already know where we use the left anti-join.
3:31:33
우리는 마지막 사용 사례에서만 이를 사용할 수 있습니다.
We can use it only in the last use case where we are checking the existence.
3:31:37
그래서 왼쪽 조인을 사용하고 where와 함께 사용하면 다른 테이블에서 데이터의 존재하지 않음을 확인할 수 있습니다.
So if you use the left join together with the where, you can check for the not existence of your data in another table.
3:31:43
그래서 이것은 정확히 이 시나리오를 위한 것입니다. 자, 그게 전부입니다.
So this is exactly for this scenario. all right so that's all
3:31:46
왼쪽 반 조인에 대해 이제 우리는 정확한
about the left anti-join now we're gonna speak about the exact
3:31:49
그 반대에 대해 이야기할 것입니다. 우리는 오른쪽 반 조인을 다룰 것입니다.
opposite of that we will cover the right anti-join
3:31:53
그래서 매우 유사할 것이지만 우리는 단지 측면을 바꾸고 있습니다.
so it's gonna be very similar but we are just switching sides so
3:31:56
가자, 알겠어
let's go okay
3:32:01
그렇다면 정확한 오른쪽 안티 조인은 무엇인가요?
so now what is exactly the right anti-join well it
3:32:04
왼쪽 안티 조인의 반대입니다. 그래서 우리는 왼쪽에 일치하지 않는 오른쪽 테이블의 행을 반환하고 싶습니다.
is the opposite of the left anti-join so we want to return the rows from the right table that has no match in the left
3:32:11
다시 말해, 두 개의 원을 보면 지금 무엇이 중요한가요?
table so again if you are looking to our two circles now what
3:32:14
중요한 것은 오른쪽 테이블입니다. 우리는 오직
is important is the right table we want to see only
3:32:17
오른쪽 테이블의 일치하지 않는 행만 보고 싶습니다.
the unmatching rows from the right table
3:32:20
그래서 b에 존재하지만 a에는 존재하지 않는 행만
so only the rows that exist in b but not
3:32:23
필요하고 왼쪽 테이블에서는 아무것도 필요하지 않습니다. 그래서 데이터가 필요하지 않습니다.
in a and from the left table we don't need anything so no
3:32:26
즉, 데이터의 유일한 출처는 오른쪽 테이블에서 오고, 왼쪽 테이블은 필터로 사용됩니다.
data is needed and that means the only source of data
3:32:29
존재 여부를 확인하기 위해서입니다. 그래서 이제 그 구문은 왼쪽 안티 조인과 매우 유사할 것입니다.
comes from the right table and you are using the left table as a filter as a lookup just in order to check the existence so now the syntax of that's going to be very similar to the left anti-join.
3:32:40
그래서 우리는 오른쪽 안티 조인이라는 특별한 유형이 없습니다. 우리는 고전적인 오른쪽 조인을 사용해야 합니다.
So we don't have a special type called right anti-join. We have to use the classical one, the right join.
3:32:46
하지만 그렇게 하면 오른쪽 테이블의 모든 데이터를 얻을 수 있습니다. 그리고 중간의 일치하는 데이터를 없애기 위해 필터를 사용합니다.
But if you do that, you will get everything from the right table. And now in order to get rid of the matching data in the middle, we use a filter.
3:32:53
우리는 where 절을 사용하여 일치하지 않는 데이터에만 관심이 있다고 말합니다.
We use the where clause where we say we are interested only on the unmatching data.
3:32:58
그래서 왼쪽 테이블의 키를 가져오고 왼쪽의 키가 null이라고 말합니다.
So we take the key from the left table and we say the key from left is null.
3:33:02
그렇게 하면 일치하는 데이터를 없앨 수 있습니다.
And if you do that, you will get rid of any matching data is
3:33:05
null은 일치하는 것이 없음을 의미하며, 여기서도 마찬가지입니다.
null means there is no match and again here the same thing the
3:33:08
테이블의 순서가 매우 중요합니다. 여기서는 측면에 대해 이야기하고 있으므로 올바르게 해야 합니다.
order of the tables is very important since here we are
3:33:11
그래서 이제 작업은 일치하지 않는 모든 주문을 가져오라고 합니다.
talking about sides and you have to do it correctly okay so
3:33:15
알겠죠?
now the task says get all orders without matching
3:33:18
고객이 없으므로 이제는 정확히 반대입니다.
customers so now it is exactly the opposite we want to
3:33:21
유효한 고객이 없는 모든 주문을 확인하고 싶습니다.
see all the orders that don't have a valid customer so
3:33:25
이것은 비즈니스에서 정말 나쁜 시나리오입니다.
this is really bad scenario you have in your business orders without a valid customers so let's see how we can discover that using sql
3:33:32
이제 우리는 주문에만 집중하고 있습니다.
joins now as you can see we are focusing completely on the orders
3:33:35
더 이상 고객이 아니며 오직 주문만 보고 싶습니다.
it's not the customers anymore and we want to see only the orders
3:33:38
고객과 일치하지 않는 곳에서 두 가지 단계가 있습니다.
where there is no match with the customers so now again here we have two
3:33:41
첫 번째 단계는 일반 조인을 수행하는 것입니다.
steps the first step we're gonna go and do the normal join so
3:33:44
왼쪽 또는 오른쪽 조인을 사용하여
using either the left or the right join now by looking to
3:33:47
이 쿼리는 고객에서 시작할 수 있도록 이렇게 두어도 됩니다.
this query you can leave it like this where you can start from the customers
3:33:50
하지만 주문에 완전히 집중하고 싶다면 전환해야 합니다.
but if you want to fully focus on the orders you have to switch
3:33:54
왼쪽에서 오른쪽으로 변경하면 모든 주문과 일치하는 고객만 얻을 수 있습니다.
this from left to right and with that you will get all the orders and only the matching customers and let's go and remove
3:34:00
여기서 작업 클라우드를 제거하겠습니다.
this work clouds from here first so i'm just adding comments and
3:34:03
이 코드는 완전히 무시할 것입니다.
with that is we're going to totally ignore this line of code
3:34:06
이제 모든 주문을 가져오는 것을 실행해 보겠습니다.
so let's go and execute it now you can see we are getting all the orders
3:34:10
고객 데이터는 일치하는 경우에만 가져옵니다.
right and data from customers only if there is a
3:34:13
우리는 고객과 일치하지 않는 주문만 보고 싶습니다.
match and now of course this is not the task we don't want to see all
3:34:16
이 세 가지 주문은 괜찮습니다.
the orders we want to see only the orders where we don't have a match from the customers so if you look to this those three orders they are okay they are totally fine
3:34:25
하지만 이 주문은 정말 나쁩니다.
we are finding customers for them so they have valid customers
3:34:28
이 주문에 대한 유효한 고객이 없습니다.
but this order here is really bad so there is no
3:34:31
이러한 유형의 주문만 결과로 표시하는 것이 우리의 작업입니다.
valid customer for this order and now our task to show
3:34:34
우리는 where 절을 사용해야 합니다.
only this type of orders in the results now what we
3:34:37
정확한 효과를 얻기 위해 id가
have to do we have to use the where clause in order to get
3:34:40
고객의 id는 null이어야 합니다.
exactly the effect so this time we're gonna say if the id
3:34:44
이 id는 null이어야 한다고 말하고 있습니다.
of the customer here so here we're gonna say the id of the customer from the table customers must be null so we're gonna remove this here and take the key
3:34:52
이로써 작업을 해결하였고, 올바른 안티 조인의 효과를 얻고 있습니다.
from the customer and we are saying this id must be null. So let's go and execute it. Perfect.
3:34:59
그로써 우리는 작업을 해결했고 오른쪽 안티 조인의 효과를 얻었습니다.
With that, we have solved the task and we are getting the effect of the right anti-join.
3:35:03
이제 고객이 없는 주문을 얻고 있습니다. 그래서 우리는 작업을 해결했습니다.
And we are getting now those orders that don't have any customers. So we have solved the task.
3:35:09
이제, 친구들, 오른쪽 조인을 사용하지 않고 이 작업을 해결해야 합니다. 하지만 여전히 같은 효과를 얻어야 합니다.
Now, my friends, you have to go and solve this task without using the right join. But still, you have to get the same effect.
3:35:15
고객이 없는 정확한 주문을 얻고 싶습니다. 그래서 비디오를 일시 정지하고 작업을 해결하세요.
You want to get exactly those orders without customers. So pause the video and go solve the task.
3:35:26
이제, 다시 말하지만, 나는 오른쪽 조인을 좋아하지 않습니다. 테이블의 측면을 바꾸면 같은 효과를 만들 수 있습니다.
Now, again, as you know me, I don't like the right joins. We can create the same effects if you switch the sides of the table.
3:35:32
B 테이블을 왼쪽에 두고 A를 오른쪽에 두면, 오른쪽에서 왼쪽으로 조인 유형을 바꾸고 테이블을 바꾸면 같은 효과를 얻을 수 있습니다.
So if you say that B table now on the left side and the A on the right side, then we will get the same effect if you go and switch the type of join from right to left and you go just switch the tables.
3:35:43
왼쪽에 B 테이블을 두고 A와 조인하면 됩니다.
So you start from the B table since it's on the left side and then join it with the A.
3:35:48
물론, A의 데이터가 null인 작업 조건에서 우리는 여전히 말합니다. 그래서 일치하는 것이 없습니다.
And we still say, of course, in our work condition where the data from A is null. So there is no match.
3:35:54
이렇게 하면 왼쪽 조인을 사용하여 왼쪽 쿼리와 정확히 같은 결과를 얻을 수 있습니다.
So if you do this, you will get the exact same results like the left query by using the left join and just switching the tables.
3:36:00
같은 결과를 얻을 것입니다. 그리고 SQL에서는 항상 대안이 있다는 것을 알게 됩니다. 당신이 끝났기를 바랍니다. 그래서 꽤 간단합니다.
So you will get the same results. And with that, you know that in SQL, we have always alternatives. I hope that you are done. So it's pretty simple.
3:36:07
당신이 할 일은 조인을 바꾸는 것입니다. 그리고 주문이 주요 테이블이기 때문에 먼저 주문 테이블에서 시작할 것입니다.
What you're going to do, we're going to go and switch the joins. And since the orders is the main table, we're going to start first from the table orders.
3:36:14
우리는 왼쪽에 두고 오른쪽 테이블은 고객이 될 것입니다. 그리고 물론 조건은 그대로 유지됩니다.
So we are putting it on the left side and then the right table going to be the customers. And of course, the condition going to stay as it is.
3:36:22
고객이 없는 주문을 보고 싶습니다.
we want to see the orders where there is no customer so
3:36:25
여기나 조인 키에서 아무것도 바꿀 필요가 없습니다.
we don't have to switch anything here or on the join key so
3:36:28
그것을 실행해 보겠습니다. 그로써 우리는 같은 정확한 결과를 얻고 있습니다.
let's go and execute it with that you are getting the same exact results since
3:36:32
여기서 별을 사용하고 있으며 항상 왼쪽 테이블에서 시작합니다.
we are using here the star it always starts from the left table
3:36:35
오른쪽 테이블의 데이터를 표시하지만 여전히 결과는 유효합니다.
and show the data from the right table but still the result is
3:36:39
우리는 일치하는 고객이 없는 이러한 유형의 주문을 얻고 있으며, 나는 이 방법을 선호합니다. 자, 이제 왼쪽과 오른쪽이 있습니다.
valid we are getting this type of orders without matching customers and i prefer this way all right so now with that we have the left the right and now of
3:36:47
다음은 전체를 얻을 것입니다. 이제 SQL에서 전체 안티 조인에 대해 이야기해 보겠습니다.
what is next we will get the full so let's speak about now the full anti-join in sql let's go
3:36:57
그렇다면 전체 안티 조인이 정확히 무엇인지 알아보겠습니다.
okay so now what is exactly a full anti-join well this
3:37:00
이번에는 측면이 없고, 우리는 단지 행만 반환하고 싶습니다.
time we don't have sides we want to return only the rows
3:37:04
어떤 테이블에서도 일치하지 않는 행을 원합니다.
that don't match in either tables so what
3:37:07
왼쪽 원을 보고 있다면, 우리는 일치하지 않는 행만 원합니다.
this means if you are looking to the left circle we want only the unmatching rows so we don't want the whole circle we want only the data that exists in A but it don't exist in B on the right table.
3:37:18
오른쪽 테이블에서 일치하지 않는 행만 원합니다.
Sounds like the left anti-join but since we are saying full then you have to do the same thing on the right side as well.
3:37:24
결과에서 B에 있는 데이터가 A와 일치하지 않는 것을 보고 싶습니다.
So on the right table we want only the unmatching rows.
3:37:27
그래서 우리는 결과에서 B에 있는 데이터 중 A와 일치하지 않는 데이터를 보고 싶습니다.
So we want to see in the result the data that is in B but don't have a match from A.
3:37:32
그래서 이것은 정확히 반대입니다. 이것을 보면 우리는 일치하지 않는 데이터만 보고 싶다는 의미입니다. 이것은 내부 조인의 정확히 반대 효과입니다.
So it's exactly the opposite and if you look to this then that means we want to see only the unmatching data and this is exactly the opposite effect of the inner join.
3:37:42
내부 조인에서는 일치하는 데이터에만 관심이 있었습니다. 겹치는 경우에만 말이죠.
In the inner join, we were interested only on the matching data, only when there is like overlapping.
3:37:46
하지만 이제 전체 반조인에서는 정확히 반대입니다. 우리는 일치하는 데이터를 보고 싶지 않습니다.
But now with the full anti-join, it is exactly the opposite. We don't want to see the matching data.
3:37:51
우리는 나머지 모든 것, 즉 일치하지 않는 데이터를 보고 싶습니다. 그래서 이 쿼리를 어떻게 작성할까요?
We want to see everything else, the unmatching data. So how are we going to write this query?
3:37:55
다시 말하지만, 여기서는 전체 반조인이라는 특별한 유형이 없습니다. 우리는 고전적인 전체 조인의 도움을 사용할 것입니다. 기본적인 것입니다.
Again, here we don't have a special type called full anti-join. We will use the help of the classical full join. So the basic one.
3:38:02
A에서 시작하여 B와 전체 조인을 하고, 같은 키를 사용합니다. 하지만 이제 흥미로운 것은 where 조건입니다.
So you start from A, full join B, and then the same key. But now what is interesting is about the where condition.
3:38:08
이제 두 가지 조건이 있습니다, 맞죠? 그래서
Now we have like two conditions, right? so in
3:38:11
A에서 일치하지 않는 모든 데이터를 가져오기 위해
order to get all data from a that has no match in
3:38:14
B에서 키가 null이어야 한다는 필터를 만들어야 합니다.
b you have to make a filter where you say the key from the b
3:38:17
테이블은 null이어야 하고, 이제 우리는 정확히 같은 것을 원합니다.
table must be null and now since we want the exact same thing
3:38:20
오른쪽 테이블에서 B에 있는 모든 데이터를 원하며, A와 일치하지 않는
from the right table we want all the data in b that has no
3:38:23
일치하지 않는 경우 A 테이블의 키도 null이어야 합니다. 그래서 이제 우리는
match in a you have to say as well the
3:38:26
두 가지 조건이 있습니다. SQL에서 두 가지 조건이 있을 경우
key from the a table must be null so now we have here
3:38:29
A 테이블의 키가 null이어야 하므로 이제 우리는
like two conditions and in sql if you have like two conditions
3:38:32
SQL에서 두 가지 조건이 있을 때, 여기에서 두 가지 옵션이 있습니다. AND 연산자 또는 OR 연산자를 사용합니다.
in the word clause you have here two options either use and operator or the or operator
3:38:38
그래서 이제 우리가 사용할 것은 OR 연산자입니다. 그래서
so now the one that we're gonna use here is the or operator so
3:38:42
오른쪽 키가 비어 있거나 왼쪽 키가 비어 있습니다.
either the key from right is empty or the key from left
3:38:45
이렇게 하면 전체 반조인의 효과를 얻을 수 있습니다. 물론 여기서 양쪽이
is empty if you do it like this you will get the effect of
3:38:48
같다면 테이블의 순서도 여기서
the full anti-join and of course since here both sides
3:38:51
그리 중요하지 않으므로 A에서 전체 조인할 수 있습니다.
are equal then the order of the tables as well here
3:38:54
B와 전체 조인하거나 B에서 A와 전체 조인해도 상관없습니다.
is not that important so you can say from a full
3:38:57
이제 이 효과를 만들기 위해 스케일로 돌아가 보겠습니다.
join b or from b full join a it doesn't matter
3:39:00
이제 우리는 다음 작업이 있으며, 고객을 찾으라고 합니다.
so now let's go back to scale in order to create this effect okay
3:39:04
주문이 없는 고객과 고객이 없는 주문을 찾으라고 합니다.
so now we have the following task and it says find customers without
3:39:07
주문이 없는 고객과 고객이 없는 주문을 찾습니다.
orders and orders without customers so
3:39:10
이것은 고객과 주문의 불일치 데이터를 보려는 것입니다.
if you are looking to this this means we want to see only the
3:39:13
주요 테이블과 보조 테이블이 없습니다.
unmatching data from customers and as well from orders
3:39:16
두 테이블 모두 동일하게 중요합니다.
there is no main table and secondary table both of them are
3:39:19
이제 불일치 데이터와 반조인을 이야기하고 있으므로 두 단계로 진행해야 합니다.
equally important so now since we are talking about the unmatching
3:39:22
첫 번째 단계는 전통적인 조인을 수행하고, 그 다음에 WHERE 절에 집중합니다.
data and the anti-join we have to do it in two steps the first step we're gonna do the classical join and then we focus on the where clause so let me remove the where clause to make it as a comment.
3:39:32
이제 왼쪽과 오른쪽의 데이터를 원하므로 전체 조인을 사용할 것입니다.
Now since we want the data from left and right, we're going to go and use the full join. So let's go and execute it.
3:39:37
이제 전체 조인의 효과를 볼 수 있습니다.
Now you can see we are getting the effect of the full join. We are getting all the orders and as well all the customers.
3:39:43
모든 주문과 모든 고객을 얻고 있습니다.
But now we are interested only on the strange cases where they are like orders without customers like this one here and as well customers without orders.
3:39:52
이제 고객이 없는 주문과 같은 이상한 경우에만 관심이 있습니다.
So that means the first three rows, they are naturally interesting for us because it is boring.
3:39:57
첫 세 행은 자연스럽게 흥미롭습니다.
We have here matching data and this
3:40:00
여기에는 일치하는 데이터가 있습니다.
is totally fine but we are not focusing on that now we are focusing
3:40:03
하지만 우리는 지금 그것에 집중하지 않고 있습니다.
only if there is like missing data from left or from
3:40:06
왼쪽 또는 오른쪽에서 누락된 데이터가 있는 경우에만.
right as you notice i'm saying or and this is very important because
3:40:10
우리는 OR 연산자를 사용하고 있습니다.
we are using the or operator so now let's focus on getting this
3:40:13
이 시나리오에서 고객 ID는 null이어야 합니다.
scenario over here we want to get an order without a customer
3:40:16
여기에서 이미 null입니다.
so that means the customer id must be
3:40:19
고객 ID가 null인 경우입니다.
null and we have it already here so we are saying where the
3:40:22
이것을 실행하면 하나의 레코드만 얻을 수 있습니다.
id of the customer is null so if i go and execute
3:40:25
하지만 반대 시나리오도 얻고 싶습니다.
it i will get only one records only this one over here
3:40:29
이 시나리오에서 고객 ID는
but as well i want to get the opposite scenario
3:40:32
null이어야 합니다.
so in this scenario the customer id must
3:40:35
주문에서 고객 ID가 null입니다.
be null so we're gonna say or the customer id
3:40:38
또는 이렇게 나란히 할 수 있습니다.
in the orders is null
3:40:41
오른쪽이 null이거나 왼쪽이 null입니다.
or we can do it like side by side like this either the
3:40:44
오른쪽 또는 왼쪽이 null이므로 실행하면 전체 반 조인의 효과를 얻고 고객을 찾습니다.
right side is null or the left side is null so if you go and execute it you will get the effect of the full anti-join and with that we are finding the customers
3:40:53
주문이 없는 고객과 고객이 없는 주문을 생각해보면 정말 재미있고 쉽습니다.
without orders and orders without customers i
3:40:56
이것이 전체 반 조인을 수행하는 방법입니다. 이제 사용 사례를 살펴보겠습니다.
think this is really fun and as well really easy so this
3:40:59
우리는 다시 전체 반 조인을 사용합니다.
is how we do the full anti-join all right so now if you are looking to the
3:41:02
우리가 전체 안티 조인을 다시 정확히 사용하는 사용 사례
use cases we use the full anti-join again exactly
3:41:05
마지막 사용 사례에서 존재 여부를 확인하기 위해 전체와 WHERE를 결합하면 다른 테이블에서 데이터의 존재 여부 또는 비존재 여부를 확인할 수 있습니다. 이것이 바로 그 시나리오입니다.
for the last use case in order to check the existence so if you combine the full with the where you can check the existence or the not existence of your data in another table so this is exactly the scenario for that
3:41:22
좋아요, 친구들 이제 보너스 섹션이 있습니다. 제가 여러분에게 도전할 것입니다.
okay my friends now we have a bonus section where i'm gonna challenge you
3:41:25
내부 조인을 사용하지 않고 다음 작업을 해결하세요.
to solve the following task without using an inner
3:41:28
모든 고객과 그들의 주문을 가져오세요.
join so it says get all customers along with their orders
3:41:31
하지만 주문을 한 고객만 포함합니다.
but only for customers who have placed an
3:41:34
내부 조인을 사용하지 않고요.
order but without using an inner join so
3:41:37
이제 비디오를 잠시 멈추고 이 작업을 해결하세요. 자, 이제 어떻게 해결할지 봅시다. 우리는 고객과
pause the video now and go and solve this task okay so now let's see how we're gonna solve this we want the customers the
3:41:46
주문을 원하지만, 이전에 주문한 고객만 원합니다.
orders blah blah blah but we want only the customers who
3:41:50
우리는 이 작업을 해결하기 위해 내부 조인을 사용했습니다. 하지만 이번에는 사용이 허용되지 않습니다.
have placed an order previously we have used the inner join in
3:41:53
그래서 가서 해결해봅시다. 이렇게 할 것입니다. 테이블에서 모든 것을 선택합니다.
order to solve this task but this time we are not allowed to use it so let's
3:41:56
고객을 선택하고 별칭을 부여합니다.
go and solve it this is how i'm gonna do it select star from table
3:41:59
이제 모든 고객을 가져오고 있지만, 저는 주문한 고객만 관심이 있습니다.
customers and give it the alias so
3:42:02
우리가 이전에 알았듯이, 두 명의 고객이 아무것도 주문하지 않았고, 우리는
now i'm getting all the customers but i am interested only
3:42:06
최종 결과에서 그들을 보고 싶지 않습니다. 이제 어떻게 할까요?
the customers who have placed an order so as we know before there is like two customers they didn't order anything and we don't
3:42:12
주문 테이블의 도움을 사용할 수 있습니다.
want to see them in the final results now how we will get that
3:42:15
우리 고객의 존재 여부를 확인하기 위해서요. 물론 내부 조인을 사용할 수 없으므로, 왼쪽 조인을 사용할 것입니다.
well we can use the help of the table orders in order to
3:42:18
주문 테이블과 함께 사용하고, 그 후에 평소처럼 결합합니다.
check the existence of our customers there and of course i'm
3:42:22
고객 ID와 관련해서는 새로운 것이 없습니다. 이제 가봅시다.
not allowed to use the inner join so i'm gonna go and use a left join
3:42:25
고객 ID와 관련하여 새로운 것은 없습니다.
with the table orders and then combine them as usual
3:42:28
이제 실행해 보겠습니다. 단계별로 진행하고 있습니다.
nothing new with the customer id so now let's go
3:42:31
그리고 단계별로 진행하고 있으니 서두를 필요는 없습니다. 간단하게 시작하고 결과를 확인하세요.
and execute it as you can see we are doing it step by step you don't have to rush everything in one go so you start simple check the results
3:42:38
이제 이 결과를 보고 다음 단계를 결정하세요.
and decide on the next step so now by looking to these
3:42:41
세 고객을 얻고 싶습니다. 그들은 뭔가를 주문했기 때문입니다.
results i want to get those three customers because they have
3:42:44
주문한 데이터에 대한 정보를 보고 있습니다.
ordered something and we are seeing data about their orders and
3:42:48
마지막 두 개는 결과에서 제외하고 싶습니다.
i don't want to get in the result the last two so again we still
3:42:51
따라서 오른쪽 테이블의 고객 ID를 사용할 수 있습니다.
can use the customer id from the right table in
3:42:54
어떤 데이터가 결과에 남고 어떤 데이터가 필터링될지를 결정하기 위해서입니다.
order to decide which data gonna stay in the result and which
3:42:58
우리는 필터링할 데이터를 사용하고 where 절을 사용할 것입니다.
data should be filtered we're gonna go and use the where clause and then the key from the orders and this time we're gonna say
3:43:04
이번에는 null이 아님을 말할 것입니다.
is not null i know we didn't learn yet
3:43:07
데이터가 있어야 한다는 의미입니다.
about the not and the logical operators but using
3:43:10
열은 null이 아니어야 합니다.
the not null it means there should be data inside
3:43:14
이렇게 하면 정확한 효과를 얻을 수 있습니다.
the column it must not be null if you do it like this and
3:43:17
내부 조인과 같은 효과를 얻을 수 있습니다.
execute you will get the exact effect as
3:43:20
왼쪽 조인을 사용하면 보고 싶은 것을 제어할 수 있습니다.
the inner join so as you can see as you are joining the tables using
3:43:23
필터를 사용하여 문제를 해결하는 방법입니다.
the left join you can control what you want to see using
3:43:26
내부 조인을 사용하지 않고도 이 작업을 수행할 수 있습니다.
the where clouds using the filter and this is how you can solve this
3:43:30
세 가지 시나리오를 다루었습니다.
task without using an inner join okay so with that
3:43:33
일치하지 않는 데이터를 찾기 위해 왼쪽, 오른쪽, 전체 반조인에 대해 이야기했습니다.
you covered all those three scenarios in order to find the unmatching
3:43:36
이제 우리는 크로스 조인에 대해 이야기할 수 있습니다.
data left right full anti-joins now
3:43:39
모든 행을 결합하고 싶습니다.
we can speak about one crazy join we call it the cross join this one is totally different from all other types that we have learned so let's understand exactly what is that cross join let's go
3:43:54
모든 가능한 조합을 보고 싶다는 의미입니다.
so now what is exactly a cross join now in some scenarios we want to combine every row from the left every row from the right.
3:44:02
A와 B의 모든 것을 원합니다.
So that means I want to see all the possible combinations from both tables. So we are doing something called like Cartesian join.
3:44:10
A의 모든 것과 B의 모든 것이 결합된 것을 보고 싶습니다.
So now if you look to our two circles, we want everything from A and as well everything from B.
3:44:15
이 예에서는 A에 두 개의 행과 B에 세 개의 행이 있습니다.
So that means I want to see everything from A combined with everything with B.
3:44:20
크로스 조인을 수행하면 여섯 가지 가능한 조합을 얻을 수 있습니다.
So in this example, we have two rows in A and three rows in B.
3:44:24
이 예제에서는 A에 두 개의 행과 B에 세 개의 행이 있습니다.
If you do a cross join, you will get six possible combinations by just
3:44:27
교차 조인을 하면 단순히 행의 수를 곱하여 여섯 가지 가능한 조합을 얻을 수 있습니다.
multiplying the number of rows between a and b so be
3:44:30
교차 조인을 사용할 때는 주의해야 합니다. 사용하면
careful using the cross join if you use it you will get like
3:44:34
결과에서 미친 수의 행이 생성되고 데이터베이스가 정말 바빠질 것입니다.
crazy number of rows in the results and you're gonna make the database really
3:44:37
결과를 찾는 데 바빠질 것입니다. 이제 구문에 대해 이야기해 보겠습니다.
busy finding out the result for you so now about the syntax it's
3:44:40
가장 쉬운 방법이 될 것이므로 평소처럼 그 중 하나에서 시작합니다.
gonna be the easiest so you start as usual from one of those
3:44:43
예를 들어 A 테이블에서 시작하고 교차 조인을 사용합니다.
tables the a for example and then you say cross join
3:44:46
B 테이블을 사용합니다. 이제 여러분이 이것을 보면 이전의 조인과는 다릅니다.
b so now my friends if you look at this you can see it's not like
3:44:49
우리는 항상 일치하지 않는 행, 일치하는 행 등에 대해 이야기했지만, 여기서는 데이터가 일치하는지 여부를 전혀 신경 쓰지 않습니다.
the previous joins that we have done we have always before talked about unmatching rows matching rows and so on but here we don't care at all about whether the data is matching or not.
3:44:59
모든 가능한 조합을 보고 싶습니다. 모든 것을
i just want to see all the possible combinations everything
3:45:02
일치하는 두 테이블에 대해 신경 쓰지 않기 때문에
so since we don't care about matching the two tables we
3:45:05
어떤 조건도 지정할 필요가 없습니다. 따라서
don't have to specify any condition so there is no need to
3:45:08
조건을 지정할 필요가 없습니다. 따라서
use the keyword on because we don't need any condition
3:45:12
그게 전부입니다. 교차 조인 P라고 말하면 마법이 일어날 수 있습니다. 이제 SQL로 가서 시도해 보겠습니다.
so that's it you just say cross join p and the magic can happen so this is the cross join let's go to SQL to try that okay so now we have the following task it says generate
3:45:21
모든 고객과 주문의 가능한 조합을 생성하라고 합니다.
all possible combinations of customers and orders
3:45:24
즉, 모든 것을 모든 것과 함께 사용하고 싶다는 의미입니다.
so that means you want everything with everything using the
3:45:28
교차 조인을 사용하면 매우 간단할 수 있습니다. 따라서 선택으로 시작하겠습니다.
cross join and this can be very simple so we're gonna start with select
3:45:31
무엇이든 테이블에서 별표를 선택할 수 있습니다. 고객 테이블에서 시작할 수 있습니다.
star from whatever table so you can start from the customers
3:45:34
그런 다음 교차 조인 주문이라고 말합니다.
and then you say cross join orders
3:45:38
매우 간단합니다. 이제 실행해 보겠습니다.
that's it's very simple let's go and execute it so
3:45:41
이제 아시다시피 우리는 다섯 명의 고객과 네 개의 주문이 있으며, 이를 곱하면
now as you know we have five customers and four orders and if you multiply them
3:45:44
결과에서 20개의 행을 얻을 수 있습니다. 이제 우리는
you will get in the results 20 rows so now we
3:45:47
모든 것을 모든 것과 함께 얻고 있습니다. 데이터가
are getting everything with everything even if the data is
3:45:50
전혀 일치하지 않더라도 예를 들어 주문을 볼 수 있습니다.
not matching at all so you can see for example the orders
3:45:54
여기서 이 주문은 오직 한 고객에게만 속합니다.
here so this is one order that belongs only to one customer
3:45:57
고객 ID 하나로 실제로부터 온 주문입니다.
the customer id one so it is an order from actually
3:46:00
마리아와 함께 이 동일한 주문을 보고 있습니다.
maria but still we are seeing this same order with
3:46:03
다른 고객들과 모든 것을 결합하고 싶기 때문에.
the other customers since we want to combine everything with everything so
3:46:07
다음 세트에 대한 규칙은 없습니다.
there are no rules the same thing for the next set so this
3:46:10
실제로 존에게 속하는 두 번째 주문입니다.
is the second order actually belongs to john but we are seeing
3:46:13
모든 고객과 함께 이 주문입니다.
this order with all customers so that's it this is
3:46:16
교차 조인이 어떻게 작동하는지입니다.
how the cross join works and now you might ask me why we have
3:46:19
이해가 안 되죠? 친구들, 저는 드물게 사용합니다.
this it makes no sense right well my friends i rarely use
3:46:22
테스트 데이터를 생성하고 싶을 때입니다.
it but sometimes if i want to generate like test data or
3:46:26
예를 들어 색상이라는 테이블과
maybe if you have like for example table called colors and table
3:46:29
제품이라는 테이블이 있을 때입니다.
called products and you would like to see all the combinations between the
3:46:33
제품과 색상 간의 모든 조합을 보고 싶습니다.
products and the colors so in some scenarios it makes really
3:46:36
모든 색상과 함께 모든 제품을 보는 것이 좋습니다.
sense to see all your products together with all the colors without
3:46:39
일치 조건 없이 몇 가지 시나리오가 있습니다.
any matching conditions or whatever so there are like few scenarios
3:46:43
교차 조인에 대한 몇 가지 시나리오입니다.
for the cross join if you are like doing simulations or
3:46:46
이것이 교차 조인을 수행하는 방법입니다.
testing so this is how we do the cross join
3:46:49
교차 조인에 대한 모든 것입니다.
okay so that's all about the cross join and with that you have covered the
3:46:52
고급 조인 유형 네 가지를 다루었습니다.
four advanced types of joins now if you look at this
3:46:55
이제 두 테이블을 결합하고 결과에서
you might ask okay how i'm gonna choose between all those types so you might ask me okay barra how you do it well i'm gonna show you now my decision tree that i usually follow in order to choose the correct type
3:47:10
두 테이블 간의 일치하는 데이터만 보고 싶습니다.
So now if I'm combining two tables and I want to see in the results only the matching data between two tables, then I go and use the inner join.
3:47:18
그것에 대한 다른 유형은 없습니다.
We don't have any other type for that. So that's simple.
3:47:21
모든 데이터를 보고 싶습니다.
But now if I want to see everything, all the data, I don't want to miss anything after joining two tables, then I take different path.
3:47:28
한 쪽이 다른 쪽보다 더 중요한지 스스로에게 묻습니다.
And here I ask myself, is there like one side more important than the other?
3:47:33
한 테이블의 모든 데이터에 관심이 있습니다.
I interested in all data from one table from
3:47:36
주 테이블 또는 마스터 테이블이 있습니다.
one side like here we have like a main table or a master table
3:47:39
그럼 왼쪽 조인을 사용하고 싶지만
then I go and use the left join but if I want to
3:47:42
내 쿼리에서 모든 테이블의 데이터를 보고 싶다면
see all the data from all tables in my query everything
3:47:45
하나의 테이블이 다른 테이블보다 더 중요하지 않다
so there is no one table more important than other then
3:47:48
나는 전체 조인을 사용하므로 이것은 또 다른 경로이다
I go with the full join so this is another path
3:47:51
나는 오직 불일치하는 데이터만 보고 싶을 때
and now the third path if I'm interested to see only
3:47:55
나는 불일치하는 데이터를 보고 싶어서 점검을 하고 있다
the unmatching data so I'm doing some kind of checkups and so on and here again the same thing do I want to see the unmatching
3:48:01
한 쪽에서만 데이터를 가져오고 싶다면
data from only one side there is like one table that is
3:48:04
중요하다면 왼쪽 안티 조인을 사용한다
important then i go and use the left anti-join
3:48:07
그래서 나는 한 테이블에서 불일치하는 데이터를 보고 싶다
so i want to see the unmatching data from one
3:48:10
나는 다른 테이블을 점검용으로만 사용하고 있다
table and i'm using the other table only for the check but in
3:48:13
내 쿼리에서 두 테이블이 모두 중요하다면
my query if both of the tables are important there is no
3:48:16
주 테이블과 보조 테이블 모두 중요하다면
main table and secondary table both are important then
3:48:19
나는 전체 안티 조인을 사용하므로 사실 이게 전부다
i go and use the full anti-join so actually that's it this is the decision tree that i follow usually as i'm writing a query and you might ask me how How about the right join?
3:48:29
이것을 보면 내가 작성하는 쿼리의 대부분에서
Well as you know me, I don't have it at all in my decision tree. So I don't use it at all.
3:48:34
나는 왼쪽 조인을 자주 사용한다고 말할 수 있다
Now by looking to this, I can tell you if I check most of the queries that I write, very often I use the left join.
3:48:41
그래서 나는 이것이 테이블을 조인하는 내 가장 좋아하는 방법이라고 말할 수 있다
So I can tell you this is my favorite way on how to join tables. So let me show you exactly why.
3:48:50
보통 나는 데이터 분석을 위해 쿼리를 작성한다
Usually I write queries in order to do data analysis. So in data analytics, you have always like starting points.
3:48:56
그래서 나는 항상 내 분석의 주 테이블로 시작한다
You have like a topic that you are analyzing like the customer. So you have always like a master table.
3:49:02
그리고 나서 무슨 일이 일어나는가? 이 테이블의 데이터가 부족하다
So I always start with the main table of my analysis. So in my query, I start from this table, from table A, the main table.
3:49:09
그래서 테이블 B에서 추가 데이터를 필요로 한다
And then what happens? The data is not enough in this table. I need some extra data that comes from another table like the table B.
3:49:16
그래서 테이블 B는 주 테이블에 추가 데이터로 존재한다
So the table B is only here like an additional data to the master table.
3:49:20
그래서 나는 테이블 B를 연결하기 위해 왼쪽 조인을 사용한다
So I go and use the left join in order to connect the table B.
3:49:24
그리고 나서 다른 테이블에서 또 다른 흥미로운 정보를 찾는다
and then i find another interesting information in another table in
3:49:27
테이블 C에서 같은 일이 발생하므로 테이블을 조인한다
table c so same things happens i go and join the tables
3:49:30
왼쪽 조인을 사용하고 계속 연결한다
using the left join and so on so i keep connecting
3:49:34
여러 테이블을 이 주요 테이블에 연결하고
multiple tables to this main table in the middle and
3:49:37
내 쿼리는 항상 왼쪽 조인을 사용하는 형태가 될 것입니다.
my query gonna look like this always doing left join
3:49:40
여러 테이블을 사용할 때, 물론 가끔
with multiple tables now of course you might say yeah but sometimes
3:49:43
일치하는 데이터만 보고 싶을 수 있습니다. 그래서 내부 조인을 사용하는 것이 합리적입니다. 그렇게 하려면 최종 결과에서 보고 싶은 모든 것을 제어할 수 있습니다.
you would like to see only the matching data and so on so it makes sense only to use the inner join well in order to do that i can control everything that I want to see in the final result using the where clause.
3:49:54
그래서 WHERE 절에서 최종 결과에서 보고 싶은 것을 정확히 정의합니다.
So in the where clause, I define exactly what I want to see in the final result.
3:49:58
그렇게 하면 일치하는 데이터와 일치하지 않는 데이터를 볼 수 있는 유연성이 생깁니다.
So with that, I get like more flexibility on whether I want to see the matching, unmatching data and so on.
3:50:04
우리가 리프트 안티 조인에서 했던 것처럼 말이죠? 데이터를 분석할 때, 저는 주 테이블에서 시작하여 모든 다른 테이블을 리프트 조인하는 설정을 자주 사용합니다.
Like we've done in the lift anti-join, right? So as I'm analyzing data, I tend very frequently having this setup where I start from the main table and I lift join all other tables.
3:50:14
그리고 WHERE 조건으로 최종 결과를 제어합니다. 이렇게 여러 테이블을 연결합니다.
And with the where conditions, I control the final results. So this is how I connect multiple tables together.
3:50:20
이제 원으로 시각화하고 싶다면 이렇게 될 것입니다. 원 A가 있습니다. 이것이 마스터 테이블, 시작점입니다.
So now if I want to visual this in like circles, it's going to look like this. we have the circle A. So this is the master table, the starting point.
3:50:27
테이블 A의 모든 데이터를 보고 싶습니다. 그리고 다른 테이블인 테이블 B와 왼쪽 조인을 합니다.
I want to see all the data from table A. And I left join it then with another table, table B.
3:50:32
테이블 B에서 일치하는 데이터만 보고 싶습니다. 그래서 왼쪽 조인과 같습니다. 이제 무엇이 일어날 수 있을까요? 다른 테이블을 추가할 것입니다.
And from table B, I want to see only the matching data. So it's like the left join. Now what can happen? I'm going to go and add another table.
3:50:40
그래서 다른 원, 원 C가 있습니다. 원 C에서 일치하는 데이터만 보고 싶습니다.
So another circle, the circle C. And from the circle C, we want to see only the matching data.
3:50:45
물론 이 원들을 계속 추가할 수 있지만, 항상 같은 것입니다. 당신의 원에는 일치하는 데이터만 있습니다.
And of course, you can keep adding circles to this, but it's going to be always the same thing. And in your circle, it has only the matching data.
3:50:52
이제 우리가 배운 대로, 여러 테이블을 결합하기 위해 조인을 사용할 수 있습니다.
So now as we learned, we can use joins in order to combine multiple
3:50:55
주제에 대한 전체적인 큰 그림을 얻기 위해 여러 테이블을 결합합니다.
tables to get a complete big picture about topic like
3:50:58
고객에 대해 모든 것을 보고 싶습니다.
the customers i would like to see everything about the customers in
3:51:01
최종 결과에서 모든 것을 보고 싶습니다. 그러니 저처럼 시작할 것입니다.
the final results so either you're gonna do it like me where you start
3:51:04
주 테이블에서 시작하여 모든 다른 테이블과 왼쪽 조인을 하거나
from the main table and then go and left join all other tables or
3:51:08
고객에 대한 주 테이블이 없다고 말할 수도 있습니다.
maybe you say you know what there is no main table about the customers
3:51:11
모든 테이블이 동등하게 중요합니다.
data all the tables are equally important then
3:51:14
일치하는 데이터에만 관심이 있다면 내부 조인을 사용하여 모든 테이블을 조인할 수 있습니다. A에서 다시 원을 가지면, 일치하는 데이터만 필요합니다.
you can go and join all those tables using the inner join if you are interested only on the match data so what can happen if you have again those circles from the From A, you need only the matching data.
3:51:25
B에서도 일치하는 데이터만 필요합니다. 세 번째 원에서도 마찬가지입니다.
From B, you need as well only matching data. And as well from the third circle.
3:51:29
그래서 이 세 테이블 간의 겹치는 부분에만 관심이 있습니다.
So you are interested only on the overlapping between all those three tables.
3:51:33
그래서 세 테이블 간의 겹치는 부분이 있는 이 섹션만 얻을 수 있습니다.
So you will get only this section where you have overlapping between all three tables.
3:51:38
그래서 이것은 여러 테이블을 조인하는 또 다른 방법입니다.
So this is, of course, another way on how to join multiple tables.
3:51:41
좋아요, 이제 친구들, 여러 테이블을 조인하는 방법을 연습하기 위해 SQL로 돌아가 보겠습니다. 자, 이제 과제를 해봅시다.
Okay, so now, my friends, let's go back to SQL in order to practice how to join multiple tables. Okay, so now let's have a task.
3:51:47
이건 조금 도전적일 것입니다. 우리는 다중 조인을 할 것입니다.
This is going to be a little bit challenging. We will be doing multi-joins.
3:51:51
판매 데이터베이스를 사용하여 모든 주문 목록을 가져옵니다.
using the sales db retrieve a list of all orders
3:51:54
관련된 고객, 제품 및 직원과 함께
along with their related customer product and employee
3:51:58
각 주문에 대해 다음을 표시하고 싶습니다.
details and for each order display the following we want
3:52:01
주문 ID, 고객 이름, 제품 이름을 보고 싶습니다.
to see the order id the customer name the product name
3:52:04
판매 가격, 판매원 이름이 있습니다.
sales price salesperson name so there
3:52:07
지금 많은 일이 진행되고 있으며, 첫 번째로 주목할 점은 지금 우리는 다른 데이터베이스를 사용하고 있다는 것입니다. 우리는 내 데이터베이스를 사용하지 않고 판매 데이터베이스를 사용할 것입니다. 이것이 우리가 해야 할 첫 번째 일입니다.
is a lot of things that is going on and the first thing that you're going to notice adults now we are using different database we will be not using the my database we're going to go and use the sales db so this is the first thing that we have to do.
3:52:20
그러므로 내 데이터베이스를 사용하는 대신, 판매 데이터베이스를 사용하라고 말하고 실행합니다.
So instead of using my database, so we say use sales DB and then execute it.
3:52:25
우리는 이제 판매 데이터베이스에 연결되었습니다. 이것이 세 번째 사항입니다. 이제 이 과제를 읽고 있다면, 관련된 많은 테이블이 있습니다.
We are now connected to the sales DB. So this is the third thing. So now if you are reading this task, there are a lot of tables that are involved.
3:52:33
우리는 주문이 필요하고, 고객, 제품 및 직원이 필요합니다.
We need the orders, we need the customers, products, and employees.
3:52:37
이 과제에는 네 개의 테이블이 필요하며, 각 테이블에서 다양한 정보를 필요로 합니다. 이제 어떻게 생각해야 할까요?
So there are like four tables needed in this task and we need different stuff from each table. So now how I think about it?
3:52:44
주로 주문 테이블에 초점을 맞추고 있습니다, 맞나요?
Well, it is mainly focusing on the table orders, right?
3:52:47
우리는 모든 주문이 필요하며, 하나도 놓칠 수 없습니다.
So we need all the orders we cannot miss any
3:52:50
여기에서 이 소리가 나면, 이것이 주요 테이블입니다.
order here so this sounds for me this is the main
3:52:53
그리고 그와 함께 다른 정보가 필요하다고 합니다.
table and then it says along with that we need other informations
3:52:56
즉, 다른 테이블은 그렇게 중요하지 않다는 뜻입니다.
so that means the other tables are not that important like
3:53:00
주문과 같은 테이블이므로, 이것이 무엇인지에 대한 느낌을 줍니다.
the orders so this gives me feeling about what is
3:53:03
주요 테이블이며, 이것이 시작점이 될 것입니다.
the main table and this is going to be my starting point so
3:53:06
주문 테이블에서 시작하겠습니다. 그래서 스타를 선택하고, 이 데이터베이스는 항상 스키마가 있다는 점에 주의해야 합니다.
let's start from that from the table orders so select star from and here you have to pay attention to that this database has always a schema it's called
3:53:15
왼쪽을 보면 판매 점이 테이블 이름입니다.
if you look to the left side sales dots the table name so
3:53:18
이제 그것을 우리의 쿼리에 작성해야 하며, 우리는 그것을 작성할 것입니다.
we have to write that now in our query so we're gonna write it over
3:53:21
여기에서 판매 점과 테이블 이름인 주문을 작성합시다.
here sales dots and then the table name that orders let's
3:53:25
이제 실행하러 가겠습니다. 이 테이블을 쿼리하는 것은 처음입니다.
go and execute it now i know this is the first time that you are querying this
3:53:28
테이블에는 여기 많은 정보가 있습니다.
table we have a lot of informations here and as well
3:53:31
우리는 많은 아이디어를 가지고 있으며, 이러한 아이디어는 다른 테이블과 데이터를 결합하는 데 도움이 될 수 있습니다. 여기서 필요한 것은 주문 ID입니다.
we have a lot of ideas those ideas can help us of course on joining our data with the other tables so what do we need from here we need the order id so we have it over here We're going to go to the order ID.
3:53:43
이번에는 명명 규칙이 다릅니다. 우리는 밑줄이나 일반적인 케이스가 없습니다. 다양한 유형의 명명이 있습니다. 그래서 조심해야 합니다.
This time, the naming convention is different. We don't have like underscores and common case. We have different type of namings. So be careful with that.
3:53:51
그렇다면 우리는 무엇이 더 필요할까요? 우리는 판매가 필요합니다. 여기 오른쪽에 판매라는 열이 있습니다. 그리고 우리는 그것을 결과에 포함시킬 것입니다.
So what else do we need? We need the sales. So if you go to the right side over here, we have column called sales. And we're going to go and include it to the results.
3:53:58
이제 다른 정보는 실제로 필요하지 않습니다.
Now, all the other informations are actually not needed.
3:54:02
하지만 다른 테이블과 결합하기 위해서는 이러한 ID가 필요합니다. 그래서 이제 무엇을 할 것인지, 별칭을 부여할 것입니다.
But I need those IDs in order to join it with other tables. So now what I'm going to do, I'm going to go and give it an alias and all.
3:54:09
이제 각 열에 대해 할당할 것입니다. 이것은 주문에서 오며, 판매에 대해서도 같은 방식입니다.
So now I'm going to go and assign it for each column. This comes from the orders and as well the same thing for the sales.
3:54:15
지금은 그게 전부입니다. 실행하면 주문과 판매를 얻을 수 있습니다. 알겠습니다. 그래서 첫 번째 테이블은 이렇습니다.
So that's it for now. And if I go and execute it, I will get the orders and the sales. All right. So that's all for the first table.
3:54:21
이제 우리가 무엇이 필요한지 보러 가겠습니다. 고객의 이름이 필요합니다. 사실, 우리는 주문에서 이 정보를 가지고 있지 않습니다.
Let's go now and see what do we need. We need the customer's name. Well, actually, we don't have this piece of information in the orders.
3:54:28
그래서 당신이 해야 할 일은 다른 테이블을 탐색하여 이 열을 찾는 것입니다.
So all that you have to do is to go and explore in the other tables in order to find this column.
3:54:33
보통 제가 하는 방법은 이렇게 테이블을 탐색하는 것입니다. 그래서 각 테이블에서 선택 기호를 씁니다.
So how I usually do, I go and explore the tables like this. So I write a symbol select from each table.
3:54:39
고객들입니다. 이제 데이터베이스 내의 각 테이블에 대해 이것을 반복합니다.
So the customers. So now I go and repeat this for each table inside the database.
3:54:44
고객들, 직원들이 있습니다.
So we have the customers, employees.
3:54:48
주문과 주문 아카이브, 그리고 제품이 있습니다.
We have an orders, the orders archive. And as well the products.
3:54:54
이제 테이블을 탐색하기 시작합니다.
So now I start exploring the table.
3:54:56
고객들로 가면
So if I go to the customers over
3:54:59
여기에서 우리는 다섯 명의 고객이 있다는 것을 볼 수 있습니다.
here, we can see we have here five customers and we can see
3:55:02
고객의 이름을 볼 수 있으며, 우리는 첫 번째 이름을 봅니다.
the names of the customers so we see the first name
3:55:05
그리고 성이 필요합니다. 이것이 내 쿼리에 필요한 것입니다.
and the last name and this is exactly what i need for my query
3:55:08
물론 이 테이블을 주문과 연결해야 합니다.
now of course we have to go and connect this table with the orders so
3:55:12
우리는 공통 열이 필요합니다. 보통 ID가 될 것입니다.
we need a common column usually it's going to be the id so here we
3:55:15
여기에서 고객 ID가 있으며, 주문을 확인하면 고객 ID도 찾을 수 있습니다.
have the customer id and if you go and square the orders you can find here as well the customer id now if Now, if you are working in big projects, you can have a lot of tables and exploring each one of them can be really hard.
3:55:26
프로젝트에서 수백 개의 테이블이 있다면, 각 테이블을 탐색하는 것이 정말 어려울 수 있습니다.
So, of course, if you have like in the project hundreds of tables, it's going to be really hard to explore each table.
3:55:30
그래서 대신 좋은 프로젝트, 좋은 데이터베이스는 일반적으로 엔티티 관계 모델, ER 모델을 가지고 있습니다.
So instead of that, a good project, a good database usually has an entity relationship model, ER model, like the one that we have for the course.
3:55:40
여기에서 데이터베이스 내의 테이블과 그들 간의 관계를 쉽게 찾을 수 있습니다.
And here you can find easily the tables that you have inside your database and as well the relationship between them.
3:55:46
이것은 특히 테이블을 결합하고 싶을 때 매우 중요합니다.
And this is very important, especially if you want to join tables.
3:55:49
이 다이어그램을 빠르게 살펴보면, 주문 테이블에 고객 ID라는 ID가 있다는 것을 이해할 수 있습니다.
So now by just looking quickly to this diagram, I can understand, okay, there is an ID called customer ID inside the table orders.
3:55:58
그것은 기본 키에 대한 외래 키와 같습니다, 그 고객 ID.
And it is like a foreign key to the primary key, that customer ID.
3:56:02
즉, 주문과 고객을 연결하려면 그 고객 ID를 사용해야 합니다.
So that means if I want to connect the orders with the customers, I have to use that customer ID.
3:56:06
이것은 정말 훌륭한 문서이며, 테이블을 조인하는 방법을 빠르게 이해할 수 있습니다. 이제 쿼리로 돌아가겠습니다.
So as you can see, this is really nice documentations and I can quickly understand how to join the tables. So now back to our query.
3:56:13
이제 제가 할 것은 리프트 조인이라고 말하는 것입니다. 그래서
Now what I'm going to do, I'm going to say lift join. so with
3:56:16
모든 주문이 출력에 표시될 수 있도록 보장합니다.
that i guarantee all the orders can be presented in the output
3:56:19
항상 10개의 주문을 볼 수 있으므로 이제 조인해 보겠습니다.
and i will see always 10 orders so now let's join it
3:56:22
고객 판매 테이블과 조인하고, 이렇게 별칭을 부여합시다.
with the table customers sales dot customers and
3:56:25
조인 조건을 설정할 것이며, 고객 ID는
let's give it an alias like this and now we're gonna build the
3:56:28
주문 테이블의 고객 ID와 같아야 합니다.
joining condition so it's gonna be the customer id from
3:56:31
고객 ID와 동일한 테이블 주문
the table orders equal to the customer id
3:56:35
고객 테이블에서 SQL이 두 테이블을 어떻게 연결하는지 이해할 수 있도록 이제 두 테이블이 연결되었고 정보를 얻을 수 있습니다.
from the table customers so that sql understand how to match the two tables and now the two tables are connected and i can get the informations now
3:56:43
고객 테이블에서 첫 번째를 가져옵니다.
from the customers so see let's go and get the first
3:56:47
이름과 성도 가져옵니다.
name and as well the last name so
3:56:50
이제 실행해 보겠습니다. 보시다시피 우리는
now let's go and execute it so now as you can see we have
3:56:53
각 주문에 대한 고객이 있어 정말 좋습니다.
customers for each order which is really nice so with
3:56:56
고객 이름과 주문 ID를 얻었습니다. 이제
that we got the customer name and the order id now the
3:56:59
다음으로 제품 이름이 필요합니다. 그래서 여기로 가서
next one we need the product name so either you're gonna go here
3:57:02
탐색을 시작할 수 있습니다. 제품 테이블 안에 있는 것 같습니다. 여기에서 제품이 있으며, 이것이 제품의 이름입니다. ER 다이어그램을 확인하면
and start exploring i think it is inside the table products and here you can see we have the product this is the name of the product and if you check our er
3:57:12
주문 테이블과 연결할 수 있습니다.
diagram you can see we can connect the table orders
3:57:15
제품 ID를 사용하여
with the products using the product id
3:57:18
왼쪽에 제품 ID가 있고 오른쪽에도 있으며, 이제 여기에서 이 조인을 구축할 수 있습니다. 다시 말하지만, 왼쪽 조인으로 가겠습니다. 주문 테이블에서 아무것도 잃고 싶지 않습니다.
so we have the product id in the left and as well in the right and now we can go and build this join as well over here so again i go with the left join i don't want to lose anything from the table orders
3:57:28
판매 제품을 선택하고 별칭을 p로 지정합니다. 이제 조건은 여기에 매우
sales products and we give it an alias p now the condition for that here you have to be very
3:57:35
집중해야 합니다. 주문에서 제품을 가져오고 싶습니다.
focused you want to get the product from the
3:57:38
그래서 o.dot 제품 ID라고 말합니다.
orders so you say o dot product id
3:57:42
제품 테이블의 제품 ID와 같습니다
equal to the product id from the table products
3:57:45
조인에서 항상 연결하고 있음을 알 수 있습니다
so as you can see in the joins we are always joining with
3:57:48
주문 테이블과 연결하고 있습니다
the table orders right we are not trying to join for example
3:57:51
고객과 제품을 항상 주 테이블과 연결하고 있습니다
the customers with the products always we are joining with the main table so with that we have connected the third table and we can get the
3:57:59
필요한 정보를 얻기 위해 제품이 필요합니다
information that we need so we need the products as
3:58:02
제품 이름으로 바꿀 것입니다
i'm gonna go and rename it products name
3:58:05
이제 테이블에서 제품 정보를 가져오고 있습니다
so let's go and execute it and with that my
3:58:08
판매도 있으므로 필요합니다
friends i'm getting now the product informations from the table
3:58:11
가격을 확인할 수 있습니다
products so we have the sales as well and we need
3:58:14
가격 정보에 대해 잊어버렸습니다
the price so if you go to the products you can see we have as
3:58:17
같은 테이블에서 가격을 가져옵니다
well price information i forgot about it so let's go and get it
3:58:20
판매원 이름을 가져오고 싶습니다
as well from the same table price so let's go and execute it and with that we have as well the prices now the last
3:58:27
직원의 이름을 가져오고 싶습니다
column it says we want to get the sales person name
3:58:30
직원 테이블을 탐색하고 실행합니다
so the name of the employee right now if you go and
3:58:34
여기에서 직원의 이름과 성을 볼 수 있습니다
explore as well we have here employees table and execute
3:58:37
이제 이 ID가 필요합니다
it you can see we have here the name and the last name of the employees
3:58:40
주문에서도 필요합니다
and we have an id so now we need this id
3:58:43
판매원 ID라는 추가 ID가 있습니다
as well in the orders so you can see we have the product id the customer id we already used those two but we have here one more extra id called the sales person id of course it is not called employee id
3:58:55
여기서 약간 의구심이 들 수 있습니다
so here you might be a little bit skeptical about it that's why we
3:58:58
ER 다이어그램을 다시 확인해야 합니다
have to go and check again our er diagram and as you can
3:59:01
직원 ID가 판매원 ID와 연결되어 있습니다
see the employee id from the employees it is connected
3:59:04
주문과 연결할 수 있다는 것을 이해합니다
to the salesperson id so with that i have better feeling
3:59:07
판매원 ID를 사용하여 직원과 연결할 수 있습니다
about it and i understand okay i can connect the orders with
3:59:10
왼쪽 조인으로 하겠습니다
the employees using the salesperson id so let's
3:59:13
왼쪽 조인을 하고 있습니다
go and do that i'm gonna say left join so as you can see
3:59:16
나는 왼쪽 조인을 하고 있어요.
i'm just doing left joins sales dots employees as e and the condition again very
3:59:23
항상 첫 번째 테이블이 포함됩니다.
important always the first table is included in
3:59:26
조인 조건에서 판매자 ID가
the join condition and here we can see the sales person id is
3:59:30
직원 ID와 같으므로
equal to the employee id so with
3:59:33
직원과 연결된 것을 얻을 수 있습니다.
that we have connected as well the employees and we will get as
3:59:36
이름과 성을 얻을 수 있습니다.
well the first name and the last name so
3:59:40
완벽해요, 이제 실행해 보겠습니다.
perfect that's it let's go and execute it and
3:59:43
여기서 문제가 발생합니다.
as you can see guys now we are getting the name of the salesperson
3:59:47
이제 이름을 얻고 있습니다.
now here comes an issue as you are joining multiple tables and you are getting columns from different tables what can happen you might encounter this scenario where you have the same names in multiple tables.
3:59:57
이제 이름이 있습니다.
So now, as you can see, we have the first name
4:00:00
고객의 성이 있습니다.
last name from the employees and as well we have the first name last name from
4:00:03
무엇에 대해 이야기하고 있는지 이해하기 어려울 것입니다.
the customers and it's going to be really hard from the result to understand what
4:00:06
고객인지 직원인지에 대해 이야기하고 있습니다.
are we talking about is it the customers is it the employee that's why
4:00:09
같은 이름이 있는 경우 별칭을 줘야 합니다.
in this scenario if you have the same names we have to go and
4:00:12
고객의 이름과 성을 말할 것입니다.
start giving aliases so for the first one we're going to say
4:00:15
직원의 이름이나 성을 말할 것입니다.
customer first name and as well for the last name we're going to say customer last name same thing for the employee so let's say
4:00:24
판매원이라고 부를 수 있습니다.
employee first name or
4:00:27
성입니다.
we can call it the salesperson whatever employee
4:00:30
이제 더 명확해질 것입니다.
last name so if you go and execute
4:00:34
고객의 이름에 대해 이야기하고 있습니다.
it now it's going to be more clear here we are talking about the
4:00:37
직원의 이름에 대해 이야기하고 있습니다.
name of the customer and here we are talking about the name
4:00:40
별칭을 사용하지 않으면 문제가 발생합니다.
of the employee and again one more thing if you are not using aliases
4:00:43
문제가 발생할 것입니다.
it's going to be an issue so for example if you go over here and you don't use the table name before the column so if i go and remove it and execute it you will see i'm getting
4:00:52
고객의 이름인지 직원의 이름인지 이해할 수 없습니다.
an error now isqul can't understand what are you talking
4:00:55
정확하게 명시하지 않으면 문제가 발생합니다.
about is it the first name of the customer or from
4:00:58
직원들에 대해 구체적으로 언급하지 않아서
the employees because you are not specific about it so you
4:01:01
이 열이 어떤 테이블에 속하는지 이스쿼를 알려줘야 해
have to tell isqul to which table belong this column it's
4:01:04
특히 같은 열이 있을 경우 테이블 이름이나 별칭을 사용하는 것이 매우 중요해
very important to use a table name or the alias before
4:01:08
열 이름, 특히 동일한 열이 있는 경우
the column name especially if you have the same column
4:01:11
정확하게 해야 해. 지금 많은 테이블이 있고
so now we will not get an error and with that you have solved the task you have really to pay attention about the join keys the condition you have to do
4:01:19
많은 열이 있으며, 때때로 조인에 잘못된 열을 지정하는 문제가 발생해
it correctly because as you can see now we have a lot of tables and a
4:01:22
조인에 잘못된 열을 지정하면 결과가
lot of columns and sometimes happens an issue where you
4:01:25
전혀 의미가 없게 섞일 수 있으니 항상 두 번 확인해
specify the wrong columns for the joins and the result
4:01:28
테이블을 조인하기 위해 올바른 키를 사용하고 있는지
can mix at all no sense so always double check are
4:01:31
작업을 해결했어. 이것이 내가 테이블을 조인하는 방법이야
you using the correct keys in order to join the tables so with
4:01:35
나는 항상 중요한 테이블에서 시작점을 가지고 있고, 나머지는 왼쪽 조인될 거야
that you have solved the task and this is exactly how i join tables
4:01:38
어떤 시나리오를 제거하고 싶다면, 나는 WHERE 절을 사용해
i have always a starting points from an important table and everything else gonna be left joined and in my results if i want
4:01:45
이것이 여러 테이블을 조인하는 방법이야
remove any scenario then i go and use the where clause so this is how i join multiple tables
4:01:51
그래서 이제 여러분은 SQL에서 테이블을 조인하는 방법에 대해 모든 것을 배웠어
okay my friends so with that you have learned now everything
4:01:54
이제 두 번째 방법으로 넘어가야 해
about how to join the tables in sql and this
4:01:57
여러 테이블에서 데이터를 결합하는 방법에 대해
is very important to understand now moving on to the second method
4:02:01
셋 연산자를 사용할 거야. 그래서 결합하는 방법을 다룰 거야
on how to combine your data from multiple tables we have the set
4:02:04
여러 테이블의 행을 결합하는 방법을 알아보자
operators so we're gonna go and cover how to combine the
4:02:07
자, 친구들. 이제 결합하기 위해
rows from multiple tables so let's go all
4:02:14
두 개의 테이블을 결합하는 방법은 두 가지가 있어
right my friends so now as we learn before in order to combine
4:02:17
열을 결합하고 싶다면 조인을 사용해
two tables we have two methods if you want to combine the columns
4:02:20
우리는 조인을 사용하고 다양한 유형을 배웠어
we use the joins and we have learned all those different
4:02:23
이 섹션을 다뤘지만, 이제 두 테이블의 행을 결합하고 싶다면
types on how to combine data using join so we have covered
4:02:26
셋 연산자를 사용할 수 있어. 여기에는
this section but now if we want to combine the rows of two tables
4:02:30
우리는 집합 연산자를 사용할 수 있고 여기에는
we can use the set operators and here we have
4:02:33
우리는 네 가지 다른 유형의 집합 연산자를 가지고 있습니다.
four different types we have union union all except and intersects so now we're gonna go and deep dive into this world on how to combine the rows of tables using the set operators
4:02:43
물론 이 과정에서는 모든 것을 다룰 것입니다.
And now, of course, in this course, we're going to cover everything. So let's go.
4:02:51
자, 이제 집합 연산자의 구문을 살펴보겠습니다.
All right. So now let's have a look to the syntax of the set operators. OK, so now let's see that we have the following query. We are selecting the data from the customers.
4:02:58
이것이 우리의 첫 번째 쿼리 또는 첫 번째 선택 문입니다.
So this is our first query or our first select statement.
4:03:02
또 다른 유사한 쿼리가 있습니다.
And we have another one which is very similar where we are selecting the informations from the employees.
4:03:07
이 두 쿼리 사이에 집합 연산자를 넣을 수 있습니다.
And this is our second select statement. So now what we can do, we can put between those two queries
4:03:14
예를 들어, 우리가 사용할 수 있는 합집합입니다.
is set operators like for example the union we can use
4:03:17
물론 합집합, 교차 등 다른 집합 연산자도 있습니다.
of course any other set operators like the union all intersects
4:03:20
구문은 매우 간단합니다.
accepts and so on so as you can see the syntax is
4:03:23
두 개의 서로 다른 쿼리가 있습니다.
very simple we have two different queries and we just
4:03:26
이것이 집합 연산자의 구문입니다.
put between them the set operator so this
4:03:29
이제 집합 연산자의 규칙에 대해 이야기하겠습니다.
is how the syntax of the set operators looks like all right friends
4:03:32
각 개별 선택 문에서 거의 모든 SQL을 사용할 수 있습니다.
so now we're going to talk about the rules of the set operators and we're going to start with the rule number one the sql clauses in each individual
4:03:39
조건절, 조인, 그룹화 등을 사용할 수 있습니다.
select statements or query we can use almost all the sql
4:03:43
단 하나의 예외가 있습니다.
clauses like where join group by
4:03:46
정렬은 한 번만 사용할 수 있습니다.
having but there is only one exception with the
4:03:49
전체 쿼리의 끝에서만 사용할 수 있습니다.
order by order by you can use it only once and
4:03:52
각 선택 문에서 정렬을 사용할 수 없습니다.
only at the end of the entire query so that means
4:03:55
각 쿼리에서 한 번만 사용할 수 있습니다.
we cannot use order by in each select statements
4:03:58
다시 말해, 두 개의 선택 문이 있습니다.
or in each query we can use it only once and only at the ends of the entire query all right so about the syntax
4:04:05
그 사이에 집합 연산자가 있습니다.
again here we have our two select statements and in
4:04:08
각 쿼리에서 여러 가지를 사용할 수 있습니다.
between them we have the set operators so now in
4:04:11
조인, 조건절, 그룹화 등을 사용할 수 있습니다.
each query we can go and use multiple stuff like
4:04:14
각 쿼리를 원하는 만큼 복잡하게 만들 수 있습니다.
the join where group by having so we can
4:04:17
모든 것이 허용되지만 정렬은 제외입니다.
make each query complex as we want so everything
4:04:20
모든 것이 허용되지만, 정렬 기준은 항상
is allowed but not the order by the
4:04:23
쿼리의 끝에 배치되어야 합니다.
order by must be always placed at the end of the
4:04:26
결과를 첫 번째 이름으로 표시하고 싶다면
entire query so if you want to show the result by the first
4:04:29
정렬 기준을 정확히 사용해야 합니다.
name you have to use the order by exactly at
4:04:32
끝에 배치해야 하므로 쿼리에서 정렬 기준을 사용할 수 없습니다.
the end so we are not allowed to use order by in
4:04:36
각 쿼리에서 열의 수는
each query okay moving on to the rule number two the number
4:04:39
같아야 합니다. 이 규칙을 이해하기 위해
of columns the number of columns in each query must
4:04:42
아주 간단한 예를 들어보겠습니다. 첫 번째 이름을 선택할 것입니다.
be the same okay so now in order to understand this rule let's
4:04:45
그리고 테이블에서 성을 선택할 것입니다.
have this very simple example we're gonna go and select the first name
4:04:48
이것이 우리의 첫 번째 쿼리입니다. 첫 번째 선택 문장이고, 다른
and the last name from the table sales customers
4:04:53
쿼리를 가지고 있다고 가정해봅시다.
so this is our first query our first select statements and let's say that i have another
4:04:58
이번에는 다른 테이블인 직원 테이블에서
and we want to select the first name last name but this
4:05:01
두 개의 쿼리가 생겼고, 이제 이들을 결합하고 싶습니다.
time from another table the employees so with that
4:05:04
하나의 결과로 결합할 것입니다.
we have our two queries and i would like now to go and combine them
4:05:08
셋 연산자 합집합을 사용할 것입니다.
into one result so we're gonna go and use the
4:05:11
이제 결과에서 첫 번째 이름과 성을 얻을 수 있습니다.
set operator union let's go and execute it
4:05:14
두 개의 테이블인 고객과 직원에서 작동하고 있습니다.
so now as you can see in the results we will get the first name and last name from
4:05:17
규칙을 충족하고 있기 때문입니다.
two tables the customers and employees and it is working
4:05:20
열의 수는 두 쿼리 모두에서 같아야 합니다.
because we are fulfilling the rule where it says the number
4:05:23
첫 번째 쿼리에서 몇 개의 열이 있나요? 두 개가 맞고,
of columns must be the same in both queries so
4:05:26
두 번째 쿼리에서도 두 개의 열이 있습니다.
how many columns do we have in the first query we have two right and
4:05:30
모든 것이 작동하는 이유입니다. 이제 규칙을 깨뜨려
as well in the second query we have two columns so that's
4:05:33
첫 번째 쿼리에 다른 열을 추가해 보겠습니다.
why everything is working so now let's go and break the rule by adding
4:05:36
고객 ID를 첫 번째 쿼리에 추가하고 싶습니다.
another column to the first query so let's say that i
4:05:39
첫 번째 쿼리에는 세 개의 열이 있지만, 두 번째 쿼리에는 두 개만 있습니다.
would like to have the customer id as well in the first query and with that as you can see in the first query we have three columns but but in the second we have only two.
4:05:49
그러니 이제 실행해 보겠습니다. 결과에서 볼 수 있듯이, union, intersect 및 모든 집합 연산자를 사용할 경우 쿼리 간에 동일한 수의 열이 있어야 한다는 오류가 발생합니다.
So let's go and execute it. Now, as you can see in the result, we will get an error where it says if you are using union intersect and all those set operators, you must have an equal number of columns between queries.
4:06:00
이것이 규칙입니다. 이를 수정하려면 동일한 수의 열이 필요합니다. 그래서 저는 고객 ID를 제거하겠습니다.
So this is the rule. You have to have the same number of columns in order to repair it. So I'm going to do, I'm just going to remove the customer ID.
4:06:07
여기서도 두 개의 열이 있으며 두 번째 열도 두 개의 열이므로 모든 것이 잘 작동할 것입니다.
So here again, we have two columns and the second one as well two columns and everything going to be working.
4:06:12
이제 규칙 3으로 넘어가겠습니다. 각 쿼리의 열 데이터 유형
Okay, moving on to the rule number three, the data types of columns in each query
4:06:16
일치해야 하며, 호환 가능해야 합니다.
must match must be compatible in matching in
4:06:20
확인하기 위해 우리가 할 일은 객체 탐색기로 가는 것입니다.
order to check that's what we're gonna do we're gonna go to the object explorer to the
4:06:23
왼쪽으로 가서 고객과
left side let's go and browse the customers and the
4:06:26
열을 살펴보면 여기 첫 번째 이름과
columns and as you can see we have here the first name and
4:06:29
성도 동일한 데이터 유형인 varchar를 가지고 있습니다.
last name with the same data type we have the varchar and
4:06:32
직원으로 가면 첫 번째 이름과 성도 동일한 데이터 유형인 varchar를 볼 수 있습니다.
if you go to the employees you can see as well the first name last
4:06:35
첫 번째 쿼리의 첫 번째 열은 varchar이고 직원의 성도 마찬가지입니다.
name having varchar so the first column is varchar from the first query and as well for the employees and as well the last name
4:06:43
고객의 성도 동일한 데이터 유형을 가지고 있습니다.
from the customers having the same data type as
4:06:46
직원의 성에서 데이터 유형이 일치합니다.
the last name from employees so the data type is matching
4:06:50
이제 이 규칙을 깨보겠습니다. 첫 번째 이름 대신 고객 ID를 사용하고 싶습니다.
now let's go and break this rule instead of
4:06:53
이제 왼쪽에서 고객 ID를 확인해 보겠습니다.
having the first name i would like to go and use the customer id
4:06:56
고객 ID는 정수형이지만 첫 번째 이름은
so now let's check the customer id on the left side it
4:06:59
varchar입니다. 그래서 여기 데이터 간의 불일치가 있습니다.
is an int an integer but the first name is
4:07:02
이제 실행해 보겠습니다. 현재 오류가 발생하고 있으며, 이스라엘이 값을 프랭크로 변환하려고 하고 있습니다.
in varchar so here we have a mismatch between data
4:07:06
정수로 변환하려고 합니다. 이것은 첫 번째 쿼리가
types let's go and try to execute it so now we are getting an error where it says israel is trying to convert the value frank
4:07:12
항상 이름과 데이터의 모든 것을 제어하고 있다는 것을 의미합니다.
to an integer so what this means the first query
4:07:15
여기 정수가 있으며, 이제 SQL은
is always controlling everything in the names and as well the data
4:07:18
첫 번째 이름 값을 정수로 변환하려고 합니다.
types so here we have an integer and now SQL is
4:07:21
정수로 변환하려고 하지만, 물론 작동하지 않을 것입니다. 왜냐하면
trying as well to convert the first name values to
4:07:24
여기 문자들이 있기 때문에 문자를 정수로 변환할 수 없습니다.
an integer and of course it will not work because we have
4:07:27
그래서 데이터 유형 간의 불일치가 발생합니다.
here characters inside and it cannot convert characters to an integer
4:07:30
그래서 데이터 유형 간에 불일치가 있습니다.
so we have a mismatch between data types between
4:07:34
고객 ID와 이름 간에 불일치가 있습니다.
the customer id and the first name and that's why we will get
4:07:37
두 번째 열에서는 문제가 없습니다.
an error the second column we don't have an issue because it is
4:07:40
첫 번째 테이블에서 varchar입니다.
varchar in the first table and as well for the second table
4:07:43
첫 번째 쿼리에서 이름을 선택하거나
so now in order to repair it either select a first name
4:07:46
여기에서 직원 ID라고 말할 수 있습니다.
in the first query or we can go over here and say employee id
4:07:49
이렇게 실행하면
and with that if i execute it so
4:07:52
우리는 오류가 발생하지 않을 것입니다.
we will not get an error because the employee id is
4:07:55
데이터 유형이 일치하기 때문입니다.
as well an integer and we have a match in the data types
4:07:59
열의 수가 같다고 해서 충분하지 않습니다.
so as you can see it's not enough to have the same number of columns you have to have as well matching data types between those two queries
4:08:05
다음 규칙으로 넘어가겠습니다.
okay let's move to the next rule rule number four the order of
4:08:08
각 쿼리에서 열의 순서가
columns the order of columns in each query must
4:08:12
동일해야 합니다.
be as well the same okay so let's understand what this means
4:08:15
여기에서 ID를 선택하는 동일한 예가 있습니다.
now we have here again the same example where we are selecting the id
4:08:18
고객의 성과 ID를 선택하고
and last name from customers and we are combining it using union
4:08:21
직원 ID와 성을 결합하고 있습니다.
with the employee id and last name from the employees and
4:08:25
모든 것이 잘 작동하고 있습니다.
as you can see everything is working because we have the same number of columns and we have a matching data types so now let's go and break it what i'm gonna do i'm just gonna switch between those two columns
4:08:35
먼저 성을 선택하고 고객 ID를 선택합니다.
so first i'm selecting the last name and then the customer
4:08:38
ID는 정수이며
id so again i have the same number of columns
4:08:41
직원의 ID와 일치합니다.
and the id is integer matching the id of
4:08:44
이제 실행해 보겠습니다.
the employee and the last name having the same data type so
4:08:47
오류가 발생하고 SQL이 변환하려고 합니다.
let's go and execute it so here again sql gonna
4:08:50
값을 정수로 변환하려고 합니다.
throw an error and says sql is trying to convert the value goldberg
4:08:53
여기에서 같은 정보를 가지고 있습니다.
to an integer so it's like character to integer it will not work so
4:08:57
ID와 성이 있습니다.
what happened here i have here the same informations i have an id and
4:09:00
성과 이름, 아이디어와 성이 있습니다. 하지만 SQL은 이렇게 작동하지 않습니다.
last name an idea and last name well sql doesn't work like this
4:09:03
첫 번째 쿼리의 첫 번째 열을 매핑하려고 합니다.
is going to go and map the first column from the first
4:09:06
두 번째 쿼리의 첫 번째 열과 첫 번째 열을 매핑하려고 합니다.
query with the first column with the second query so it's going to go and map
4:09:09
성에서 직원 ID로 매핑하려고 합니다. 그들은
last name to employee id and since they have
4:09:13
서로 다른 데이터 유형이기 때문에 오류가 발생할 것입니다. SQL은 이해하지 못합니다.
different data types it's going to throw an error so sql doesn't understand
4:09:16
매핑하는 방법을 모르거나, 예를 들어 ID와 ID를 매핑하는 방법을 모르거나
or don't know how to map let's say the id with the id and
4:09:20
서로 다른 데이터 유형이기 때문에 SQL은 오류를 발생시킬 것입니다.
since they have different data types sql gonna go and throw an error
4:09:23
여기서 보시다시피 고객과 직원 간에 동일한 정보가 있습니다.
so as you can see here we have the same informations between
4:09:26
하지만 그들은 동일한 순서를 가지고 있지 않기 때문에 SQL은 정보를 매핑할 수 없습니다.
customers and employees but they don't have the
4:09:29
열의 이름 때문에 SQL은 단순히
same order so sql cannot go and map the information
4:09:32
이렇게 카운트를 매핑합니다. 첫 번째 열은
because of the names of the columns it's gonna go and simply
4:09:35
첫 번째 쿼리의 첫 번째 열과 두 번째 쿼리의 첫 번째 열에서
just mapping the count like this the first column
4:09:38
이 규칙에서 보시다시피 동일한
from the first query with the first column from the second query
4:09:42
열의 순서를 가져야 합니다. 먼저 ID, 그 다음 성입니다. 그렇게 하면 다시 작동할 것입니다.
so as you can see in this rule you must have the same
4:09:45
출력에서 볼 수 있는 열 이름은 첫 번째 쿼리의 열 이름에 의해 정의되고 결정됩니다.
order of the columns first the id and then the last name and with that it's gonna work again all right moving on to the rule number five the column aliases.
4:09:55
이것은 첫 번째 쿼리가 출력에서 열의 이름을 지정하는 책임이 있음을 의미합니다.
Column names that we see in the output in the result is defined and determined by the column names of the first query the first select statements.
4:10:04
다시 같은 예를 들어보겠습니다. 고객 ID 성은 고객에서, 직원 ID 성은 직원에서 가져옵니다.
So this means the first query is responsible of naming the columns in the output. Okay, so let's understand what this rule means.
4:10:11
출력을 자세히 살펴보면 출력에서 고객 ID가 있고 직원 ID가 없음을 알 수 있습니다.
Again, we have the same example, the customer ID last name from customers union employee ID last name from employees.
4:10:17
직원 ID의 ID가 있지만, 보시다시피 첫 번째 쿼리가 출력의 이름을 제어하고 있습니다.
So if you check closely the output, you can see that in the output we have the customer ID and not the employee ID.
4:10:24
첫 번째 열이 고객 ID로 호출되기 때문에 출력에서 고객 ID로 표시됩니다.
even though we have the IDs from the employee ID. But as you can see, the first query is controlling the naming of the output.
4:10:32
따라서 다음 쿼리의 이름 지정은 완전히 무시될 것입니다.
So since the first column called the customer ID, you will see it in the output as a customer ID.
4:10:38
그래서 출력에 별칭을 주고 싶다면, 첫 번째 쿼리에서만 그렇게 해야 합니다.
So the naming of the like the next queries will be totally ignored.
4:10:43
예를 들어, 여기에서 고객 ID 대신 ID라고 부르고 싶습니다.
So that's why if you want to give aliases to the output, you're going to go and do it only for the first query.
4:10:48
이제 실행하면 출력에서 ID를 얻을 수 있습니다.
So for example, I go over here and say instead of having customer ID, I would like to call it as an ID.
4:10:54
각 쿼리에서 이 별칭을 줄 필요가 없습니다.
So now if I go and execute it, as you can see in the output, we will get an ID.
4:10:59
그래서 각 쿼리에서 이 별칭을 줄 필요가 없습니다.
So I don't have to go and in each query give this alias.
4:11:02
그래서 다음 쿼리에서 같은 이름을 줄 필요가 없습니다.
So I don't have to go over here and say, yeah, you are as well the ID because it's enough to define it from the first query.
4:11:09
따라서 다음 쿼리에서 동일한 이름을 제공할 필요가 없습니다.
So there's no need to give the same names in the next queries.
4:11:13
성에 대한 별칭을 원한다고 가정해 보겠습니다. 그래서 저는 이렇게 last_underscore_name으로 하고 싶습니다.
Let's take another example where we would like to have an alias for the last name. So I would like to have it like this last underscore name.
4:11:20
그리고 두 번째 쿼리에서 이렇게 해보겠습니다. last
and let's go and do it in the second query so last
4:11:24
underscore name을 실행해 보겠습니다.
underscore name let's go and execute
4:11:27
지금 출력에서 보시다시피 여전히 last name이 있습니다.
it so now as you can see in the output we still have last name
4:11:30
그리고 언더스코어가 없는 이유는 이것이 완전히 무시되기 때문입니다.
and there's no underscore because this is totally ignored
4:11:33
SQL에서 이것은 첫 번째 쿼리가 아닙니다.
from sql this is not the first query the
4:11:36
첫 번째 쿼리는 언더스코어 없이 last name이라고 말합니다.
first query says you are last name without underscore
4:11:39
그래서 다시 말하지만, 그렇게 하려면 여기로 가서 첫 번째 쿼리에 넣어 보겠습니다. 실행해 보겠습니다. 친구들, 첫 번째 쿼리는 매우 중요합니다.
so again if you want to do that we go over here let me just get it and put it in the first query let's go and execute it so my friends the first query is very important in order to give
4:11:50
출력에 대한 이름을 제공하기 위해서입니다. 따라서 별칭을 만들고 싶다면
the names for the output so if you want to do aliases and
4:11:53
항목의 이름을 바꾸려면 첫 번째 쿼리에서만 하십시오.
to rename stuff do it only on the first query and
4:11:56
또한 첫 번째 쿼리는 데이터 유형을 제어합니다. 알겠습니다.
as well the first query controls the data types all right now
4:11:59
마지막 규칙에 맞추어 올바른 정보를 일치시키는 것입니다.
to the last rule matching the correct informations if
4:12:03
쿼리에서 다른 모든 규칙을 충족하고 오류가 없다면
in your query you fulfill all other rules and you don't have an error
4:12:06
SQL에서 결과가 정확하고 올바르다는 것을 의미하지 않습니다.
in the sql that doesn't mean that your result
4:12:09
정보를 쿼리 간에 올바르게 매핑하는 것은 오직 당신의 책임입니다.
is accurate and correct you are the only one that is responsible of mapping the informations between queries correctly because
4:12:17
SQL은 당신의 쿼리와 테이블의 내용과 정보를 이해하지 못하기 때문입니다.
sql doesn't understand the content and the informations of
4:12:20
쿼리 간에 정보를 올바르게 일치시키지 않으면 출력에서 부정확하고 잘못된 결과를 얻게 됩니다.
your tables of your queries and if you don't match the informations correctly between the queries you will get inaccurate and wrong results in the output okay so now back to our example let's say i would like to get
4:12:32
좋습니다. 이제 예제로 돌아가서, 이름과 성을 가져오고 싶다고 가정해 보겠습니다.
the first name and as well the last name
4:12:35
고객의 이름과 직원의 동일한 정보를 가져오고 싶습니다.
from the customers and the same informations from the employees
4:12:38
이제 실행해 보겠습니다. 보시다시피 매우 좋습니다.
let's go and execute it now as you can see it's very nice
4:12:41
우리는 두 테이블에서 첫 번째 이름과 성을 하나의 결과로 가져오고 있습니다.
where we are getting the first name last name from both tables in
4:12:45
그리고 SQL의 모든 요구 사항을 충족하고 있습니다.
one result and we are fulfilling all the requirements in sql
4:12:48
같은 숫자, 같은 데이터 유형 등 이제 가서 만들자.
same numbers same data types and so on now let's go and make
4:12:51
잘못된 결과가 나올 것이므로, 내가 할 것은 단순히 교환하는 것이다.
incorrect results so what i'm gonna do i'm just gonna swap
4:12:54
두 번째 쿼리에서 이름과 성을 교환하는 것이다.
the first name and last name in the second query
4:12:57
그래서 먼저 성을 그리고 그 다음 이름을.
so first last name and then the first name so
4:13:01
실행해 보자. 이제 보시다시피 결과를 얻을 수 있다.
let's go and execute it so now as you can see we will get results because
4:13:04
우리는 모든 다른 규칙을 충족하고 있다. 왜냐하면 우리는 동일한
we are fulfilling all other rules because we have the same
4:13:07
열의 수와 일치하는 데이터 유형을 가지고 있기 때문이다.
number of columns and as well we have matching data types
4:13:11
그래서 첫 번째는 문자이고, 첫 번째 이름과
so the first one is character the first name and the
4:13:14
성도 문자이므로, ISQL은 정의한 대로 결과를 제시할 것이다.
last name is as well character so isql will just present the
4:13:17
결과는 당신이 정의한 대로지만 결과는
result as you define it but the result is
4:13:20
완전히 잘못되었다. 왜냐하면 이제 첫 번째를 확인하면
completely wrong because now we have if you check the first
4:13:23
여기 첫 번째 이름이 있고, 여기서 우리는 성을 볼 수 있다.
column here the first name so here we can see last names
4:13:26
예를 들어 브라운과 베커가 첫 번째 이름 안에 있다.
inside the first names for example brown and becker
4:13:29
그것들은 성이지만 우리는 그것들을 첫 번째 이름 안에서 볼 수 있다.
those are last names but we can see them inside the first name and the same thing in the last name we now we can see first names inside it mari carol they They are all first names.
4:13:40
그래서 보시다시피 결과는 정말 나쁜 데이터 품질을 가지고 있다.
So as you can see, the results has really bad data quality. We are now mixing stuff and it doesn't make any sense.
4:13:46
하지만 SQL은 그것을 알지 못할 것이다. 왜냐하면 SQL은 데이터의 내용에 대해 알지 못하기 때문이다.
But SQL will not know that because SQL doesn't know the information, the content of your data.
4:13:52
그냥 데이터 유형을 매핑하는 것이다. 그래서 첫 번째 이름은 VARCHAR이고, 성도 VARCHAR이다.
It's just mapping the data types. So first name is a varchar, the last name as well varchar.
4:13:57
모든 것이 괜찮고 결과를 얻을 수 있다. 친구들, 두 쿼리 간에 동일한 정보가 매핑되도록 책임이 있다.
Everything is fine and you will get the results. So my friends, you are responsible of having the same informations mapped between the two queries.
4:14:06
SQL에서 오류가 없다고 해서 올바른 결과가 없다는 의미는 아니다.
and not having an error from SQL doesn't mean that we have no correct results.
4:14:10
두 쿼리 간에 매핑하는 정보에 주의하라. 좋아, 이것이 집합 연산자의 규칙이다.
So pay attention to the information that you are mapping between the two queries. Alright, so those are the rules of the set operators.
4:14:18
첫 번째는 ORDER BY는 전체 쿼리의 끝에서 한 번만 사용할 수 있으며, 모든 쿼리는 동일한 열 수, 일치하는 데이터 유형, 동일한 열 순서를 가져야 한다.
So the first one is that the order by can only be used once at the end of the entire query and all queries must have the same number of columns, the matching data types, the same order of columns
4:14:30
첫 번째 쿼리는 항상 결과 집합의 이름과 별칭, 데이터 유형을 제어한다.
And the first query always control the names and the aliases of the result set and as well the data type.
4:14:36
마지막 규칙은 쿼리 간에 올바른 정보를 서로 매핑하고 있는지 확인하라.
And the last rule of that, make sure that you are mapping the correct informations to each other between queries.
4:14:43
그래서 이것이 집합 연산자의 규칙이다. 좋아, 그럼 유니온이란 무엇인가?
So those are the rules of the set operators. Okay, so what is union?
4:14:51
유니온은 두 쿼리에서 모든 고유한 행을 반환할 것이다.
Union is going to go and return all distinct unique rows from both queries.
4:14:56
즉, 모든 것을 결합하고 모든 행이 출력에 표시됩니다.
So that means it's going to go and combine everything and all the rows going to be presented at the output.
4:15:01
따라서 모든 고유한 행이 있다고 하니, 유니온은 결합된 결과 집합에서 모든 중복을 제거합니다.
So since it says all distinct unique rows, that means union going to go and remove all duplicates from the combined result sets.
4:15:09
유니온은 각 행이 한 번만 나타나도록 합니다. 자, 이제 아주 간단한 예를 들어보겠습니다.
So union going to make sure that each row can appear only once. All right. So now let's have this very simple example.
4:15:16
두 개의 데이터 세트가 있습니다. 고객 데이터가 있고, 첫 번째 이름이 있는 다섯 명의 고객이 있습니다.
We have two sets of data. We have the customers where we have five customers with the first names
4:15:22
또한 직원이라는 또 다른 세트가 있으며,
and as well we have another set called employees and we have as well
4:15:25
직원의 첫 번째 이름이 있으며 다섯 명의 직원이 있습니다.
the first names of the employees and we have five employees
4:15:28
이제 첫 번째 이름을 살펴보면 고객과 같은 사람이 있습니다.
and now if you take a look to the first names you can see that we have the
4:15:31
고객과 직원 모두에서 같은 사람이 있습니다.
same persons as the customers and as well as employees
4:15:34
우리는 두 데이터 세트에서 '주어진'과 '결혼'을 가지고 있습니다.
we have given and marry in both sets of data
4:15:38
이제 유니온이 어떻게 실행되는지 보겠습니다. 고객과 직원 모두에서 모든 사람을 반환하지만, '주어진'과 '결혼'이 출력에 두 번 나타나므로 한 번만 표시됩니다.
so now how is skill gonna execute union it's gonna go and return everyone from customers and everyone from the employees but now since we have given and married twice in the output we're gonna have them only once.
4:15:49
이것이 유니온이 작동하는 방식입니다. 두 세트에서 모든 사람을 반환할 수 있지만 중복은 없습니다.
So this is how the union works. It can go and return everyone from two sets, but without duplicates. All right.
4:15:56
이제 다음 작업이 있습니다. 직원과 고객의 데이터를 하나의 테이블로 결합하라고 합니다.
So now we have the following task and it says, combine the data from employees and customers into one table.
4:16:01
즉, 하나의 테이블에서 직원과 고객의 모든 정보를 결합하고자 합니다. 어떤 정보가 필요할까요?
So that means in one table, we want to combine all informations from employees and customers. So which informations do we need?
4:16:07
이것이 제가 보통 스스로에게 묻는 첫 번째 질문입니다. 이를 위해 먼저 데이터를 탐색해야 합니다.
This is the first question that I usually ask myself. So in order to do that, first, we have to explore the data.
4:16:13
판매 고객에서 모든 항목을 선택하고 세미콜론을 입력합니다. 그런 다음 다른 쿼리를 작성할 것입니다.
So select star from sales customers and then semicolon. Then I'm going to write another query.
4:16:21
판매 및 직원에서 모든 항목을 선택하고 세미콜론을 입력합니다.
Select star from sales and employees and semicolon.
4:16:26
이제 왜 두 개의 다른 세미콜론을 사용하는지 설명하겠습니다. SQL에 두 개의 별도 쿼리가 있다고 말하는 것입니다.
So now why I'm using two different semicolons because I'm telling SQL we have now two separate queries. They have nothing to do with each other's.
4:16:33
이렇게 실행하면 출력에서 두 개의 결과 그리드를 볼 수 있습니다.
And if you go and execute it like this, and now in the output, you can see we got two result grids.
4:16:38
첫 번째 결과 그리드는 첫 번째 쿼리용이고 두 번째
The first result grid is for the first query and the second
4:16:42
두 번째 쿼리용입니다. 서로 관련이 없습니다.
one for the second query so they have nothing to do with each
4:16:45
나는 이 두 테이블을 탐색하여 어떻게 매핑할 것인지 이해하고자 합니다.
others i just want to explore those two tables in order to understand how
4:16:48
이 두 테이블을 확인하면 둘 다 ID가 있음을 알 수 있습니다.
i'm gonna map those informations so now if we check those two
4:16:51
따라서 이 정보를 매핑할 수 있습니다. 둘 다
tables you can see that both of them has ids so we
4:16:54
이름과 성도 가지고 있습니다.
can map those informations right both of them has
4:16:57
그리고 이름 성 그렇게
as well first name last name so that
4:17:01
즉, 고객의 이름과 성을 함께 매핑할 수 있습니다. 하지만 직원에 대한 정보는 없으므로 무시해야 합니다.
means i can go and map the first name and last name together now in the customers we have country but we don't have this information in the employee so we have We have to go and ignore it.
4:17:10
직원에 대한 점수가 없기 때문에 여기에 점수가 없습니다.
And we have as well here score where we don't have a score for the employees.
4:17:15
즉, 고객과 직원 간의 세 가지 정보를 매핑할 수 있습니다.
That means I can go and map three informations between the customers and employees.
4:17:19
이제 정말로 ID가 필요한지 생각해 볼 수 있습니다. 테이블에 ID가 있는 것이 의미가 없습니다.
Now of course we can go and think do we need really the IDs because it doesn't make really any sense to have the IDs in the tables.
4:17:25
고객 ID와 직원 ID가 있으므로 더 이상 고유하지 않습니다. 그래서 무시할 수 있습니다.
It's not anymore unique because we have here the customer ID one and employee one. So I think we can go and ignore it.
4:17:31
매핑하는 데 유용한 정보는 이름과 성 두 가지뿐입니다. 이제 이 두 가지 정보를 추가해 보겠습니다.
So the only really two information that is useful to map is the first name and last name. So now let's go and add those two informations.
4:17:39
우리는 직원으로부터도 이름과 성, 같은 정보를 필요로 합니다.
So we need the first name, last name and the same information as well from the employees.
4:17:44
이제 모든 것을 하나의 쿼리로 만들고 싶습니다. 그래서 세미콜론을 제거할 것입니다.
But now we want everything to be in one query. That's why I'm going to go and remove the semicolons.
4:17:50
이제 두 쿼리 사이에서 집합 연산자를 사용해야 합니다. 데이터를 결합하기 위해 두 가지 옵션이 있습니다: 유니온 또는 유니온 올.
Now we have to go and use set operators between those two queries. And now in order to combine the data, we have two options, either union or union all.
4:17:57
이 예제에서는 중복에 대한 언급이 없습니다.
In this example, it doesn't mention anything about duplicates and so on.
4:18:01
중복이 있다면 유니온을 사용하여 제거하고 싶습니다. 그래서 그게 전부입니다.
I would like to go with that union in order to remove the duplicates if there is any. So that's it.
4:18:07
이제 실행해 보겠습니다. 출력에서 보시다시피, 우리는 단 하나의 결과만 있습니다.
Let's go and execute it. Now, as you can see in the output, we have only one result because we have only one big query.
4:18:13
고객과 직원의 이름과 성이 있습니다. 쿼리의 순서에 대해 한 가지 더 말씀드리겠습니다.
And now we have the first names and last names from the customers and employees. And now one more thing about the order of the queries.
4:18:19
직원으로 시작하든 고객으로 시작하든 정확히 같은 결과를 얻습니다.
It doesn't matter whether we start with the employees or with the customers, we will get the exact same results.
4:18:24
열의 이름에 주의하세요. 항상 첫 번째 쿼리가 이름을 제어합니다.
But pay attention to the naming of the columns. Always the first query controls the names.
4:18:29
이제 같은 이름을 가지고 있으므로 문제가 되지 않을 것입니다.
But since now they have the same naming, so it should not be a problem.
4:18:33
이 두 테이블을 전환하고 다시 시작하면 정확히 같은 결과를 얻을 것입니다.
So if I go and switch those two tables and start it again, we will get exact same results.
4:18:39
이제 SQL이 유니온을 사용하여 데이터를 결합하는 방법을 이해해 보겠습니다.
So now let's understand how SQL did combine the data using the union.
4:18:43
이제 첫 번째 쿼리와 두 번째 쿼리, 즉 직원과 고객의 결과가 있습니다.
Okay, so now we have here the results from the first query and the second query, employees and customers. And we are combining the data using union.
4:18:51
SQL의 첫 번째 단계는 직원의 첫 번째 쿼리에서 열을 가져오는 것입니다.
The first step in SQL is that it's going to go and take the columns from the first query, which is from the employees.
4:18:56
결과에 첫 번째 이름과 성을 열 이름으로 가져올 것입니다.
So it's going to take the first name, last name as a column name to the results.
4:19:01
이제 다음 단계는 두 테이블 간의 행을 결합하기 시작하는 것입니다.
And now the next step is that is going to go and start combining the rows between those two tables. So first, we're going to go and take the rows from employees.
4:19:08
데이터에 중복이 있는지 확인할 것입니다. 여기에는 중복이 없습니다.
And as well, we're going to check whether there is duplicates in the data. So as you can see, we don't have here any duplicates. So we're going to have the five employees.
4:19:16
이제 고객의 두 번째 쿼리에서 행을 추가하기 시작할 것입니다.
And now the next step is going to start adding rows from the second query from the customers very carefully without generating any duplicates.
4:19:23
출력에 없으므로 결과에 추가할 것입니다. 다음 고객은 케빈 브라운입니다.
We don't have it in the output. That's why it's going to go and add it to the result. And then the next customer, we have Kevin Brown.
4:19:30
결과에 이미 포함되어 있으므로 SQL은 이를 추가하지 않습니다. 그렇지 않으면 중복이 생성됩니다.
as you can see we have it already in the results that's why SQL will not go and add it to the results otherwise it's gonna go and generate duplicates
4:19:37
SQL은 이 고객을 무시할 것이고, 마리도 결과에 있으므로 건너뛸 것입니다. 이제 마크로 넘어갑니다.
so SQL gonna ignore this customer the same thing for Mari we have Mari as well in the results so it's gonna skip it and then we're gonna go to the mark as you can see we don't have mark in the results
4:19:48
SQL은 이 고객을 출력에 추가할 것이고, 마지막으로 안나를 추가할 것입니다. 결과에 안나가 없으므로 추가할 수 있습니다.
that's why SQL gonna go and take this customer and put it in the output and then the last one we have Anna we don't have Anna in the results that's why SQL can go and as well add it to the results and now with this SQL did combine
4:20:00
이 두 테이블 간의 행이 있으며, 여기에는 8명이 있습니다.
the rows between those two tables and we have here eight persons.
4:20:02
SQL이 데이터를 결합하고 있지만 중복을 생성하지 않도록 매우 주의하고 있습니다.
So as you can see, SQL is combining the data, but very carefully not generating any duplicates. All right, so that's it.
4:20:09
이것이 유니온 연산자가 작동하는 방식입니다. 이제 유니온 올이 두 쿼리의 모든 행을 반환합니다.
This is how the union operator works. OK, so now union all union all going to go and return all rows from both queries.
4:20:20
유니온과 매우 유사하며 모든 행을 결합하고 모든 것이 결합된 결과 집합에 표시됩니다.
So it's very similar to union. It's going to go and combine all the rows and everything going to be presented in the combined result sets.
4:20:27
유니온과의 큰 차이점은 유니온 올이 중복을 제거하지 않는다는 것입니다.
But the big difference to the union union all will not remove any duplicates.
4:20:32
중복을 제거하지 않는 유일한 집합 연산자로 모든 행을 그대로 표시합니다.
It is the only set operators that doesn't remove duplicates and it's going to show all the rows as it is.
4:20:38
쿼리에서 행이 10번 나타나면 출력에서도 10번 나타납니다.
So if you have a row 10 times from the query, you will find it as well in the output 10 times.
4:20:44
언제 유니온을 사용하고 언제 유니온 올을 사용해야 하는지 물어볼 수 있습니다.
Now you might ask me when to use union and when to use union all.
4:20:48
그들 사이의 큰 차이점은 유니온 올이 성능이 훨씬 더 좋고 유니온보다 빠르다는 것입니다.
I'm going to say that there is one big difference between them is that union all has way better performance and it's faster than the union.
4:20:56
유니온 올은 중복 제거와 같은 추가 단계를 수행하지 않기 때문입니다.
And that's because Union All doesn't perform additional steps like removing duplicates.
4:21:01
내 쿼리에서 중복이 없다는 것을 이미 알고 있다면 유니온을 사용하지 말고 항상 유니온 올을 사용하세요.
So my friends, that means if you know already that in my queries, there is no duplicates. I know my tables. I know my queries. There is no duplicates.
4:21:09
유니온 올의 또 다른 시나리오는 중복을 보고 싶을 때입니다.
Don't use Union and always use Union All because you will get better performance.
4:21:14
데이터 품질 검사를 수행하고 여러 쿼리를 결합한 후 중복이 있는지 확인하고 싶습니다.
Another scenario for the Union All is that I would like to see the duplicate.
4:21:17
이 상황에서는 유니온 올을 사용합니다. 이제 같은 예를 다시 보겠습니다.
I'm doing data quality checks and I would like to see whether there is duplicate after I combine multiple queries.
4:21:23
고객과 직원이 같은 사람으로 주어집니다.
So in this situation, I go and use as well the union all. Now we have again the same example. We have the customers and employees.
4:21:30
이제 유니온 올을 사용하여 데이터를 결합하면 중복을 포함한 모든 행을 반환할 수 있습니다.
And we have as well the same persons given and Mary as customers and as well as employees.
4:21:35
SQL은 이렇게 유니온 올을 실행할 수 있습니다. 고객과 직원의 모든 것을 반환할 수 있습니다.
So now if you want to combine the data using union all, it can return all rows including duplicates.
4:21:41
그리고 주어진 사람과 메리는 출력에 두 번 나타날 수 있습니다.
So that means SQL can go and execute union all like this. It can return everything from customers and everything from employees.
4:21:49
유니온 올은 두 결과 집합에서 모든 행을 그대로 반환합니다.
And given and Mary can be presented twice in the output.
4:21:52
집합에 중복이 있으면 출력에서도 중복이 발생합니다.
So as you can see, UnionAll is returning all the rows as it is from the two result sets.
4:21:58
케빈과 메리가 출력에 각각 두 번 존재하게 됩니다. 이것이 유니온 올의 작동 방식입니다.
And if there is duplicates in the sets, we will get as well duplicates in the output.
4:22:02
이제 직원과 고객의 데이터를 하나의 테이블로 결합하라는 매우 유사한 SQL 작업이 있습니다.
So Kevin is going to be existing twice in the output and Mary as well twice. So this is how the UnionAll works. All right.
4:22:08
이제 직원과 고객의 데이터를 중복을 포함하여 하나의 테이블로 결합하라는 매우 유사한 SQL 작업이 있습니다.
So now we have very similar SQL task and it says combine the data from employees and customers into one table, including duplicates.
4:22:16
그래서 마지막 작업과 정확히 같습니다. 하지만 이번 작업에서는 중복을 포함하라고 말하고 있습니다.
So it's exactly like the last task. But this time in the task, we are saying include duplicates.
4:22:21
그래서 우리는 union을 사용할 수 없고 union all을 사용해야 합니다.
so we cannot go and use union we have now to go and use union all
4:22:24
우리는 정확히 같은 쿼리를 가질 것이므로 선택하고 있습니다.
we will have the exact same query so we are selecting
4:22:27
직원의 이름과 성, 그리고 고객의 이름과 성을 선택하고 있습니다.
the employees first last name and as well customers first last name and
4:22:31
이제 union을 사용하는 대신 union all을 사용할 것입니다.
now instead of using union we're going to go and use union all
4:22:34
우리가 해야 할 일은 여기로 가서 union all이라고 말하는 것입니다.
so all what we have to do is that to go over here and say union all
4:22:37
이제 이것에 주목하세요. 이전 union에서 볼 수 있듯이,
so now pay attention to this as you can see in the union previously
4:22:41
출력에서 8개의 레코드 또는 8명의 사람이 나왔습니다. 이제 실행해 보겠습니다.
we got eight records or eight persons from the output so now let's go and execute it
4:22:47
결과를 확인해 보세요. 이제 10명이 나왔습니다.
and check their results now as you can see we got now 10 persons
4:22:50
8명이 아니라 10명입니다. 그 이유는 고객이 5명 있기 때문입니다.
instead of eight and that's because we have five customers and
4:22:53
5명의 직원이 있으며 데이터에 중복이 있습니다.
five employees and we have duplicates inside the data we have
4:22:56
여기에서 마리와 같은 중복이 두 개 있습니다.
two duplicates now if you check we have here mari and as well over
4:22:59
여기에서 마리와 같은 중복이 있으며, 케빈도 마찬가지입니다.
here we have mari and same goes for kevin we have given over here
4:23:03
여기에서 마리와 케빈의 중복이 있습니다.
and as well here so we have duplicates inside the data and sql
4:23:06
데이터와 SQL에 중복이 있습니다.
just combined the two tables okay so now we can understand how sql
4:23:09
두 테이블을 결합했습니다. 이제 SQL이 어떻게 작동하는지 이해할 수 있습니다.
execute union all in order to combine data all right again
4:23:12
데이터를 결합하기 위해 union all을 실행합니다.
we have the two results from queries we have the employees and customers and
4:23:16
쿼리에서 두 결과가 있습니다. 직원과 고객이 있습니다.
it's going to do the same steps first gonna go and get the column names
4:23:19
같은 단계를 수행할 것이며, 먼저 열 이름을 가져옵니다.
from the first query and put it in the output it's
4:23:22
첫 번째 쿼리에서 가져와서 출력에 넣습니다.
gonna go and take all the employees and put it in
4:23:25
모든 직원을 가져와서 출력에 넣습니다.
the output without checking anything so that means if there
4:23:28
아무것도 확인하지 않고 출력에 넣습니다.
is duplicates in the data it's gonna be presented as well in the output
4:23:31
데이터에 중복이 있다면 출력에서도 표시됩니다.
it's very simple now it's gonna go to the second step and
4:23:34
이제 매우 간단합니다. 두 번째 단계로 넘어갑니다.
as well take all the customers and append
4:23:37
출력을 이렇게 추가합니다.
it into to the output like this so that's
4:23:40
매우 빠르며 모든 행을 결합할 것입니다.
it it's very fast i'm gonna go and just combine all the rows from
4:23:44
직원과 고객의 모든 행을 가져오면
the employees and all the rows from the customers and with that we're gonna get
4:23:47
10명의 사람을 얻을 수 있습니다.
the 10 persons and as you can see we have duplicates in the data so
4:23:50
결혼한 사람과 제공된 사람이 두 번 있습니다.
we have married twice and given as well twice and that's
4:23:53
그래서 유니온 올이 가장 빠른 이유입니다.
why union all is the fastest it doesn't have any extra steps or checks just taking all rows from all queries and put it in the output all right so as you can see it's very simple right so that's all for the union all
4:24:09
그렇다면 제외는 무엇인가요?
okay so what is except sometimes we call it minus in other databases
4:24:12
SQL 서버에서는 제외라고 부릅니다.
but in sql server we call it except so it's going to go and
4:24:15
첫 번째 쿼리에서 고유한 행을 반환합니다.
return a distinct rows from the first query
4:24:19
두 번째 쿼리에서 찾을 수 없는 행입니다.
that are not found in the second query so
4:24:22
쿼리의 순서가 최종 결과에 영향을 미칠 수 있습니다.
from this definition we can understand that that the order of the queries
4:24:25
첫 번째 쿼리와 두 번째 쿼리가 있습니다.
can affect the final result there is a first query and a second query so it is the only set operator
4:24:31
쿼리의 순서에 주의해야 합니다.
where you have to pay attention to the order of the queries
4:24:34
결과 집합에서 중복을 제거합니다.
and as well it's like the others it's gonna go i remove the duplicates
4:24:38
두 개의 집합이 있습니다.
from the result sets all right again we have this very simple example
4:24:41
고객과 직원이 동일한 사람입니다.
we have two sets five customers five employees and
4:24:44
케빈과 메리입니다.
there is the same persons as a customer and as employees
4:24:47
이제 두 집합을 결합할 것입니다.
kevin and mary so now we're gonna go and combine those two sets using the
4:24:50
첫 번째 테이블에서 고유한 행을 반환합니다.
accepts or sometimes we call it minus so it says it's
4:24:53
두 번째 테이블에 없는 행입니다.
gonna return unique rows in the first table that are not
4:24:56
왼쪽에 고객이 있다고 가정해 보겠습니다.
in the second table so what can happen what is the first table
4:24:59
여기에는 다섯 명이 있습니다.
let's say the customers on the left side so here we have five persons
4:25:03
직원이 아닌 고객이 필요합니다.
joseph mark anna kevin and mary so now
4:25:06
조셉, 마크, 안나에게는 안전합니다.
the rule is we need the customers that are not employees
4:25:09
두 번째 집합에 존재하지 않기 때문입니다.
so it's safe for joseph mark and anna because
4:25:13
그들은 두 번째 집합에 존재하지 않기 때문에 안전합니다.
they are not existing in the second set that's
4:25:16
왜 ISQL이 이 세 가지 값을 반환할 수 있는지, 하지만 이제 두 고객과 메리에게는 문제가 있습니다.
why isql can return those three values but now for the two customers given and mary here there is an issue given and mary they are members
4:25:24
두 번째 집합, 두 번째 테이블인 직원들입니다.
of the second set the second table the employees that's
4:25:27
왜 ISQL이 그들을 출력에서 제외할 것인지입니다.
why isquels gonna go and exclude them from the output
4:25:30
그들은 규칙을 충족하지 않기 때문에
because they are not fulfilling their rule so the
4:25:33
출력은 세 고객과 직원의 모든 값, 고객과 직원 간의 공통 값을 가져올 것입니다.
output will get only three customers and all the values from employees and the common values between customers and employees
4:25:41
출력에서 제외될 것입니다.
will be excluded from the output so
4:25:44
이것이 수용이 작동하는 방식입니다.
this is how the accepts works all right so let's have a very simple skill task and it says find the employees who are not customers at the same time okay so So let's see how we can solve that.
4:25:54
우리는 같은 쿼리를 유지할 것입니다.
We're going to stay with the same queries. As usual, we have the employees and the customers.
4:25:59
모든 것을 포함하는 대신, 우리는 제외라는 집합 연산자를 사용할 수 있습니다.
But instead of having union all, we can use a set operator except.
4:26:03
그래서 이제 제외를 사용하고 있으므로 쿼리의 순서가 올바른지 확인해야 합니다.
So now since we are using except, we have to make sure that the order of the queries are correct.
4:26:06
첫 번째 쿼리는 직원들입니다.
So the first query is the employees, which is correct because we have to find the employees who are not customers at the same time.
4:26:15
작업이 동시에 직원이 아닌 고객을 찾으라고 하면, 우리는 그것을 전환해야 합니다.
So we are focusing on the employees. The first table is correct. And the second table is customers.
4:26:20
우리는 먼저 고객을 쿼리해야 합니다.
If the task says find the customers who are not employees at the same time, then we have to go and switch it.
4:26:26
이제 출력에서 우리는 동시에 고객이 아닌 세 명의 직원을 봅니다.
We have first to query the customers. So now everything is correct. Let's go and execute it.
4:26:31
하지만 우리가 아는 것처럼, 다섯 명의 직원이 있습니다.
And now in the output, we see three employees who are not customers at the same time. So we have Carol, Frank and Michael.
4:26:38
이제 제가 정보를 전환하면 어떤 일이 일어날 수 있는지 보여드리겠습니다.
But as we know, we have five employees, Kevin and Mary. They are not here in the result because they are customers as well.
4:26:44
고객부터 시작하고 직원으로 넘어갑니다.
So now let me show you what can happen if I just switch those informations.
4:26:48
실행해 보겠습니다.
so we start with customers and then with employees let's
4:26:51
이제 우리는 고객 정보를 얻고 있습니다.
go and execute it as you can see we're going to get completely different results
4:26:54
이제 출력에서 우리는 세 명의 고객을 얻었습니다.
now we are getting customers informations and
4:26:57
동시에 직원이 아닌 고객입니다.
now in the output we got three customers who are not
4:27:00
이렇게 하면 잘못될 것입니다.
employees at the same time this is not what you want from this task
4:27:03
고객을 먼저 실행하고 이제 이해해 봅시다.
so if you do it like this it's going to be incorrect so pay always attention here to the order of that query so now let's go and correct it so we're going to have first employees and then
4:27:12
고객을 실행해 보겠습니다.
customers let's execute it and now let's go and understand
4:27:15
isql이 except 연산자를 어떻게 실행하는지
how isql execute the except operator all
4:27:18
다시 말해, 두 쿼리 또는 두 테이블의 결과가 있습니다.
right so again we have the results from the two queries or from two tables
4:27:21
이제 우리는 그들 사이에서 except를 수행하고 있으니, 어떻게 되는지 봅시다.
and now we are doing except between them so let's see how
4:27:24
isql은 그것을 실행할 것이고, 평소처럼 먼저 이름을 가져올 것입니다.
isql gonna execute it it's gonna take as usual first the names
4:27:28
첫 번째 쿼리에서 직원의 이름을 가져와서 출력에 넣고, 이제 isql은 출력에 첫 번째 쿼리의 데이터만 표시할 것입니다.
from the first query from the employees and put it in the output and now isql gonna present data only from the first query in the output and it's gonna go and use the customers only as a check.
4:27:39
SQL은 고객의 데이터나 역할을 넣지 않을 것입니다.
So SQL will not put any data or roles from the customers.
4:27:43
단지 두 번째 쿼리를 조회로 사용하여 데이터를 확인할 것입니다. 그래서 첫 번째 직원부터 시작할 것입니다.
It will just use the second query as a lookup in order to check the data. So it's going to start with the first employee.
4:27:50
솔직히, 고객에게 frank이 있나요? 글쎄요, 없습니다.
Frankly, do we have frankly in the customers? Well, no, we don't have it.
4:27:54
그래서 SQL은 그것을 수용하고 출력에 넣을 것입니다. 그리고 다음 단계에서 SQL은 두 번째 직원으로 가서 확인할 것입니다.
That's why SQL is going to accept it and put it in the output. And then in the next step, SQL is going to go to the second employee and check.
4:28:01
보시다시피, 우리는 이미 고객에게 그것이 있습니다. 그래서 SQL은 그것을 무시할 것입니다.
As you can see, we have it already in the customers. So SQL is going to go and ignore it.
4:28:06
출력에 있어서는 허용되지 않습니다. mari도 고객에게 있습니다.
it's not allowed to be in the output the same thing for
4:28:09
그래서 출력에 표시되지 않을 것입니다. michael은 고객에게 없습니다.
mari we have it as well in the customers that's why it
4:28:12
그래서 출력에 표시될 수 있습니다. carol에 대해서도 마찬가지입니다.
will not be presented in the output so michael we
4:28:15
고객에게 michael이 없기 때문에 출력에 표시될 수 있습니다.
don't have michael in customers that's why it
4:28:18
carol도 고객으로 없기 때문에 마찬가지입니다.
can be presented in the output and as well for carol
4:28:21
우리는 고객으로 캐롤이 없다는 같은 상황입니다.
the same thing we don't have carol as a customer and
4:28:25
출력에서 볼 수 있듯이 우리는 첫 번째 테이블에서만 데이터를 가져오고 두 번째 테이블은 정보를 확인하는 데만 사용됩니다.
we're gonna have it in the output so as you can see we will get data only from the first table and the second table only gonna be used in order to check the information
4:28:33
따라서 출력에는 고객이 없고 직원만 있습니다.
from it so we don't have in the output any customers it's only employees
4:28:37
이제 테이블을 전환하면 어떤 일이 발생하는지 빠르게 확인해 보겠습니다.
so now let's check quickly what's gonna happen if we switch the tables so
4:28:40
이제 고객이 첫 번째 테이블로 설정되어 데이터를 가져오게 됩니다.
now we have the customers as the first table is going to take the
4:28:43
첫 번째 테이블의 열을 가져와서 고객 정보를 출력에 표시하기 시작합니다.
columns from the first table and kind of start presenting the
4:28:46
고객 정보를 출력에 표시하고 직원은 조회용으로만 사용됩니다.
customers informations in the output and gonna go and use the
4:28:50
조셉은 직원에 없고, 케빈과 메리는 이미 직원에 있으며, 마크와 안나는 직원의 일부가 아닙니다.
employees only as a lookup so do we have joseph we don't have it in the employee and then kevin and mary we have it already in the employees and Mark and Anna are not part of the employees.
4:29:01
그래서 SQL은 이렇게 출력에서 결과를 표시할 수 있습니다.
That's why SQL can go and present the results in the output like this.
4:29:05
이제 보시다시피 SQL은 고객 테이블에 집중하고 있으며, 직원이 아닌 고객으로부터 데이터를 가져오고 있습니다. 직원은 확인용으로만 사용됩니다.
So now, as you can see, SQL is focusing on the table customers and we are getting data from the customers, not from the employees employees is only as a check.
4:29:13
그래서 이를 통해 우리는 쿼리의 순서가 예외에 대해 매우 중요하다는 것을 이해합니다. 순서가 다르면 다른 결과를 얻을 것입니다.
So with that, we understand the order of the queries is very important for the exceptions. We will get different results if we have different order.
4:29:20
좋습니다, 그래서 이것이 except 연산자에 대한 모든 것입니다. 알겠죠?
All right, so that's all for the except operator. okay
4:29:27
그렇다면 intersect는 무엇인가요? intersect는 제가 반환할 것입니다.
so what is intersect intersect gonna go i return
4:29:30
두 쿼리에서 공통된 행만 있습니다.
only row that are common in both queries it's
4:29:34
내부 조인과 매우 유사한 것이고, 여기서 나는
something very similar to the inner join and as well here i'm
4:29:37
중복을 제거할 것이므로 출력에 중복이 없을 것입니다. 다시 말해, 우리는 다섯 명의 고객과 다섯 명의 직원이 있는 매우 간단한 예제를 가지고 있으며, 이제 우리는 교차를 사용하여 이들을 결합할 것입니다.
gonna go i remove duplicates so there will be no duplicates in the output all right again we have this very simple example where we have five customers and five employees and now we're gonna combine them using the intersect
4:29:48
교차가 하는 것은 두 테이블 간의 공통 행을 반환하는 것입니다. SQL은 이를 어떻게 실행할까요? 매우 간단합니다.
So what intersects does it going to go and return common rows between two tables. So how is SQL going to execute it? It's very simple.
4:29:55
공통 값을 검색할 것입니다. 공통 값은 무엇일까요?
It's going to go and search for the common values. So what are the common values?
4:30:00
케빈과 메리이며, SQL은 이 두 값만 반환하고 나머지는 결과에서 제외됩니다.
It's Kevin and Mary and SQL gonna return only those two values given and Mary and all others gonna be excluded from the results.
4:30:09
매우 간단하죠? 공통 값만 반환할 것입니다. 이것이 SQL에서 교차가 작동하는 방식입니다.
It's very simple, right? It's gonna go and return only the common values. And this is how the intersect works in SQL.
4:30:14
좋아요, 이 간단한 작업을 해봅시다. 직원이면서 고객인 사람을 찾으라고 합니다.
Okay, let's have this simple task and it says find the employees who are also customers.
4:30:19
우리는 직원과 고객에 대한 동일한 쿼리를 가질 수 있습니다.
So we can have the same queries, employees and customers.
4:30:22
하지만 제외 대신 교차를 사용할 것입니다. 직원과 고객 간의 공통 정보를 찾고 있기 때문입니다.
But instead of having except we're going to go and use intersects since we are finding the common information between the employees and customers.
4:30:30
매우 간단하고 직관적입니다. 실행해 봅시다. 그러면 케빈과 메리를 얻을 것입니다.
It's very simple and straightforward. Let's go and execute it. And with that, we're going to get that Kevin and Mary.
4:30:35
이 두 사람은 동시에 직원이자 고객입니다.
This is the two persons that are at the same time employees and customers.
4:30:40
물론 쿼리의 순서에 주의할 필요는 없습니다. 고객이면서 직원인 사람을 찾으라고 해도 동일할 것입니다.
And of course, you would don't have to pay attention to the order of the queries. It's going to be the same if we say find the customers who are also employees.
4:30:47
예를 들어, 고객과 직원을 바꾸면 결과가 동일하다는 것을 알 수 있습니다.
So if you go and just switch, for example, the customers with employees, you will see that.
4:30:52
정확히 같은 결과를 얻을 것이므로 어떤 쿼리가 먼저인지 상관하지 않습니다.
will get the exact same results so it doesn't matter which
4:30:55
첫 번째 쿼리가 정의하는 이름에 주의하세요.
query is first again pay attention to the first query that define
4:30:58
이제 SQL이 교차를 어떻게 실행하는지 이해해 봅시다.
the names so now let's understand how is scale execute intersects behind
4:31:02
우리의 두 테이블이 다시 있고, 이제 우리는 교차를 수행하고 있습니다.
the scenes okay again our two tables and now we are doing intersects
4:31:06
따라서 일반적으로 첫 번째 쿼리에서 열을 가져올 것입니다.
so as usual is going to go and take the columns from the first
4:31:09
이제 우리는 이 두 결과 간의 공통 데이터를 찾을 것입니다.
query and now we're going to go and find the common data between those
4:31:12
행별로 수행할 것이므로, 우리는
two results so it's going to do it row by row so we have
4:31:15
직원 프랭크가 고객으로 있는지 확인합니다. 아니요.
the employee frank do we have it as a customer no so it
4:31:19
출력에 포함되지 않을 것입니다.
will not be in the output given brown we have it in the
4:31:22
여기서 고객으로서도 직원으로서도 존재합니다.
employees and as well as a customer over here so that's why
4:31:25
마이클과 캐롤은 고객이 아닙니다.
we will get it in the output the same thing for mary so we have mary as employee and as well as customer so we're gonna have it in the output
4:31:32
그들은 단지 직원입니다.
michael and carol they are not customers they
4:31:35
고객인 조셉도 마찬가지입니다.
are only employees that's why we will not get it in the output
4:31:38
우리는 마크와 안나를 가지고 있지 않습니다.
the same thing goes for the customers joseph we don't have
4:31:42
따라서 우리는 두 개의 공통 정보를 얻을 것입니다.
mark we don't have anna because they are not employees so
4:31:45
테이블이나 두 개의 쿼리로 시작하든 상관없습니다.
with that we're gonna get only the common informations between the two
4:31:48
결국 우리는 같은 정보를 얻을 것입니다.
tables or two queries and it doesn't matter whether we start with
4:31:51
모든 것이 매우 간단합니다.
customer or with employees we will get at the end the same
4:31:54
이것이 SQL에서 교차점이 작동하는 방식입니다.
information all right so that's all it's very simple right this is
4:31:58
SQL에서 교차점이 작동하는 방식
how the intersect works in sql all
4:32:04
좋은 친구들, 이제 데이터 분석이나 데이터 엔지니어링 프로젝트에서 세트 연산자를 어떻게 사용하는지 보여드릴 부분에 왔습니다. 여기 세트 연산자의 가장 중요한 사용 사례가 있습니다.
right friends so now we come to the part where i'm going to show you how i usually use the set operators in my projects for data analysis or for data engineering so here are the most important use cases for the set operators
4:32:16
좋습니다, 첫 번째 사용 사례는 데이터 분석을 하기 전에 유사한 테이블을 결합하는 것입니다.
Alright, the first use case is combining similar tables before doing data analysis.
4:32:22
어떤 시나리오에서는 보고서를 생성하고 유사한 테이블 위에 유사한 쿼리를 작성하게 됩니다.
In some scenarios, we want to generate a report and we end up writing similar queries on top of similar tables.
4:32:28
그리고 마지막에 모든 쿼리의 결과를 조인하여 최종 보고서를 제시합니다.
And we go at the end and join all the results from the queries in order to present the final report.
4:32:34
이제 그렇게 하는 대신, 먼저 모든 유사한 정보를 하나의 테이블로 결합할 수 있습니다.
And now instead of doing that, what we can do, first we can go and combine all the similar informations into one table.
4:32:40
그 위에 쿼리, 데이터 분석을 수행하여 보고서를 생성할 수 있습니다.
And then we can do on top of it a query, a data analysis in order to generate a report.
4:32:45
그리고 우리는 유니온 또는 유니온 올을 사용하여 이를 할 수 있습니다.
and we can do that using the union or union all let's
4:32:48
몇 가지 예를 들어보겠습니다. 예를 들어, 직원, 고객, 공급업체 및 학생이라는 네 개의 테이블이 있다고 가정해 보겠습니다.
have a few examples so let's say that we have four tables employees
4:32:51
보시다시피, 이 모든 테이블은 동일한 정보를 공유하고 있습니다.
customers suppliers and students so as you can see
4:32:54
그들은 사람에 대한 데이터를 보유하고 있습니다. 이제 데이터베이스에서 조직의 모든 개인을 포함하는 보고서를 생성한다고 가정해 보겠습니다.
all of them are sharing the same informations they
4:32:58
당신이 하게 될 일은 직원에 대한 SQL 쿼리를 작성하고 고객에 대한 또 다른 쿼리를 작성하는 것입니다.
hold data about persons so now let's say that you are generating a
4:33:01
그리고
report that requires all the individuals in
4:33:04
이렇게 됩니다.
the organization in the database so what you're going to end up doing is writing a SQL query for the employees another one for customers and as
4:33:12
공급업체와 학생들을 위해서도 SQL 쿼리를 작성할 것입니다.
well for the suppliers and the students and then you're gonna go
4:33:15
이제 이 쿼리들의 결과를 최종 보고서에 통합할 것입니다.
and merge all the results from those queries into the
4:33:19
이 설정의 문제는 많은 유사한 쿼리가 있다는 것입니다.
final report now the issue with this setup is that you
4:33:22
여기서 네 번 반복되고 있습니다. 이제 발생할 수 있는 일은
are having a lot of queries a lot of similar queries
4:33:25
첫 두 쿼리의 논리를 변경하고
so you have it here four times and now what might happen at
4:33:28
나중에 다른 두 쿼리에도 적용하는 것을 잊어버리면
that you go and change the logic of the first two queries and
4:33:31
보고서에서 매우 일관성 없는 데이터를 얻게 됩니다. 그래서 대신
you forget later to do it for the other two and you will get really inconsistent data in the reports so instead of that what we
4:33:39
집합 연산자를 사용하여
do we can go and use the set operators in order to
4:33:42
모든 테이블을 하나의 큰 테이블로 결합할 것입니다.
combine first all those tables in one big
4:33:45
그렇게 하기 위해 우리는 유니온을 사용할 것입니다.
table so what we're gonna do we're gonna go and use a union in
4:33:48
이 네 개의 테이블을 하나의 테이블로 결합하기 위해서입니다.
order to combine those four tables into the table
4:33:51
직원들의 모든 행을 가져와서 인물 테이블에 넣을 것입니다.
persons so we're gonna have it like this so we will get all the
4:33:54
고객, 공급업체, 학생들의 모든 행을 가져와서
rows from the employees and put it in the persons all the rows
4:33:57
하나의 큰 테이블에 모든 정보를 넣을 것입니다.
from the customers from the suppliers and as well from the students and put everything in one big table that holds all the informations about the individuals that we have inside our database.
4:34:09
데이터를 결합한 후 다음 단계는 이 새로운 큰 테이블을 분석하기 위한 SQL 쿼리를 작성하는 것입니다.
And now the next step after we combine the data, now we write an SQL query in order to analyze this new big table and the result going to be presented in their reports.
4:34:20
여기서의 장점은 데이터 분석가를 위한 SQL 쿼리가 하나만 있다는 것입니다.
And now of course, the advantage here is that we have only one SQL query for the data analyzers on top of this table instead of having it four times.
4:34:28
SQL 쿼리의 논리를 변경하면 데이터베이스의 모든 데이터에 자동으로 적용됩니다.
And now if you go and change the logic of the SQL query, it can be applied automatically on all the data that you have in the database.
4:34:35
우리는 이미 직원과 고객 간의 데이터를 결합한 예제를 수행했습니다.
And we have done already this example where we have combined the data between the employees and customers.
4:34:40
보고서를 작성하기 전에 데이터를 결합해야 하는 또 다른 시나리오입니다.
Another scenario where we have to combine data before doing any reporting that sometimes the database developers tend to divide a table one big table into multiple small tables in order to optimize the performance.
4:34:52
예를 들어, 연도별로 주문을 나누는 것입니다.
For example, here splitting the orders by the year, we have orders 2022 2023.
4:34:57
이제 다시, 각 테이블에 대한 쿼리를 작성하거나
Now again, here if you want to generate a report in in order to analyze the orders over the years over the time either you're going to go and make a query for each of those tables
4:35:07
모든 테이블을 결합하여 하나의 주문 테이블을 만들 것입니다.
or you're going to go first combining all those tables into
4:35:11
모든 테이블 간에 유니온을 사용하여 중앙 테이블을 생성할 것입니다.
one table called orders so what we're going to do
4:35:14
첫 번째 테이블의 모든 행과 다음 테이블의 모든 행을 포함할 것입니다.
we're going to use a union between all those tables in order to generate one central table called the orders so all the rows from the first table and all rows from the next table
4:35:24
다음 것과 마지막 것이라서 우리는
the next one and the last one so we're
4:35:28
모든 것을 하나의 피크 테이블에 넣을 것이고, 주문이 생기면
gonna put everything in one peak table and once we have the orders
4:35:31
우리는 분석 SQL 쿼리를 작성할 것입니다.
we're gonna go and write analytical SQL query on
4:35:34
주문 상단에서 보고서를 생성하기 위해
top of the orders in order to generate the
4:35:37
데이터 분석을 준비하는 데 매우 중요한 단계입니다.
report so as you can see it's very important step in order to prepare
4:35:41
데이터를 분석하기 전에
the data before doing data analysis okay so
4:35:44
다음 SQL 작업을 수행해 보겠습니다. 주문은 별도의 테이블에 저장되어 있습니다. 주문과 주문 아카이브가 있습니다. 중복 없이 모든 주문 데이터를 하나의 보고서로 결합하세요.
now let's have the following SQL task and it says the orders are stored in separate tables we have the orders and orders archive now combine all orders data into one report without duplicates.
4:35:55
작업을 보면 두 개의 테이블, 주문과 주문 아카이브를 결합해야 합니다. 따라서 유니온 또는 유니온 올입니다.
Okay, so by looking to the task, we have to combine two tables, orders and orders archive. So either union or union all.
4:36:02
작업에 중복 없이 결합하라고 하므로 유니온을 사용해야 합니다.
But since the task says without duplicates, that means we have to go with the union.
4:36:06
데이터를 결합하기 전에 주문과 주문 아카이브의 내용을 이해해야 합니다.
But now before we combine any data, we have first to understand the content of the orders and the orders archive in order to map the columns correctly.
4:36:14
먼저 두 테이블을 탐색해야 합니다. 그러니 시작해 보겠습니다.
So first we have to go and explore the two tables. So let's start with
4:36:19
주문에서 데이터를 선택하는 것으로 시작하겠습니다. 세미콜론
selecting the data from orders everything semicolon
4:36:23
그리고 두 번째 테이블인 판매에서
and as well from the second table sales
4:36:27
주문 아카이브와 세미콜론
orders archive and as well semicolon
4:36:30
이제 실행해 보겠습니다. 출력에서
so let's go and execute it so now in the output
4:36:33
두 개의 결과가 나옵니다. 두 개의 별도 쿼리가 있기 때문입니다.
we get two results because we have two separate queries the first
4:36:36
첫 번째 결과는 주문에 대한 것이고, 두 번째는 주문 아카이브에 대한 것입니다.
result is for the orders and the second one is for the orders
4:36:40
주문 아카이브를 조금 더 크게 만들어 보겠습니다.
archive let me just make it a little bit bigger and
4:36:43
거의 동일한 테이블이 있습니다. 주문 ID, 제품 ID, 고객 ID가 있습니다.
now as you can see we have almost identical tables so as you can see we have the order id product id customer
4:36:49
모든 것이 동일하게 보입니다.
id so everything looks like identical
4:36:52
물론 객체 탐색기를 사용하여 확인할 수 있습니다.
and of course we can go and check that using the object explorer
4:36:55
왼쪽에 주문이 있습니다.
on the left side so we have here the orders and
4:36:59
여기 열이 있습니다. 주문으로 가면
those are the columns and if you go to the orders
4:37:02
주문 아카이브에서 동일한 열이 있습니다.
archive you can see that we have the
4:37:06
모든 열을 주문에서 주문 아카이브로 매핑할 수 있습니다.
exact same columns so that means we can go and map all
4:37:09
주문에서 모든 열이 주문 아카이브로 옵니다.
comes from orders with all columns of orders archive
4:37:12
그래서 가서 그걸 해봅시다. 저는 그냥 제거할 것입니다.
so let's go and do that so i'm just going going to remove
4:37:15
모든 세미콜론을 제거한 후, 우리는 유니온을 사용할 것입니다.
all semicolons and then we're going to go and use the union so
4:37:18
이제 우리는 하나의 쿼리에 모든 것을 가지고 있으니 실행해봅시다.
now we have everything in one query let's go and execute
4:37:21
이제 우리는 출력에서 하나의 단일 결과를 얻을 것입니다.
it now we will get in the output one single result one
4:37:25
모든 정보가 포함된 단일 테이블과 함께.
single table with all informations from orders and
4:37:28
주문 아카이브에서 모든 주문을 이제 하나의 테이블에 가지고 있습니다.
orders archives so we have all orders now in
4:37:31
현재 모든 것이 일치하고 있습니다.
one table and everything currently is matching so
4:37:34
이로써 우리는 작업을 해결했습니다. 우리는 모든 주문이 포함된 하나의 결과를 가지고 있습니다.
with that we have solved the task we have one result with all orders we don't have any duplicates since we are using union and we have combined the
4:37:41
데이터는 있지만, 이 솔루션에는 한 가지 문제가 있습니다.
data but now we have one issue with that this solution
4:37:44
이 쿼리는 빠르고 지저분하며, 실제로는
this query is quick and dirty and actually it's
4:37:48
최고의 관행을 따르지 않고 있습니다. 그래서 이제 최고의 관행은
not following the best practices so now the best practices here is
4:37:51
각 쿼리에서 모든 열을 명확하게 나열하는 것입니다.
to list clearly all the columns in each
4:37:54
별표를 사용하지 않고, 이제 가서 그렇게 해봅시다.
query without using star all right so now let's go and do that now
4:37:57
주문 테이블에서 모든 열의 목록이 필요합니다.
we need a list of all columns from the table orders
4:38:00
주문 아카이브 테이블과 함께, 많은 열이 있으니
and the table orders archive and since we have a lot of columns what we're gonna do we go to object explorer right click on the table name and then let's go select
4:38:09
상위 천 개의 행을 선택합시다.
the top thousand rows so let's click on that and
4:38:12
이제 우리는 모든 열 이름이 포함된 매우 간단한 선택 문을 얻을 것입니다.
now we're going to get a very simple select statements where we have all
4:38:15
이것이 제가 일반적으로 모든 열이 필요한 경우 하는 일입니다.
the column names from the table orders this
4:38:18
그래서 가서 복사하고 쿼리로 돌아갑시다.
is what i usually do if i need all the columns in my select statements
4:38:21
첫 번째 별표를 그것들로 교체합시다.
so let's go and copy it and go back to our query then
4:38:25
열을 교체하고, 주문 아카이브에도 같은 작업을 할 것입니다.
let's go replace the first star with those
4:38:29
쿼리를 보기 위해 이것을 작게 만듭시다.
columns and we're going to do the same thing as well for the orders archive since they have the same names so let's go and do that as well so let
4:38:36
이제 우리는 주문 테이블에 대한 선택이 있습니다.
just make this smaller in order to see the query
4:38:40
모든 열이 포함된 선택과 함께.
so now we have a select for the table orders
4:38:43
주문 아카이브 테이블에 대한 모든 열이 포함된 선택과 함께.
with all columns and as well a select with all columns
4:38:46
주문 아카이브 테이블을 위해 실행해 보겠습니다.
for the table orders archive so let's go and execute
4:38:49
이제 같은 결과를 얻으려고 합니다.
it and of course now we're going to go and get the same results now
4:38:52
왜 이렇게 하는지 궁금할 수 있습니다. 왜 스타를 고수하지 않았을까요?
you might ask why we are doing this why didn't we stick with the
4:38:56
스타는 빠르고 간단합니다. 그 이유는 다음과 같습니다.
star it's quick as simple well for the following reason
4:38:59
현재 상태는 모든 것이 일치하고 있습니다.
so now currently the status is that everything is matching we
4:39:02
우리는 100개의 동일한 테이블을 가지고 있지만, 시간이 지나면서 개발을 하다 보면 주문 테이블의 스키마를 변경할 수 있습니다.
have 100 identical tables but what What happened with the time is that we do development in our solution and we might go and change the schema of the table orders.
4:39:11
그래서 우리는 이름을 바꾸거나 새로운 열을 추가하거나 열을 바꿀 수 있습니다.
So we might rename stuff, we might add a new columns or maybe switch the columns.
4:39:17
이것은 시간이 지나면서 주문 테이블이 아카이브와 더 이상 동일하지 않다는 것을 의미합니다.
So this means the table order with the time will not be any more identical with the archive.
4:39:23
이 테이블에서 주문을 개발하고 두 열을 스위치했다고 가정해 보겠습니다.
And this is, of course, a problem if you are mapping the data blindly using the star. So now let me show you what I mean.
4:39:29
어떤 이유로 인해 이제 제품이 먼저 나오고 그 다음에 주문 ID가 나옵니다.
Let's say that in this table we are developing the orders and we just switch those two columns in the schema.
4:39:35
이제 제품 ID가 먼저 나오고 그 다음에 주문 ID가 나옵니다.
for some reason so now we have the product
4:39:38
이제 실행해 보겠습니다. 스타를 사용하고 있다면 눈치채지 못할 것입니다.
id first and then the order id so let's
4:39:42
이 정보를 보지 못할 것입니다. 하지만 스크립트를 사용하면 보게 될 것입니다.
go and execute it now if you are using star you will not notice
4:39:45
여기서 우리는 먼저 주문 ID가 나오고 그 다음에 제품 ID가 나오며, 반대의 경우도 있습니다.
this information but if you are using script you gonna see
4:39:48
여기서 우리는 주문 ID가 나오고 갑자기 제품 ID가 나오는 문제를 볼 수 있습니다.
immediately that here we have first the order id and then product id and here we have the opposite so it's more clear listing the columns than using the star and now as you can see in the output
4:40:00
그래서 우리는 잘못된 데이터가 발생하여 잘못된 분석으로 이어질 것입니다.
You can see that we have a problem that here we have order IDs and then suddenly we have something like the product ID.
4:40:08
따라서 여기서 최선의 방법은 스타를 사용하지 않고 모든 열을 명확하게 나열하는 것입니다.
So we're going to have incorrect data which leads to incorrect analyzes.
4:40:11
데이터를 결합할 때 제가 일반적으로 사용하는 또 다른 기술은 쿼리 안에 데이터의 출처를 추가하는 것입니다.
So here the best practice is to not use a star and to clearly list all the columns.
4:40:16
무슨 뜻인지 아시겠죠? 여기서 주문 ID 1을 가진 두 개의 주문이 있습니다. 이들은 중복이 아닙니다.
Now one more technique that I usually use once I'm combining data is that I add the source of the data inside the query.
4:40:23
이들은 완전히 다른 정보입니다. 그리고 이는 서로 다른 테이블에서 온 것입니다.
So what I mean with that? Now you can see that we have here two orders with the order ID 1. They are not duplicates.
4:40:29
제가 일반적으로 하는 것은 각 레코드의 출처를 추가하는 것입니다.
They are completely different informations. And that's because they come from different tables.
4:40:34
사용자들이 이 레코드가 어디서 왔는지 이해하는 데 정말 유용한 정보입니다.
So what I usually do, I go and add the source of each record.
4:40:38
예를 들어 첫 번째 열에 '주문'이라는 단어를 가질 것입니다.
It's really nice information for the analytics for the users to understand where this record come from. So how are we going to do that?
4:40:44
그리고 우리는 이를 '출처 테이블'이라고 부를 것입니다.
We're going to have, for example, on the first column, the following word, let's say orders.
4:40:50
두 번째 쿼리에서도 같은 작업을 할 것입니다. 여기서 출처 테이블은 주문이 아닙니다.
And we're going to call it, let's say that's source table.
4:40:54
그리고 두 번째 쿼리에서도 같은 작업을 할 것입니다, 맞죠? 여기서 소스 테이블은 주문이 아닙니다.
And we're going to do the same thing as well in the second query, right? So the source table here is not the orders.
4:41:01
주문 아카이브입니다. 그래서 저는 쿼리에 정적 열을 추가하여 테이블의 소스를 볼 수 있습니다.
It's the orders archive. So I'm just adding a static columns to my query in order to see the source of the table.
4:41:09
이제 여기 두 가지 다른 값이 있습니다. 실행해 보겠습니다.
So now we have here two different values and let's go and execute it.
4:41:13
이제 우리는 소스 테이블이라는 새 열을 만들었고, 여기에는 두 가지 값만 있습니다. 주문과 주문 아카이브입니다.
And now you see we have created a new column called source table where it has only two values. We have the orders and the orders archive.
4:41:19
주문 ID로 데이터를 정렬해 보겠습니다. 주문 ID로 정렬하겠습니다. 실행해 보겠습니다.
Let's go and sort the data by the order ID. So order by order ID. So let's go and execute it.
4:41:26
이제 매우 명확하게 볼 수 있습니다. 첫 번째 주문, 주문 ID 1은 주문 테이블에서 왔고 두 번째는 주문 아카이브에서 왔습니다.
And now you can see it very clearly. The first order, order ID one comes from the table orders and the second one comes from the orders archive.
4:41:34
이것은 여러 테이블을 결합할 때 데이터에 추가할 수 있는 정말 좋은 정보입니다.
So this is really nice information that you can add to your data once you are combining multiple tables.
4:41:39
이것은 서로 다른 테이블 간의 데이터를 결합하는 사용 사례에 대한 모든 것입니다.
So that's all about this use case on how to combine data between different tables.
4:41:43
좋습니다, 이제 집합 연산자에 대한 또 다른 사용 사례가 있습니다.
All right, now we have another use case for the set operators.
4:41:50
이것은 데이터 엔지니어를 위한 것입니다. 우리는 두 데이터 배치 간의 차이를 찾기 위해 제외를 사용할 수 있습니다.
It's more for data engineers. We can use the except in order to find the delta between two batches of data.
4:41:57
예를 들어, 데이터 엔지니어는 소스 시스템에서 데이터 웨어하우스나 데이터 레이크로 매일 새로운 데이터를 로드하기 위해 데이터 파이프라인을 구축합니다.
For example, data engineers build data pipelines in order to load daily new data from the source systems to a data warehouse or a data lake.
4:42:06
이 데이터 파이프라인에서 소스 시스템에서 생성된 새로운 데이터를 식별하기 위한 논리를 구축해야 합니다.
Now in those data pipelines, we have to build a logic in order to identify what are the new data that is generated from the source system in order to insert it in the data warehouse.
4:42:16
이를 수행하는 한 가지 방법은 집합 연산자 제외를 사용하여 현재 데이터를 이전 로드와 비교하는 것입니다.
One way to do it is to use the set operator except in order to compare the current data with the previous load.
4:42:23
첫 번째 날에 두 고객이 있다고 가정해 보겠습니다.
Let's have a very simple example in the day number one we have two customers
4:42:26
하나와 둘이 있습니다. 이 날에 무슨 일이 일어날까요? 우리는 로드할 것입니다.
one and two so what's gonna happen in this day we're gonna go and load
4:42:29
이 두 고객을 데이터 웨어하우스에 로드할 것입니다. 그래서 데이터에서
those two customers into the data warehouse so in the data
4:42:33
데이터 웨어하우스에서 우리는 또한 하나와 둘을 얻을 것입니다. 그래서 이것은 첫 번째 날입니다.
warehouse we will get as well one and two so this is for
4:42:36
첫 번째 날에는 특별한 일이 없습니다. 우리는 데이터를 있는 그대로 로드합니다.
the first day nothing is crazy we just load the data as it is
4:42:39
이제 두 번째 날에는 소스 시스템에서 새로운 데이터를 가져올 것입니다.
now for the second day we will get a new data from the
4:42:42
소스 시스템에서 이렇게 보일 것입니다. 이제 두 번째 날을 확인하면
source system and it gonna look like this so now if you check the second day you
4:42:45
고객 번호 1이 다시 나타나고, 우리는 이미 데이터 웨어하우스에 로드했습니다.
can see that we have again the customer number one we have already loaded to the data warehouse so we have it as the previous day
4:42:52
하지만 새로운 고객, 고객 ID 3이 있습니다.
but we have a new customer customer id number three so
4:42:55
이제 새로운 데이터만 로드하기 위해 고객 번호 1을 다시 로드할 필요가 없습니다.
now in order to load only the new data we don't need
4:42:58
우리가 할 수 있는 것은 두 번째 날과 이전 로드인 첫 번째 날 사이의 제외를 수행하는 것입니다.
to load again the customer number one what we can do
4:43:01
우리가 할 수 있는 것은 첫 번째 날과 두 번째 날의 고객 번호 1을 제외하는 것입니다.
we can do and accept between the day number
4:43:05
이전 로드와 함께 두 번째
two with the previous load with the day number one so
4:43:08
이 두 세트 사이에서 단순히 수행하고 수용한다면
now if we simply do and accept between those two sets
4:43:11
우리는 새로운 데이터를 식별할 것입니다
we're gonna go and identify the new data
4:43:14
소스 시스템에 존재하는 데이터입니다
that is existing in the source system which is only the
4:43:17
기록 번호 3입니다. 이제 우리가 수용한다면
record number three so now what can happen if we do accept between day
4:43:20
이틀과 하루 사이에서 하나의 기록을 얻을 것입니다
two and day one we will get one record the
4:43:23
새로운 기록을 내부에 삽입할 것입니다
new record that we're gonna go and insert it inside
4:43:26
우리 데이터 웨어하우스에 삽입할 것입니다
our data warehouse so as you can see this set operator except is very
4:43:29
이 집합 연산자는 두 세트를 비교하는 데 매우 강력합니다
powerful in order to compare two sets and not
4:43:33
데이터 분석을 위해서만 사용할 수 있는 것이 아닙니다
only for data analysis we can use it as you can see for data engineering in order to identify what is the new data that is generated from the sources in order to insert it inside our data warehouse
4:43:48
데이터 마이그레이션을 수행하는 경우 사용할 수 있습니다
okay one more use case for the set operators that i personally use a lot in my project
4:43:52
데이터 품질을 확인하기 위해 수용할 수 있습니다
that if you are doing data migrations you can use
4:43:55
데이터 완전성을 확인하기 위해 사용할 수 있습니다
the accept in order to check the data quality and
4:43:58
데이터 마이그레이션을 수행하는 시나리오입니다
more specifically we can use it in order to check the data completeness
4:44:02
두 데이터베이스 간의 시나리오입니다
okay so we have the following scenario where we are doing data migrations
4:44:05
이 테이블을 데이터베이스 A에서 B로 이동하고
between two databases so let's say that we would like to move this table from database a to database b so we're gonna go and load the
4:44:12
새 데이터베이스에 테이블을 로드합니다
table to the new database and now what is very
4:44:15
데이터를 이동한 후 중요한 것은
important after you move the data is that to check whether all
4:44:19
모든 기록이 이동했는지 확인하는 것입니다
the records did move from database a to database b
4:44:22
하나의 기록도 누락되지 않도록
we are not missing anything even one record so we
4:44:25
데이터 완전성 테스트를 수행하고
want to do data completeness test and there are many methods on
4:44:28
이 테스트를 수행하는 방법 중 하나입니다
how to do this test one of them is to use that set
4:44:31
데이터베이스 A에 여전히 남아 있는 기록을 찾기 위해
operator except so how we're gonna do it we're gonna do an except between the table from database a and the table from database b in order to find any records that
4:44:40
마이그레이션되지 않은 기록입니다
is still in database a which is not migrated
4:44:44
결과는 비어 있어야 합니다
to the database p and of course the best result is that
4:44:47
결과가 비어 있어야 합니다
we will not get anything the result should be empty
4:44:50
비어 있다면 데이터베이스의 모든 행이 존재하지 않는다는 의미입니다
if we get an empty that means all the rows from database
4:44:53
아직 끝나지 않았습니다
a exists in the database b and now of course we
4:44:56
데이터베이스에서 새로운 행을 찾고 싶습니다
are not done yet we want to do the comparison but the way around
4:45:00
데이터베이스 a에서 찾지 못한 b
we want to find any new rows that is in database
4:45:03
두 테이블은 동일해야 합니다
b that we don't find in database a those two
4:45:07
첫 번째 테이블은 데이터베이스 b에서 가져올 것입니다
tables must be identical so now what we're gonna do we're
4:45:10
데이터베이스 a와 비교할 것입니다
gonna do an accept but the first table gonna be from the database b
4:45:13
결과가 비어 있어야 한다는 기대가 있습니다
and then we're gonna compare it with the database a and we have the same expectation the output should be as well empty and now after doing the accept twice for both
4:45:22
두 테이블이 동일하다는 것을 의미합니다
sides and we are getting empty in the results that
4:45:25
우리는 아무것도 놓치지 않았습니다
means those two tables are identical and we are not
4:45:28
데이터 마이그레이션의 품질을 향상시키기 위한 훌륭한 사용 사례입니다
missing anything so this is another amazing use case for the set operators in order to improve the quality of your data migrations and in order to do data completeness tests
4:45:42
세트 연산자에 대한 간단한 요약을 해보겠습니다
okay so now let's have a quick summary about the set operators so the
4:45:46
세트 연산자는 여러 쿼리의 행을 결합합니다
set operator is going to go and combine the rows of multiple queries multiple
4:45:49
네 가지 유형의 세트 연산자가 있습니다
tables into one single results and we have four
4:45:52
첫 번째는 유니온입니다
different types of the set operators the first one is the union
4:45:55
중복을 포함하지 않고 모든 규칙을 결합합니다
where it's gonna go and combine all the rules but without
4:45:58
두 번째는 유니온입니다
including any duplicates the second one we have the union
4:46:01
첫 번째 쿼리에서 찾을 수 없는 모든 규칙을 보여줍니다
all it's very similar and the third one we have the except it's
4:46:05
두 번째 쿼리에서 찾을 수 없는 규칙을 보여줍니다
gonna show all the rules from the first query that cannot be found
4:46:08
두 쿼리 간의 공통 규칙을 보여줍니다
in the second query and the fourth one we have the intersects where
4:46:11
세트 연산자를 사용하기 위한 SQL 규칙이 있습니다
it's gonna show the common rules between two queries and
4:46:15
쿼리는 동일한 수의 열을 가져야 합니다
of course we have sql rules in order to use the set operators both
4:46:18
동일한 데이터 유형과 열의 순서가 필요합니다
of the queries should have the same number of columns the same
4:46:21
첫 번째 쿼리가 별칭을 제어합니다
data types and the order of columns and the last
4:46:24
규칙을 잊지 마세요. 첫 번째 쿼리가 별칭을 제어합니다.
rule don't forget that the first query controls the aliases
4:46:28
열의 이름과 전체 데이터 유형입니다.
the name of the columns and the data types of the entire
4:46:31
결과와 우리는 집합 연산자에 대한 놀라운 사용 사례를 찾았습니다.
result and we have found amazing use cases for the set operators
4:46:34
예를 들어, 유니온과 유니온 올을 사용하는 것처럼
like for example using union and union all in order
4:46:38
유사한 정보를 하나의 큰 테이블로 결합합니다.
to combine similar informations into one big
4:46:41
테이블을 결합하거나 놀라운 제외 연산자를 사용할 수 있습니다.
table or we can go and use the amazing except operator
4:46:44
두 가지 다른 결과를 비교하기 위해
in order to compare two different results in order to
4:46:47
그들 사이의 차이를 찾기 위해 보통 사용합니다.
find the differences between them and i usually use it
4:46:50
데이터를 테스트하기 위한 데이터 품질 검사를 수행하기 위해
in order to do data quality checks to test the data
4:46:53
당신은 당신의 데이터 논리에서 제외를 구현할 수 있습니다.
completeness and another use case as a data engineer you
4:46:56
파이프라인에서 새로운 데이터를 식별하기 위해
can go and implement the except in your logic in your data
4:46:59
시스템에 삽입해야 하는 데이터입니다.
pipelines in order to identify what are the new
4:47:03
그로 인해 우리는 내부에 있는 모든 집합 연산자를 배웠습니다.
data that must be inserted in your system okay my friends
4:47:06
SQL에서 여러 데이터의 결합 방법을 배웠습니다.
so with that we have learned all the set operators that we have inside
4:47:09
SQL을 사용하여 여러 테이블을 결합하는 방법을 배웠습니다.
sql and with that you have learned how to combine your data from multiple
4:47:12
SQL을 사용한 테이블, 이제 이 장은 끝났습니다. 이제 오른쪽으로 가서 SQL의 함수에 대해 이야기하기 시작하겠습니다.
tables using sql so we are done with this chapter now we're going to go to the right side so now we're going to start talking about the functions in sql
4:47:20
레벨 또는 단일 값 함수입니다.
and here we have two peak families the first one is the raw
4:47:24
집계 분석 함수가 있습니다. 첫 번째부터 시작합시다.
level or the single value functions and the second one we
4:47:27
원시 레벨 함수와 여기에서 여러 개로 그룹화할 수 있습니다.
have the aggregate analytical functions so let's start with the first one
4:47:30
카테고리로 나누고 문자열 함수로 시작하겠습니다.
the raw level functions and here we can group them into multiple
4:47:33
먼저 함수가 정확히 무엇인지 이해합시다.
categories and we will start now with the string functions but
4:47:36
SQL에서 왜 필요한지 알아봅시다.
first let's understand what is exactly functions and why do
4:47:39
정확히 함수가 무엇인지, 왜 필요한지 알아봅시다.
we need them in sql so let's go okay
4:47:46
테이블 안에 데이터가 있습니다. 할 수 있는 일이 많습니다.
so what is exactly function and why we need it now again we
4:47:49
데이터로 할 수 있는 일이 많습니다.
have our data inside the table now there is like a lot of stuff
4:47:52
데이터로 할 수 있는 일이 많습니다.
that you can do with your data so sometimes you have to change the
4:47:55
데이터 값을 변경해야 할 때가 있습니다.
values of your data like doing data manipulation or you want
4:47:59
집계 및 분석을 하고 싶을 수 있습니다.
to do some aggregations and analyzes so maybe you want
4:48:02
데이터를 분석하고 인사이트를 찾고 싶을 수 있습니다.
to analyze your data and find insights and maybe build
4:48:05
보고서를 작성하고 싶을 수 있습니다.
reports and sometimes you might find bad data inside
4:48:08
데이터를 정리하고 싶을 수 있습니다.
your tables and you want to clean that up so you want to do data
4:48:11
데이터 변환과 조작을 해야 할 때가 있습니다.
cleansing and sometimes you have to do data transformations and data
4:48:15
SQL 작업을 해결하기 위해 데이터 조작을 합니다.
manipulation on our data in order to solve some SQL
4:48:18
함수에 대해 다시 말하자면, 함수란 무엇인가요?
tasks and in SQL in order to solve those tasks
4:48:21
내장된 코드 블록으로 입력 값을 받습니다.
we have functions so again what is exactly function
4:48:24
그런 다음 함수가 이 값을 처리합니다.
it is a built-in code block that accepts an
4:48:27
결과를 반환하고 출력 값을 제공합니다.
input value then the function gonna go and process this value
4:48:30
입력 값을 주고 변환을 수행합니다.
and it gonna return a result an output value so
4:48:34
출력을 제공하고 함수를 두 가지 큰 범주로 나눌 수 있습니다.
you give an input value do some transformations and
4:48:37
첫 번째는 단일 행 함수입니다.
give an output and we can group the functions into two big
4:48:40
함수에 단일 값만 제공합니다.
categories the first one we call it single row functions
4:48:43
그러면 하나의 값을 반환합니다.
so you give the function only one value and other
4:48:46
입력은 단일 값만 됩니다.
return you will get as well one value so the input for the function
4:48:49
함수의 출력도 단일 행 값이 됩니다.
gonna be only one single value like maria and
4:48:52
하나의 값이 입력되고 하나의 값이 출력됩니다.
the output of the function gonna be as well single row value so
4:48:56
다른 범주는 다중 행 함수입니다.
one value in one value out and now the other category of
4:48:59
예를 들어, sum 함수를 사용합니다.
functions we call it multi-row functions so
4:49:02
여러 값을 받아서 요약합니다.
for example if you have the function sum this function accept multiple
4:49:05
입력은 여러 행이고 출력은
rows multiple values like it gets 30 10 20 40 the function is then gonna go and summarize all those rows and return in the output only one value the summarization of all those values can be 100.
4:49:17
하나의 단일 값입니다.
so the input is multiple rows and the output
4:49:20
입력은 여러 행이고 출력은
is one single value so those are the two main categories
4:49:23
하나의 단일 값이므로 두 가지 주요 범주입니다
of functions in sql now
4:49:29
SQL의 함수입니다 이제
my friends you have to understand something about the functions that you can go
4:49:32
친구들, 여러분은 함수에 대해 이해해야 할 것이 있습니다.
and nest functions together so you can use multiple functions together in order to manipulate one value and this technique is not only in sql in any programming language so let's Let's have this example.
4:49:41
함수를 함께 중첩할 수 있습니다. 여러 함수를 함께 사용하여 하나의 값을 조작할 수 있습니다. 이 기술은 SQL뿐만 아니라 모든 프로그래밍 언어에서 사용됩니다. 예를 들어 보겠습니다.
We have the function left. It's gonna go and extract like few characters, let's say two characters.
4:49:46
왼쪽 함수가 있습니다. 몇 개의 문자를 추출할 것입니다. 예를 들어 두 문자를 추출합니다.
So the input for this function, let's say it's Maria. This value gonna enter the function. The function is gonna go and extract the first two characters.
4:49:53
이 함수의 입력은 마리아라고 가정해 보겠습니다. 이 값이 함수에 들어갑니다. 함수는 처음 두 문자를 추출합니다.
And in the output, we will get only two characters, ma. So this is one function. We have an input and output.
4:49:59
출력에서 우리는 두 문자만 얻을 것입니다. 'ma'입니다. 이것이 하나의 함수입니다. 우리는 입력과 출력을 가지고 있습니다.
Now you might say you know what we have multiple steps on this
4:50:02
이 함수의 입력은 마리아라고 가정해 보겠습니다. 이 값이 함수에 들어갑니다. 함수는 처음 두 문자를 추출합니다.
value so the first step we want to extract the first two
4:50:05
출력에서 우리는 두 문자만 얻을 것입니다. 'ma'입니다. 이것이 하나의 함수입니다. 우리는 입력과 출력을 가지고 있습니다.
characters using the left function but we have a second step
4:50:08
이제 여러분은 여러 단계가 있다고 말할 수 있습니다.
so we want to transform this output into a lower case
4:50:11
첫 번째 단계는 처음 두 문자를 추출하는 것입니다.
characters so we have another function lower and the input for
4:50:15
왼쪽 함수를 사용하지만 두 번째 단계가 있습니다.
this second function will be the output of the first
4:50:18
이 출력을 소문자로 변환하고 싶습니다.
function so ma it is at the same time output and input
4:50:21
소문자로 변환하고 싶습니다.
for another function so the lower function gonna take this value
4:50:24
그래서 우리는 또 다른 함수인 lower가 있습니다.
and convert it into lower case character so it's like
4:50:27
이 두 번째 함수의 입력은 첫 번째 함수의 출력이 될 것입니다.
inside the factory the materials can be processed into multiple
4:50:30
ma는 동시에 출력이자 입력입니다.
stations and the output of one station can be the input for
4:50:34
또 다른 함수의 입력이 될 것입니다.
the next station and this is exactly what we can do with the functions
4:50:37
lower 함수가 이 값을 가져와서
so now how we're going to build that the first step is to start with the first
4:50:40
소문자 문자로 변환합니다. 공장 내부에서
function so this is simple one function now for the next
4:50:43
재료는 여러 작업으로 처리될 수 있습니다.
step what you're going to do on the left side you can write lower
4:50:46
하나의 작업의 출력은 다음 작업의 입력이 될 수 있습니다.
and put the whole thing in parentheses so now the whole
4:50:49
이것이 바로 우리가 함수로 할 수 있는 일입니다.
thing the first function gonna be inside another function
4:50:53
이제 어떻게 구축할 것인지 첫 번째 단계는 첫 번째로 시작하는 것입니다.
and with that you have nested one function in another and of
4:50:56
물론, 예를 들어 길이를 필요로 하는 세 번째 함수를 원하신다면
course if you need a third function like for example the length
4:50:59
전체 내용을 다시 두 개의 괄호 사이에 넣을 것입니다.
what you're gonna do you're gonna put the whole thing again between two parentheses
4:51:02
이제 왼쪽의 출력이 아래로 가게 됩니다.
so now that means the output of the left gonna go to the lower
4:51:05
아래의 출력이 길이로 가게 되므로
and the output of the lower gonna go to the length so
4:51:08
매우 간단하며, 이 실행의 순서는 항상 내부 함수에서 시작됩니다. 왼쪽 함수가 먼저 실행되고, 그 다음 외부 함수인 아래 함수가 실행됩니다. 마지막으로 실행되는 함수는 길이입니다.
it is very simple and the order of the execution for this will start always in the inner function so the left function can be executed first and then the outside function the lower and And the last function that's going to be executed is the length.
4:51:20
이것이 SQL 또는 다른 프로그래밍 언어에서 중첩 함수가 작동하는 방식입니다.
This is how the nested functions works in SQL or in any programming language.
4:51:28
이제 SQL에서 친구들, 우리는 많은 함수가 있습니다. 그래서 우리는 그것들을 하위 카테고리로 그룹화해야 합니다.
Now my friends in SQL, we have a lot of functions. That's why we have to group them as well into subcategories.
4:51:34
단일 행 함수에 대해 이야기하고 있다면, 문자열 값과 숫자, 날짜 및 시간, 그리고 널을 처리하기 위한 함수가 있습니다.
Like if you are talking about the single row functions, we have functions for the string values and as well for the numeric, the date and time, and as well functions in order to handle the nulls.
4:51:44
여기에서 다중 행 함수에 대해 이야기하고 있다면, 기본적으로 두 그룹이 있습니다. 첫 번째는 간단한 집계 함수입니다.
And if you are talking about the multi row functions here, we have basically two groups. The first one is the simple aggregate functions.
4:51:50
이것들은 데이터를 집계하기 위한 기본입니다. 그리고 우리는 또 다른 고급 함수가 있습니다.
Those are the basics in order to aggregate your data. And we have another advanced one.
4:51:55
우리는 이를 윈도우 함수라고 부르거나 때때로 분석 함수라고 부릅니다. 이제 이 두 그룹을 살펴보겠습니다.
We call it the window functions or sometimes we call it analytical functions. So now I'm looking to those two groups.
4:52:00
이제 친구들, 이 함수들을 이해하는 것이 매우 중요합니다. 왜냐하면 이를 사용하면 데이터로 원하는 모든 것을 할 수 있기 때문입니다.
And now my friends, it is very important to understand those functions because using them, you can do whatever you want with your data.
4:52:07
이 두 그룹을 살펴보면, 단일 행 함수는 여기서 데이터를 조작하고 두 번째 그룹을 준비하는 함수입니다.
And if I'm looking to those two groups, the single row functions, those stuff here, they They are functions in order to manipulate and prepare the data for the second group.
4:52:16
데이터 엔지니어와 데이터 분석가를 생각한다면, 데이터 엔지니어는 단일 행 함수를 사용하여 SQL에서 데이터를 준비할 것입니다.
So if you are thinking about data engineers and data analysts, the data engineer is going to go and prepare the data in SQL using the single row functions.
4:52:23
따라서 데이터를 정리하고 변환하며 조작하기 위해 이를 사용할 것입니다. 분석가를 위해 준비하기 위해서요.
So you're going to use them in order to clean up, transform, manipulate your data in order to prepare it for the analyzers.
4:52:31
데이터 분석가라면 거의 모든 작업에서 집계 함수를 주로 사용할 것입니다. 그래서 저는 이렇게 봅니다.
And if you are data analyst, you will be mostly using the aggregate functions in almost every task. So I really see it like this.
4:52:37
데이터 엔지니어를 위한 단일 행 함수와 데이터 분석가를 위한 다중 행 함수입니다.
the single row functions for data engineers and multi-row functions for data analysts.
4:52:42
이 과정에서 우리가 할 일은 각 하위 그룹을 하나씩 방문하여 함수들을 탐색하고, 어떻게 작동하는지, 언제 사용할 것인지 이해하는 것입니다.
And my friends, what we're going to do in this course, we're going to visit each of those subgroups one by one, exploring the functions, understanding how they work and when we're going to use them.
4:52:51
그래서 첫 번째 그룹, 문자열 함수부터 시작하겠습니다. 여기서 문자열 값을 조작하는 방법을 배울 것입니다. 자, 시작합시다.
So let's start with the first group, the string functions. And here we're going to learn how to manipulate the string values. So let's go.
4:53:03
좋습니다, 이제 많은 문자열 함수가 있으므로, 목적에 따라 카테고리로 나누겠습니다.
Okay, so now since we have a lot of string functions, I'm going to go and divide them into categories. based on the purpose.
4:53:08
예를 들어, 문자열 값을 조작하는 함수 그룹이 있습니다.
So for example, we have a group of functions that's going to go and manipulate the string values.
4:53:13
그래서 우리는 연결, 대문자, 소문자, 교체 등이 있습니다.
So we have concatenation, upper, lower, replace and so on.
4:53:16
그리고 또 다른 그룹은 문자열 값에서 계산을 수행할 수 있는 단 하나의 함수가 있습니다.
And another group where we have only one function, it is where we can do calculations on the string values.
4:53:21
마지막 그룹은 문자열 값에서 무언가를 추출하는 방법에 관한 것입니다. 여기에는 left, right, substring의 세 가지 함수가 있습니다.
And the last group, it is all about how to extract something from a string value. And here we have three functions, left, right, substring.
4:53:28
이제 데이터 조작에 관한 첫 번째 그룹을 시작하겠습니다. 여기서 첫 번째 함수는 concat입니다.
So now let's go and start with the first group about the data manipulation. first function we have here concat.
4:53:33
자, concat 또는 연결이란 정확히 무엇인가요?
Alright, so what is exactly concat or concatenation?
4:53:40
여러 문자열 값을 하나의 값으로 결합합니다.
It's going to go and combine multiple string values into one value.
4:53:45
여러 가지가 있다면 모든 것을 하나의 값으로 넣을 수 있습니다. 아주 간단한 예를 들어보겠습니다. 이제 Michael이라는 값이 있다고 가정해 보겠습니다.
So if you have multiple things, you can put everything in one value. So let's have a very simple example. Okay, so now let's say that you have one value called Michael.
4:53:52
여기에는 이름이 있고 성을 위한 완전히 분리된 값이 있습니다. 다른 열에는 Scott과 같은 값이 있습니다.
So here you have the first name and you have totally separated value for the last name, another column where you have a value like Scott.
4:53:59
이제 당신은 이름과 성이 분리되어 있는 것이 의미가 없다고 말하고 있습니다. 이 두 값을 하나로 결합하고 싶습니다.
And now you're saying, you know what, it makes no sense to have the first name separated from the last name. I would like to go and combine them in one value.
4:54:06
따라서 concat을 사용하여 이 두 값 또는 여러 값을 하나의 값으로 결합할 수 있습니다. 예를 들어 Michael Scott과 같이요.
So you can go and use the concat in order to combine those two values or multiple values into one single value like Michael Scott.
4:54:14
이제 거의 모든 것을 정리한 것 같습니다. 두 개의 열 대신 하나의 값으로 전체 이름을 보는 것이 더 좋습니다.
I think that pretty much sums it up. So it is nicer to see the full name in one value instead of having like two columns for that.
4:54:22
이제 그게 전부입니다. 이것이 우리가 연결이 필요한 이유입니다. 이제 SQL로 돌아가서 그것을 시도해 보겠습니다.
So that's it. This is why we need the concatenations. Now let's go back to SQL in order to try that out.
4:54:27
이제 다음 작업이 있습니다. 먼저 고객 목록을 보여주세요.
okay so now we have the following task show a list of customers first
4:54:31
국가와 함께 이름을 한 열에 표시해야 합니다.
names together with their country in one column so
4:54:34
즉, 고객 목록을 만들어야 하고 두 개의 열을 하나로 결합해야 합니다.
that means we have to make a list of customers and we have to combine two
4:54:37
이름과 국가를 필요로 합니다.
columns in one so let's start writing the query select we
4:54:40
고객 테이블에서 가져옵니다. 먼저 이것을 실행해 보겠습니다.
need the first name the country from
4:54:44
고객 목록이 있지만 문제는 이름과 국가가 서로 다른 열에 있다는 것입니다. 작업에서는 하나의 열에 있어야 한다고 합니다.
the table customers so first let's go and execute this now
4:54:47
이제 이 두 가지를 결합하기 위해 연결 함수를 사용해야 합니다. concat입니다.
as you can see we have a list of customers but the issue here the first name and the countries those two informations are in different columns but the task says they should be in one column.
4:54:56
첫 번째 인수로 이름을 시작하고 그 다음에 국가를 이렇게 추가하고 이름을 지정하겠습니다.
So now in order to combine those two things we have to use the concatenate function. So concat.
4:55:01
이름 국가라고 부르겠습니다. 이제 실행해 보겠습니다. 출력에서 새로운 열을 볼 수 있습니다.
So I'm going to start with the first argument it's going to be the first name and then the country like this and we're going to give it a name.
4:55:08
이것은 이름 국가라고 불리며 두 정보를 하나의 열에 가지고 있습니다.
Let's call it like this name country. Now let's go and execute it. Now in the output you can see we have a new column.
4:55:14
우리는 Maria Germany와 join USA가 있지만, 그 사이에 간격이 없어서 보기 좋지 않습니다.
It's called name country and we have both of the informations in one column.
4:55:18
이제 그들 사이에 약간의 구분을 만들 수 있습니다.
So we have Maria Germany join USA but it doesn't really look good because there is like no spacing between
4:55:24
사이에 하나 더 추가하여요.
them now we can go and make some separation between them
4:55:28
예를 들어 공백을 추가하면 이제 우리는
by just adding one more thing in between like
4:55:31
이름과 공백을 함께 연결하고 있습니다.
for example maybe space so now we are concatenating the
4:55:34
그리고 나서 국가를 추가하겠습니다. 이제 실행해 보겠습니다.
first name together with a space this over here
4:55:37
보시다시피 이름과 국가 사이에 좋은 구분이 있습니다.
and then the country so let's go and execute it now as you
4:55:40
첫 이름과 국가 사이에 깔끔한 구분이 있습니다.
can see we have nice separations between the first name and the country
4:55:44
물론, 하이픈이나 언더스코어와 같은 다른 구분 기호를 추가할 수 있으며 같은 효과를 얻을 수 있습니다.
and of course you can go and add different separations like maybe minus or underscore and you will get the same effects
4:55:50
그렇게 하면 고객 목록이 생깁니다.
so with that we have a list of customers where we have
4:55:53
첫 이름과 국가가 한 열에 함께 있습니다.
the first name together with the country in one column as you can see
4:55:56
매우 간단합니다. 두 열을 결합하는 방법입니다.
it's very simple this is how you combine two columns in
4:55:59
정말 간단하고 쉬운 변환입니다. SQL의 연결에 대한 모든 것입니다.
one it is really nice and easy transformation okay so that's all about
4:56:02
SQL의 연결에 대해 이야기할 것입니다. 다음은 두 가지 함수입니다.
the concatenation in sql next we're going to talk about two functions
4:56:05
대문자와 소문자 함수입니다.
the upper and the lower okay
4:56:11
대문자 함수는 문자열의 모든 문자를 대문자로 변환합니다.
so what is upper function it's going to go and convert all the characters of a string to an uppercase it's going to make everything
4:56:18
모두 대문자로 변환되고 소문자 함수는 정반대입니다.
capitalized and the lower function is exactly the opposite it's
4:56:21
모두 소문자로 변환됩니다. 이제 두 함수에 대한 간단한 예를 들어보겠습니다.
gonna go and convert everything to a lowercase so let's
4:56:25
세 가지 값이 있으며 각기 다른 대소문자를 가지고 있습니다.
have very simple example for those two functions okay so now we have like
4:56:28
첫 번째 값은 첫 글자만 대문자이고 나머지는 소문자입니다.
three values with different cases the first one where you have only
4:56:31
그 다음은 같은 값이지만 모두 소문자이고, 세 번째는 모두 대문자입니다.
the first character capitalized and the rest is lowercase and
4:56:34
첫 번째 값은 대문자로 변환됩니다.
then the same value but everything is lowercase and a third one where you have everything with an uppercase now if you go and apply the function upper to those three values
4:56:43
모든 것이 대문자로 변환됩니다. 첫 글자만 대문자가 아닙니다.
what can happen for the first value is going to go and turn it
4:56:46
두 번째 값은 완전히 대문자로 변환됩니다.
into an uppercase so everything going to be capitalized not
4:56:49
모든 문자가 변경됩니다. 마지막 값은 이미 대문자입니다.
only the first character and now for the second value is going to
4:56:52
마지막 값은 이미 대문자입니다.
turn it as well to completely capitalized so all the characters
4:56:55
출력에서 같은 값을 얻습니다.
gonna change and for the last value it is already capitalized
4:56:59
사실 아무 일도 일어나지 않습니다.
so in the output you will get the same value so actually nothing gonna
4:57:02
대문자에 대한 간단한 설명입니다. 이제 소문자를 사용하면 첫 번째 문자만 변경됩니다.
happen for that so this is simply the uppercase now let's see what can happen if you use the lowercase for the first value only the first character is gonna be changed and then
4:57:10
모든 것이 소문자로 변환됩니다. 두 번째 값은 이미 소문자입니다.
will have everything in lowercase the second value it is already
4:57:14
소문자를 적용하면 아무 일도 일어나지 않습니다.
a lowercase value so if you apply lowercase nothing can
4:57:17
마지막 값은 모두 대문자입니다.
happen you will get the same value but for the last one everything here is
4:57:20
대문자로 되어 있고 소문자를 적용하면 모든 문자가
capitalized and if you apply lowercase all the characters gonna
4:57:23
소문자로 변환됩니다. 그래서 친구들, 이것은 매우
convert to a lowercase so my friends this is very
4:57:26
간단합니다. 이제 연습하기 위해 스케일로 돌아가겠습니다.
simple let's go back to scale in order to practice that okay
4:57:29
그래서 우리는 다음 작업이 있으며 고객의
so we have the following task and it says transform the customer's
4:57:33
이름을 소문자로 변환하라고 합니다. 이제 보시다시피 첫
first name to lowercase so now as you can see the the first
4:57:36
문자는 대문자이고 나머지는
names here the first character is a capital the rest is
4:57:39
소문자입니다. 그래서 이제 이 작업에서는 전체를
lowercase so now in this task we have to convert the whole
4:57:42
소문자로 변환해야 합니다. 그러니 가서 해봅시다.
thing into lowercase so let's go and do that it's
4:57:46
매우 간단합니다. 우리는 첫 번째 이름을 소문자로
very simple we're gonna say lower first name
4:57:49
변환하겠습니다. 그리고 이를 low name이라고 부르겠습니다.
and let's go and call it low name so that's
4:57:52
그게 다입니다. 이제 실행해봅시다. 소문자 이름을 비교해보면
it let's go and execute it if we go and compare the lower name
4:57:55
첫 번째 이름과 비교할 수 있습니다. 모든 문자가 이제 소문자로 되어 있습니다. 그래서 이 작업은
with the first name you can see all the characters now in the lowercase so that's it for the task we have transformed the first name to lowercase all
4:58:04
고객의 첫 번째 이름을 대문자로 변환하는 것입니다. 자, 가서
the next task is exactly the opposite transform the customer's
4:58:07
새로운 열을 만들겠습니다. upper라고 하겠습니다.
first name to uppercase so let's go and
4:58:10
그런 다음 첫 번째 이름을 up으로
have a new column we're gonna say upper then
4:58:13
첫 번째 이름을 대문자로
the first name as up
4:58:16
이름이므로 간단합니다. 이제 시작합시다.
name so that's it it's very simple let's go and
4:58:20
실행하면 출력에서 'up'이라는 새 열이 생겼습니다.
execute now you can see in the output we have a new column called up
4:58:23
이 열 안에는 첫 번째 이름이 있지만 이제 모든
name and inside it we have the first name but now all
4:58:26
문자가 대문자로 되어 있습니다. 이것이 SQL에서 대소문자를 변환하는 방법입니다. 이제 대문자와 소문자에 대해 다 설명했습니다. 다음은 매우 흥미로운 함수인 trim에 대해 이야기하겠습니다.
the characters in uppercase so this is how you convert the case to lower or to upper in sql okay so that's all about the upper and the lower next we're going to talk about very interesting function it is the trim
4:58:42
trim 함수는 문자열 값에서 앞뒤 공백을 제거합니다.
so the trim function gonna go i remove the leading
4:58:45
따라서 문자열 값의 시작과
and trailing spaces in your string values so
4:58:48
끝에 있는 빈 공백을 제거합니다. 간단한 예를 들어보겠습니다.
it's gonna go and get rid of the empty spaces at the start and
4:58:51
이제 다양한 시나리오를 살펴보겠습니다. 첫 번째는 값이 있을 수 있습니다.
at the end of a string value let's have a very simple example okay
4:58:55
이런 식으로.
so now we're gonna have different scenarios the first one you can have like a value
4:58:58
공백이 없는 조인, 이것이 일반적인 경우입니다.
join where you don't have any spaces and this is the normal case
4:59:01
하지만 때때로 시작 부분에 이렇게 공백이 있을 수 있습니다.
but sometimes you might have it like this where at the start you have
4:59:04
선행 공백, 빈 공백 또는 때때로
a leading space you have an empty space or sometimes
4:59:07
우리는 이를 공백이라고 부릅니다. 다른 경우에는 공백이
we call it white space in another scenario the space might
4:59:10
세상의 끝에 있을 수 있습니다. 그래서 우리는 이를 후행 공백이라고 부릅니다.
be at the end of the world so here we call it trailing space
4:59:13
세상의 끝에 있을 수 있습니다. 그래서 우리는 이를 후행 공백이라고 부릅니다.
and in another scenario you might have both of them this is
4:59:16
이 두 가지 모두 있을 수 있습니다. 이것은
really bad where at the start you have the leading space and
4:59:19
정말 나쁩니다. 시작 부분에 선행 공백이 있고
at the end you have the trailing space and of course you might not have only
4:59:23
끝에 후행 공백이 있을 수 있으며, 물론 하나의 공백만 있을 수도 있습니다.
one space you might have multiple spaces depend on how long
4:59:26
여러 개의 공백이 있을 수 있습니다. 사용자가 공백을 얼마나 눌렀는지에 따라 다릅니다.
did the user press the space right so of course my friends
4:59:29
그래서 물론 친구들, 공백은 정말 악성입니다. 이렇게 되는 것은 말이 안 됩니다.
spaces are really evil and this makes no sense to have it
4:59:32
당신의 데이터에 공백이 있는 것은 말이 안 됩니다. 이제 해야 할 일은 데이터 정리입니다.
in your data now what you have to do is to do data cleansing we have
4:59:35
이 혼란을 정리해야 하며, 이를 위해 최고의 기능이 있습니다.
to clean up this mess and you have the best function in order to
4:59:38
데이터를 정리하기 위해, 트림 기능이 있습니다. 트림을 적용하면
clean up the data you have the trim so if you apply trim
4:59:41
구절 값에 대해 아무 일도 일어나지 않습니다. 모든 것이 깨끗하기 때문입니다.
for the verse value nothing gonna happen because everything is clean
4:59:45
이제 두 번째 경우에 대해 적용하면 선행 공백이 있을 때, 이 공백을 제거하게 됩니다. 후행 공백도 마찬가지입니다.
and we don't have any spaces now if you apply it for the second case
4:59:48
끝에 공백이 있으면 트림 기능이 이를 찾아서 정리해 줄 것입니다.
where you have a leading space if you do that it's gonna go i remove this space the same thing for the training space so if you If you have space at the end, the trim function is going to find it and clean that up.
5:00:00
시작과 끝에 공백이 있으면 문제 없습니다. 그것을 정리해 줄 것입니다.
start and at the end, then it's as well, no problem. It's going to go and clean that up.
5:00:04
그리고 트림 기능은 여러 개의 공백도 정리할 수 있습니다.
And as well, the trim function can go and clean multiple spaces.
5:00:07
예를 들어, 끝이나 시작에 5개, 10개의 공백이 있다면, 트림 기능이 이를 정리해 줄 것입니다. 이것이 트림 기능입니다.
So if you have like five spaces, 10 spaces at the end or at the start, the trim function is going to go and clean that up. So this is how the trim works.
5:00:15
이제 여러분의 기술로 돌아가서 공백이 있는지 확인해야 합니다. 자, 이제 매우 까다롭고 흥미로운 작업이 있습니다.
And now let's go back to your skill in order to find out whether we have any spaces. Okay, so now we have a very tricky and interesting task.
5:00:21
고객의 이름에 선행 또는 후행 공백이 포함된 고객을 찾으라고 합니다.
It says find the customers whose first name contains leading or trailing spaces.
5:00:28
이 값들을 살펴보면 고객의 이름 안에 공백이 있는지 찾아야 합니다.
So now by looking to those values, we have to find any spaces inside the customer's name.
5:00:33
이 결과를 보면 공백을 찾을 수 없습니다. 특히 후행 공백은 보기 어렵습니다.
Now by just looking to this result, you will not find any white spaces because it's really hard to see, especially if it is like trailing spaces.
5:00:41
이제 이름에서 공백을 감지하기 위한 쿼리를 작성해야 합니다. 어떻게 할 수 있을까요?
Now we have to write query order to detect any spaces in the names. So how we can do that?
5:00:48
좋아요, 이제 조금 생각해보고 힌트를 줄 수 있어요.
Okay, so now think about it a little bit and I can give you a hint.
5:00:50
공백을 제거하기 위해 trim 함수를 사용할 수 있고, 이를 where 절 안에서 사용해야 해요.
You can use the function trim in order to remove any white spaces and you have to use it inside where clause.
5:00:57
우리가 할 일은 where를 말하는 거예요. 이제 공백을 감지하기 위한 조건을 만들어야 해요.
So what we're going to do, we're going to say where. So now we have to build a condition to detect any spaces.
5:01:03
첫 번째 이름이 trim을 적용한 후 자신과 같지 않다면 그렇게 말하는 거예요.
So if you are saying if the first name is not equal to itself first name after applying a trim.
5:01:10
첫 번째 이름을 잘라낸 후, 그것이 첫 번째 이름과 같지 않다면, 그러면 공백이 있었다는 뜻이에요.
So after trimming the first name, if it is not equal to the first name, so that means there was spaces.
5:01:19
그렇다면 여기서 무슨 일이 일어나고 있는 걸까요? 마리아를 살펴보죠. 마리아에 null이 없다면, 이 값을 잘라내도 아무 일도 일어나지 않아요.
So again, what is going on here? Let's go for Maria. If Maria has no nulls, if you trim this value, nothing can happen.
5:01:25
값은 이전과 정확히 같을 거예요. 왜냐하면
the value gonna stay exactly like before because there is
5:01:28
공백이 없지만 마리아에
no white spaces but if in maria there is any
5:01:31
공백이 있다면 값을 잘라내도
space inside it trimming the value will not be
5:01:34
첫 번째 이름과 같지 않을 거예요. 만약 공백이 포함되어 있다면
equal to the first name if it contains any spaces so
5:01:38
열이 잘라낸 후 같은 열과 같지 않다면, 그러면 공백이 있다는 뜻이에요.
if the column is not equal to the same column after
5:01:41
잘라낸 후 공백이 있다는 뜻이에요. 그러니 실행해 보죠. 이제 출력에서 한 고객을 볼 수 있어요.
trimming it that means there is spaces so let's
5:01:45
존이 이 상황에 있는 곳에서, 믿지 않으신다면
go and execute it and now we can see in the output we have one customer
5:01:48
저를 따르지 않으신다면, 여기서 더 쉬운 방법을 찾을 수 있어요.
john where we have this situation now if you don't believe
5:01:51
확인해 보죠. 이 부분을 주석 처리하고 살펴보죠.
me or you don't follow me here we can have another easier
5:01:54
우리의 첫 번째 이름을 확인해 보죠. 이제 계산할 수 있어요.
check so let's go and comment this out and let's have a look
5:01:57
첫 번째 이름의 길이를 이제 계산할 수 있어요. 이전에 했던 것처럼요.
to our first names now we can go and calculate the
5:02:01
이제 길이를 계산해 보죠. 이제 실행해 보죠.
length or the first name like we have done before so
5:02:05
여기 마리아를 보면 다섯 글자가 있어요. 하지만 존은
length name and let's go and execute it now
5:02:08
여기 마리아를 보면 우리는 다섯 개의 문자가 있지만 존이 있습니다.
if you can see here maria we have five characters but john
5:02:11
여기 네 개의 문자가 있지만 길이는 다섯입니다. 그 이유는 어딘가에 공백이 있기 때문이며, 공백도 문자의 하나로 계산될 수 있습니다. 그래서 여기 뭔가 잘못된 것이 있습니다, 맞죠? 그리고 다른 것들도 확인할 수 있습니다.
we have here four characters but the length is five that's because we have somewhere space and the space can account as a character so here there is like something wrong right and you can check the others as well
5:02:23
모든 것이 일치하지만 오직 존만 문제가 있습니다. 이제 이것을 더 명확하게 보기 위해 우리는 두 가지 함수를 사용할 것입니다: trim과 length. 먼저 첫 번째 이름을 잘라봅시다.
everything is matching but only john we have here an issue and now in order to see this more clearly we're gonna use two functions the trim and the length so first let's go and trim the first name
5:02:35
값을 잘라낸 후에 길이를 계산할 것입니다.
and after trimming the values i'm gonna calculate the length
5:02:38
그래서 우리는 trim과 함께 중첩하고 있습니다.
so we are nesting together the trim and the
5:02:41
length를 호출할 것이고, 이를 length trim name이라고 부를 것입니다.
length and i'm gonna call it length trim name
5:02:44
이제 실행해 봅시다
so let's go and execute it now
5:02:47
값을 다듬기 전의 길이를 볼 수 있습니다
we can see the length before trimming any value and
5:02:51
값을 다듬은 후의 길이를 볼 수 있습니다
we can see the length after trimming the values so
5:02:54
존의 다듬기 전 길이는 다섯입니다
you can see over here that john before trimming is five
5:02:57
다듬기 후 길이는 네입니다
and after trimming is four so we have here an issue
5:03:01
이제 더 명확하게 만들 수 있습니다
now we can make things more clear where we can go and
5:03:04
첫 번째 이름의 길이를 빼겠습니다
subtract the length of the first name with
5:03:07
첫 번째 이름의 길이를 다듬기 전에
the length of the first name but first we trim the values
5:03:10
여기서 플래그라고 부를 수 있습니다
so here we can call it maybe a flag or something so let's
5:03:14
플래그를 보고 실행해 봅시다
go and execute it now by looking to the flag it is really
5:03:17
제로가 있으면 모든 것이
easy to now to see if we have a zero then everything is
5:03:20
공백이 없지만 더 높은 값이 있으면
fine we don't have any white spaces but if we have higher than
5:03:23
여기서 제로와 같은 값이 있으면
zero like here one then this is an indicator that
5:03:26
공백이 있다는 것을 나타냅니다
we have a white space either you do it like this where
5:03:29
첫 번째 이름이 다듬기 전과 다르거나
the first name is not equal the first name after trimming or
5:03:33
더 복잡한 해결책을 사용할 수 있습니다
you use more complicated solution where you say where
5:03:36
여기서 길이를 제거하겠습니다
and i'm gonna remove this from here the length of
5:03:39
첫 번째 이름이 다듬기 후와 같지 않습니다
the first name is not equal to the length after
5:03:42
실행하면 다시 존이 나옵니다
trimming so not equal so if you go and execute
5:03:45
데이터 내의 빈 공간을 감지합니다
it you will get exactly again john so this is how we detect
5:03:49
트림 기능을 사용하여
any empty spaces inside our data using the trim
5:03:52
첫 번째 해결책을 선호합니다
function or maybe as well using the length but i really
5:03:55
빈 공간을 제거하는 방법에 대한 모든 것입니다
prefer the first solution it is way easier using one function
5:03:58
트림을 사용하여
all right so that's all about how to remove the empty spaces using
5:04:02
중요한 함수인 replace에 대해 이야기하겠습니다
the trim next we're going to talk about a very important function called
5:04:05
지금 교체
replace now
5:04:10
교체 함수는 특정 문자를 교체합니다
the replace function gonna go and replace a specific character
5:04:13
즉, 우리는 오래된 것이 있고 그것을 새로운 것으로 교체하고 싶습니다
so that means we have something old and we want to replace it with something
5:04:16
새로운 것을 이해하기 위해 매우 간단한 예를 들어보겠습니다
new let's have a very simple example to understand it all right so now
5:04:19
전화번호가 대시로 구분되어 있다고 상상해 보세요
imagine we have a phone number where the data is splitted by a
5:04:22
이제 데이터에 대시가 있는 것이 마음에 들지 않습니다
dash now let's say that i don't like to have the dash in my data
5:04:25
슬래시와 같은 다른 특수 문자를 사용하고 싶습니다
i would like to have slash like any other special character now
5:04:28
대시를 교체하기 위해 교체 함수를 사용할 수 있습니다
in order to replace the dash we can use the function replace
5:04:32
SQL에 대해 두 가지를 지정해야 합니다
so we have to specify for sql two things the
5:04:35
오래된 값인 대시와 새로운 값인 슬래시를 지정해야 합니다
old value the dash with a new value the slash so if you do that in the output it's going to go and remove all All those dashes between the numbers and the replacement can be the dash between them.
5:04:46
그래서 매우 간단합니다, 맞죠? 우리는 오래된 값을 새로운 값으로 교체하고 있습니다
So it's very simple, right? All that you are doing is replacing an old value with a new value. And that's why we call it replace.
5:04:52
하지만 우리는 무엇인가를 제거하기 위해 이 함수를 사용할 수도 있습니다
But we can use this function as well in order to remove something. Not only we replace.
5:04:57
새로운 값에 아무것도 지정하지 않으면 됩니다
And you can do that by not specifying anything in the new value
5:05:01
단순히 작은 따옴표만 사용하면 됩니다
like just the single quotes and with that it's gonna be nothing
5:05:04
빈 공간이 될 것입니다
a blank so now what's gonna happen is clearly gonna go and
5:05:07
대시를 빈 공간으로 교체하는 것입니다
replace the dash with a blank and that means i'm
5:05:10
출력에서 대시를 제거하게 됩니다
just removing the dashes from the output so if you do it
5:05:13
대시를 제거하면 숫자만 남게 됩니다
you will remove the dash and you will get only numbers so if
5:05:16
교체가 빈 공간이 된다면 이 함수는
the replacement gonna be a blank then that means this function
5:05:20
지정한 모든 값을 교체하게 됩니다
will be replacing any value that you specify so
5:05:23
이것이 바로 작동하는 방식입니다
this is exactly how it works and this is why we use the
5:05:26
SQL에서 교체 함수를 사용하는 이유입니다
replace function in sql now let's go back in order to practice so
5:05:29
같은 예를 들어 보겠습니다
let's do the same example this time we're gonna go and select from a
5:05:32
정적 값을 선택할 것입니다
static value so we're gonna get one two three four five six
5:05:35
일곱 여덟 아홉 제로입니다
seven eight nine zero so if you go and execute
5:05:38
이제 전화번호를 얻고 있으니 이 값에서 대시를 제거합시다.
it you can see we are getting the phone number now let's go and remove
5:05:42
이 값에서 대시를 제거합시다. 새 줄을 만들어 봅시다.
the dashes from this value so let's have a new line and we
5:05:45
첫 번째로 지정해야 할 것은 SQL의 값 자체입니다.
start with replace the first thing that you have to specify for
5:05:48
값 자체입니다. 이제 값을 가져옵시다.
sql the value itself so let's go and get the value
5:05:51
첫 번째 인자는 이것입니다. 두 번째 인자는
this is the first argument the second argument gonna be the
5:05:54
이전 값입니다. 이전 값은 대시가 될 것이고,
old value so the old value gonna be the dash and now the
5:05:58
세 번째 인자는 대체 값이 될 것입니다. 우리는
third argument will be the replacements and since
5:06:01
그것을 제거하고 싶으니 아무것으로 대체하고 싶지 않습니다.
we want to remove it we don't want to replace it with anything we
5:06:04
따라서 단일 따옴표만 있고 그 사이에 아무것도 없습니다. 이제 이렇게 이름을 바꿉시다. 이것이 전화입니다.
will have just single quotes and nothing between them so there is no space between those single quotes now we can go and rename stuff like this is the phone and this is
5:06:13
깨끗한 전화입니다. 이제 실행해 봅시다.
a clean phone let's go and execute
5:06:16
이제 함수의 출력에서 대시가 없음을 알 수 있습니다.
it now as you can see in the output of the function we don't have
5:06:20
숫자 사이에 대시가 없고 테스트할 수 있습니다.
any dashes between the numbers and you can go and test
5:06:23
예를 들어 슬래시를 추가할 수 있습니다.
stuff like for example i can go and add a slash
5:06:26
그리고 실행하면 그 사이에 슬래시가 보일 것입니다.
and execute it you will see slashes between them so
5:06:29
여러 가지를 시도해 볼 수 있습니다. 이것은 좋은 사용 사례입니다.
you can go and try multiple stuff so this is one nice use case
5:06:32
대체 함수에 대한 또 다른 사용 사례가 있습니다.
for the replace function now there is another use case for the replace
5:06:35
데이터 파일에서 이름이 저장될 수 있습니다.
function is that sometimes in my data file
5:06:38
예를 들어 reports.txt라고 가정해 보겠습니다. 파일 형식을 .txt에서
names can be stored like for example let's say reports dot txt and now let's say that i would like to change the file formats from dot txt to
5:06:47
csv로 변경하고 싶습니다. 어떻게 할까요?
csv now how we're going to do that we're going to go with a new
5:06:50
새 줄을 추가하고 첫 번째 인자는
line say replace and then the first argument going to be
5:06:53
값이 될 것입니다. 여기서 값을 가져오고 이전 값은 .txt가 될 것입니다.
the value so let's take our value from here and now what is the old value it's going to be the dot txt and i want to replace it with another format with another extension so it So it can be the CSV.
5:07:04
새 파일 이름과 이전 파일 이름을 지정하겠습니다.
So we're going to say this is the new file name and this is the old file name.
5:07:11
이제 실행해 봅시다. 출력에서 SQL이 TXT를 CSV로 대체했습니다.
So let's go and execute it. And now as you can see in the output SQL did replace the TXT with CSV.
5:07:18
이것은 제가 프로젝트에서 대체 함수를 사용하는 곳입니다.
This is as well where I use the replace function in my projects. So my friends, the replace function is really fun.
5:07:23
대체에 대한 두 가지 좋은 사용 사례입니다.
And those are two nice use cases for the replace. All right. So that's all about the replace function in SQL.
5:07:29
이제 우리는 전체 데이터 조작을 다뤘습니다.
And with that, we have covered the whole data manipulations.
5:07:32
다음 그룹에서는 계산에 대해 이야기할 것입니다.
in the next group we're going to talk about the calculations and here
5:07:35
현재 우리는 길이 함수 하나만 있습니다.
we have only one function the length now
5:07:41
링크 함수는 매우 간단합니다. 몇 개를 셀 것입니다.
the links function it's very simple it's going to go and count how many
5:07:44
하나의 값에서 몇 개의 문자가 있는지 계산하고 있습니다.
characters you have in one value so you are calculating
5:07:47
값의 길이를 계산하고 있습니다. 이해하기 쉬운 예를 들어보겠습니다.
the length of a value let's have very simple example to understand
5:07:51
이제 마리아라는 값을 가지고 있다고 가정해 보겠습니다.
it okay so now let's say that we have the value maria if you apply
5:07:54
링크 함수를 적용하면 어떻게 될까요? 시작할 것입니다.
the links function for that what can happen is going to go and start
5:07:57
이 값 안에 몇 개의 문자가 있는지 세기 시작합니다.
counting how many characters we have inside this value so
5:08:00
m은 1, a는 2, 3, 4, 5입니다.
the m is 1 a 2 3 4 5 in
5:08:03
출력으로 5라는 숫자를 얻게 됩니다. 5는
the output you will get the number 5 so 5 is
5:08:06
이 값의 길이 또는 총 문자 수입니다.
the length or the total number of characters in this value now
5:08:10
350이라는 숫자가 있다고 가정해 보겠습니다.
let's say that you have a number like 350 if you go and apply
5:08:13
링크 함수는 여전히 몇 개의 자릿수를 셀 것입니다.
the links function still is going to go and count how many digits
5:08:16
3은 1, 5, 2, 3입니다.
do we have the three is one five two three so
5:08:19
그 총 링크는 3이 될 수 있습니다. 숫자에도 적용할 수 있습니다.
the total links for that can be three so you can apply it even for
5:08:22
날짜 값에도 적용할 수 있습니다.
numbers and not only that you can go and apply it on a date value
5:08:25
2026년 1월 23일이라는 날짜가 있다고 가정해 보겠습니다.
so let's say that you have the following date 2026 first
5:08:29
각 자릿수와 각 문자를 세고, 언더스코어도 포함됩니다.
23 so it's going to go and count each digit each character even the underscores not only the numbers underscore is as well a digit right so the total length of this day it's gonna be 10.
5:08:40
어떤 데이터 유형에도 링크 함수를 적용할 수 있습니다.
so you can apply any data type to the links function and in the
5:08:43
출력으로 항상 숫자를 얻게 됩니다. 이렇게
output you will get always a number that's it this is how you
5:08:46
어떤 값의 문자 수를 셀 수 있습니다. 이제 기술로 돌아가서
can count the number of characters in any value let's go back to skill in order to practice stats okay so now we have the task calculate the length
5:08:53
각 고객의 이름 길이를 계산하는 작업을 하겠습니다.
of each customer's first name so it is very simple
5:08:56
이름 열에 길이 함수 len을 적용할 것입니다.
we're gonna go and apply the function length l e n to
5:09:00
이름 열에 적용하고 길이라고 부를 것입니다.
the column first name and we're gonna call it length
5:09:03
이름을 실행해 보겠습니다.
name so let's go and execute it and with that
5:09:06
우리가 얻고 있는 출력 숫자입니다.
as you can see we are getting the output numbers and these numbers
5:09:10
각 이름의 문자 수입니다.
are the number of characters of each name
5:09:13
고객의 이름의 문자 수입니다.
of our customers so this is how we calculate the length and that's it for this group now moving on to the next one it's going to be very interesting now we're going to
5:09:20
문자열 값에서 무언가를 추출하는 방법에 대해 이야기하겠습니다.
about how to extract something from a string value and
5:09:23
이제 왼쪽과 오른쪽 두 가지 함수를 다룰 것입니다.
here we're gonna cover now two functions the left and the right now
5:09:30
왼쪽 함수는 문자열 값의 시작에서 특정 문자의 수를 추출합니다.
the left function gonna go and extract specific number
5:09:34
값의 시작에서 몇 개의 문자를 가져오고 싶다면 왼쪽을 사용할 수 있습니다.
of characters from the start of a string value
5:09:37
하지만 이제 오른쪽 함수는 정반대입니다.
so if you want to get few characters at the beginning of a value you can use the left but now the right function is exactly the opposite we're gonna go and extract specific number of characters from the end of string value.
5:09:49
값의 끝에서 몇 개의 문자를 가져오고 싶다면 오른쪽을 사용할 수 있습니다.
So if you want few characters from the end of your value, you can use right.
5:09:53
왼쪽 또는 오른쪽 함수를 적용하려면 SQL에 두 가지를 제공해야 합니다.
Now in order to apply the left or the right function, you have to give SQL two things.
5:09:57
추출할 부분의 값과 추출할 문자 수입니다.
The value where you want to extract a part from it and the number
5:10:01
문자 수는 왼쪽과 오른쪽 모두에 동일합니다.
of characters how many characters you want to extract and this
5:10:04
이 값을 다시 가지고 있다고 가정해 보겠습니다.
is the same for the left and the right now let's say that we have again this value
5:10:07
마리아이고, 작업에서 첫 두 문자를 추출하라고 한다면
maria and now if the task says i would like to extract the
5:10:10
시작 위치에 대해 이야기하고 있으므로 왼쪽 함수를 사용할 것입니다.
first two characters and since we are talking about the starting
5:10:13
두 문자를 요청했으므로 두 개로 시작하겠습니다.
position we're gonna use the left function and since it says
5:10:16
m은 하나, a는 둘입니다.
two characters we're gonna go with the two so it's really gonna start counting
5:10:20
그 후에 멈추고 잘라서 두 문자를 반환할 것입니다.
m is one a is two and after that it's gonna stop
5:10:23
m a, 왼쪽에서부터 세고 있습니다.
and make a cut and this girl gonna go and return the two characters
5:10:26
오른쪽으로 가고 있습니다. 작업에서 마지막 두 문자를 추출하라고 한다면
m a so we are counting from the left side going to
5:10:29
여기서 마지막 두 문자를 이야기하고 있습니다.
the right side right now if your task says extract
5:10:32
값의 끝 위치에 대해 이야기하고 있습니다.
the last two characters here we are talking about the
5:10:35
오른쪽에서 접근하고 있으므로 오른쪽 함수를 사용할 것입니다.
end position of your value and for that we're gonna use the
5:10:38
오른쪽에서 두 문자를 원하므로 오른쪽에서 세기 시작할 것입니다.
right function since we are approaching from the right side and since we want only two characters the number of characters gonna be two so this time it's gonna start counting from the right side
5:10:47
왼쪽으로 이동하므로 a는 하나 i는
moving to the left side so a is one i is
5:10:51
두 개 그리고 그게 전부입니다. 그러면 sql이 멈추고 추출할 것입니다.
two and that's it then sql gonna stop and extract
5:10:54
두 문자만 i a를 추출하려면
only those two characters i a so if you want to extract
5:10:57
시작 위치에서 데이터를 사용하려면 왼쪽을 사용하지만
data at the starting position you use the left but if you want to
5:11:00
값의 끝 위치에서 문자를 추출하려면
extract characters from the end position of your value then
5:11:03
오른쪽 함수를 사용합니다. 이제 sql로 돌아가서 연습해 보겠습니다. 자, 이제 다음 작업이 있습니다. 각 이름의 처음 두 문자를 가져옵니다. 그래서 우리는 처음 두 문자만 필요합니다.
you use the right function now let's go back to sql in order to practice okay so now we have the following task retrieve the first two characters of each first name so we just need the first two characters
5:11:14
왼쪽에서 오기 때문에
since we are coming from the left side we can go and use the
5:11:17
왼쪽 함수를 사용할 수 있습니다. 그래서 아주 간단합니다. 이름과
function left so it's very simple first name and
5:11:21
두 문자만 필요하므로 두 개입니다. 그래서 우리는 그것을 처음이라고 부를 것입니다.
we need only two characters so two so we're gonna call it first
5:11:24
두 문자 실행해 보겠습니다.
two character let's go and execute it
5:11:27
출력에서 두 문자가 보입니다. 이제 ma가 있습니다.
and now you can see in the output we have two characters ma now
5:11:30
john과 함께 우리는 g만 있습니다. 왜냐하면 앞에 공백이 있기 때문입니다.
with john we have only g because we have a leading space
5:11:34
그대로 두거나 변환할 수 있습니다.
well you can leave it like this or you can transform it and
5:11:37
그런 다음 george는 ge가 되고, 그래서 우리는 처음 두 문자를 얻고 있습니다. 이제 john을 수정하기 위해 할 수 있는 것은 trim을 먼저 하고 left를 적용하는 것입니다.
then george we have ge and so on so with that we are getting the first two characters now in Now in order to fix it for John, what you can do, we can say trim first and then apply the lift.
5:11:47
그렇게 하면 모든 공백이 제거되고 left를 적용합니다. 그래서 모든 것이 완벽하게 보입니다. john의 경우 J.O.가 있습니다.
So with that, we are getting rid of all white spaces and then we apply the lift. So with that, everything looks perfect. So for John, we have J.O.
5:11:54
이것이 열의 처음 두 문자를 얻는 방법입니다. 이제 다음으로 넘어갑니다.
So this is how we can get the first two characters of a column. Now let's move to the next one.
5:11:59
작업은 각 이름의 마지막 두 문자를 가져오라고 합니다. 그래서 이번에는 마지막 두 문자가 필요합니다.
The task says retrieve the last two characters of each first name. So this time we need the last two.
5:12:05
우리는 오른쪽에서 오고 있습니다. 그래서 이렇게 할 수 있습니다. 우리는 오른쪽 이름을 말할 것이고, 마지막 두 문자도 말할 것입니다.
So we are coming from the right side. So we can do it like this. We're going to say right first name and then as well to the last two character.
5:12:16
실행해 보겠습니다. 이제 출력에서 볼 수 있듯이, 우리는 이름의 마지막 두 문자가 있는 새 열이 있습니다.
Let's go and execute it. And now as you can see the output, we have new column where we have the last two characters from the first name.
5:12:22
여기 IA, ER이 있으며 john도 잘 작동합니다. trailing space가 없기 때문입니다.
So we have here IA, ER and for John as well working. That's because we don't have any trailing spaces.
5:12:29
그러나 trailing space가 있으면 trim 함수를 사용하세요. 알겠습니다. 그래서 왼쪽과 오른쪽에 대한 모든 것이었습니다.
But if you have any trailing spaces, then go and use that trim function. All right. So that's all for the left and right.
5:12:34
이제 마지막 함수로 넘어갑니다. substring이 있습니다.
And now we're going to go to the last function. We have the substring.
5:12:41
substring은 지정된 위치에서 문자열의 일부를 추출합니다.
So the substring gonna go and extract a part of a string at a specified position.
5:12:46
이번에는 시작이나 끝에서 무언가를 원하지 않고 중간에 있는 무언가를 원합니다.
So this time we don't want something from the beginning or the end, we want something like in the middle.
5:12:51
시작 위치를 지정하고 그곳에서 몇 문자를 추출하고 싶습니다.
So we want to specify the starting position and we want to extract few characters from there.
5:12:56
그래서 시작 위치를 지정하고 거기서 몇 글자를 추출하고 싶습니다.
So let's have a very simple example to understand it. Now in order to use the substring you need three things.
5:13:01
첫 번째는 특정 부분을 추출하고자 하는 값입니다. 그리고 SQL이 추출을 시작할 시작 위치를 지정해야 합니다.
The first one is the value itself where you want to extract a specific part from it and And then you have to specify the starting position where SQL gonna start extracting the characters that you want.
5:13:12
SQL은 또한 링크가 필요합니다. 몇 글자를 추출해야 하는지요. 이제 다음 작업을 해보겠습니다.
And as well SQL needs the links. How many characters we have to extract. So now let's say that we have the following task.
5:13:18
두 번째 문자 이후에 두 글자를 추출합니다.
After the second character extract two characters.
5:13:21
이것을 읽으면 시작 위치를 지정했음을 알 수 있습니다.
So from reading this you can see we specified the starting position.
5:13:25
이것은 두 번째 문자이며 링크는 두 글자가 됩니다. 예를 들어, Maria가 있다고 가정해 봅시다.
This is the second character and the links gonna be the two characters. So let's have this example. If you have Maria.
5:13:31
이제 시작 위치를 지정해야 합니다. 두 번째 문자 이후에 있다고 말하고 있습니다. 첫 번째 문자 M은 1입니다.
So now we have to specify the starting position. Now we are saying after the second character. So the first character M is 1.
5:13:38
그럼 A는 2입니다. 2 이후에 위치 번호 3이 됩니다. 맞죠? R부터 시작합니다.
Then A is 2. After 2 we got the position number 3. Right? So starting from R.
5:13:44
즉, SQL에 대해 3을 지정해야 합니다. 시작 위치는 3번이 될 수 있습니다. 이것은 2 이후입니다.
So that means we have to specify for SQL 3. Because the starting position can be number 3. This is after the 2.
5:13:50
이제 우리는 단지 2글자만 원합니다. R과 I를 원합니다. 이것을 SQL에 주면 Maria의 시작 위치는 3입니다.
Now we want only 2 characters. So we want the R and the I. If you give this to SQL Maria. Starting position 3.
5:13:58
길이는 2입니다. SQL은 두 글자, R과 I를 추출할 수 있습니다. 이것이 바로 당신이 원하는 것입니다.
And the length 2. SQL can go and extract the 2 characters. The R and I. And this is exactly what you want.
5:14:04
우리는 두 번째 위치, 두 번째 문자 이후에 두 글자를 원합니다. 그래서 우리는 왼쪽이나 오른쪽에서 무언가를 추출하지 않았습니다.
We want two characters after the second position, the second character. So with that, we didn't extract something from the left or from the right.
5:14:11
우리는 특정 위치에서 추출했습니다. 이것이 바로 substring이 필요한 이유입니다.
We extracted at specific position. And this is exactly why we need the substring.
5:14:16
이제 조금 더 어렵게 만들어 보겠습니다. 두 번째 문자 이후에 모든 문자, 즉 모든 글자를 추출하겠습니다.
Now, let's make it a little bit more difficult, where we're going to say after the second character, extract everything, all the characters.
5:14:22
그래서 ri뿐만 아니라 ri a도 원합니다. 이제 시작 위치에 대한 것은 변하지 않았습니다. 우리는 3에 머물 것입니다.
So not only ri, I would like ri a. So now nothing's changed about the starting position. We're going to stay at three.
5:14:28
하지만 이제 이 값을 보고 R부터 시작하여 모든 것을 추출하고 싶다면 길이를 3으로 지정해야 합니다.
But now if you are looking to this value and you want to extract everything starting from R, that means you have to specify the length of 3.
5:14:36
하지만 이것은 그리 좋지 않습니다. 같은 열에 또 다른 값을 가져오겠습니다. 그래서 우리는 Martin이 있습니다. 시작 위치도 R이 될 것입니다.
But this is not really good because let's have another value in the same column. So we have Martin. So the starting position is going to be as well R.
5:14:43
그리고 이제 길이는 달라질 것입니다. 여기 4글자가 있습니다. 이제 길이는 더 이상 3이 아니라 4입니다.
And now the length is going to be different. So we have here 4 characters. So now the length is not anymore 3, it is 4.
5:14:50
하지만 SQL에 대해 끝에 무언가를 지정해야 합니다. 4로 가도 Maria에게는 괜찮습니다.
But you have to specify something at the end for SQL. You can go for 4, that's fine for Maria as well.
5:14:55
하지만 값이 많으면 정확한 길이를 지정하기가 정말 어려울 것입니다.
but if you have a lot of values it's gonna be really hard to specify
5:14:58
정확한 길이를 지정하기 때문에 3이나 4와 같은 고정 숫자를 지정하는 대신
exactly the correct length that's why instead of specifying
5:15:02
3이나 4와 같은 고정 숫자를 지정하는 대신 다른 함수를 사용할 수 있습니다.
a static number like three or four we can use another function
5:15:06
이제 친구들, 길이 함수를 사용하면
so now my friends if you use the length function you
5:15:09
문자의 총 개수를 얻을 수 있습니다. 그러므로
will get the total number of characters right so for
5:15:12
maria는 5를 얻고 martin은 6을 얻습니다.
maria you will get five for martin you will get six
5:15:15
그리고 그 숫자는 링크에서 사용하기에 괜찮습니다.
and those numbers are okay to use in the links because they are
5:15:18
우리가 필요로 하는 것보다 많고, 그건 전혀 문제되지 않습니다.
more than what we need and that's totally fine so if So if you are saying, okay, for Maria, start from the third position and cut for me five characters, SQL gonna find only three, but you will not get an error.
5:15:28
그래서 당신이 말하고 있다면, 마리아를 위해 세 번째 위치에서 시작하고 다섯 글자를 잘라주세요.
So you are extracting more than you need and you will always get all the characters after the starting position.
5:15:34
SQL은 세 개만 찾을 것이지만, 오류는 발생하지 않을 것입니다.
So this is a little trick that we use in order to make the links dynamic where we cannot find one value that we can use in all scenarios.
5:15:42
다음 작업은 고객 목록을 가져오는 것입니다.
And now let's go back to SQL in order to practice the substring. Okay.
5:15:46
첫 번째 문자를 제거한 후 이름입니다.
following task and it says retrieve a list of customers first
5:15:50
왜 그런지 묻지 마세요, 하지만 어떤 이유로 우리는
names after removing the first character so now
5:15:53
첫 번째 이름의 첫 문자를 보고 싶지 않습니다.
don't ask me why but for some reason we don't want to see the
5:15:56
그것을 제거하고 싶습니다.
first character of the first names we want to remove it so
5:15:59
어떻게 할 수 있을까요? 우리는 왼쪽이나 오른쪽을 사용할 수 없습니다.
how we can do that we cannot use the left or the right we have to
5:16:02
서브스트링을 사용해야 합니다.
go with the substring because it is a little bit more complicated
5:16:05
그래서 서브스트링을 사용하고, 첫 번째 인수는 값이 될 것입니다.
so substring and let's go and get and the first argument gonna be the value so it comes from the first name and then And the second argument is the starting position.
5:16:14
첫 번째 이름에서 가져오고, 두 번째 인수는 시작 위치입니다.
So where we want to start. Since it is saying I want all the characters after the first character.
5:16:20
우리가 시작하고 싶은 위치입니다.
So that means we will be starting from the position number two.
5:16:24
첫 번째 문자 이후의 모든 문자를 원한다고 말하고 있습니다.
So for example, Maria here, the first character M, position number one, and we want to start our substring from the position number two.
5:16:31
그래서 우리는 두 번째 위치에서 시작할 것입니다.
So that was the easy part. Now the next one, the question is how much characters we want to leave.
5:16:38
예를 들어, 마리아의 경우 첫 번째 문자는 M이고, 위치 번호는 1입니다.
So do we leave here like four characters? Like in Maria, we have four characters, but in John, we have only three.
5:16:45
우리는 두 번째 위치에서 서브스트링을 시작하고 싶습니다.
Then the next one is four and so on. So if you go, for example, with four and let's call it sub name.
5:16:52
그래서 그건 쉬운 부분이었습니다.
So we make it static. What can happen? It's going to work for some scenarios like Maria.
5:16:57
다음 질문은 얼마나 많은 문자를 남길 것인가입니다.
We have a area and for better, we are getting eater. But for Martin, it is not working.
5:17:03
여기서 네 글자를 남길까요? 마리아는 네 글자가 있지만, 존은 세 글자입니다.
We are not getting the last in because it has like five characters after the first one.
5:17:08
그 다음은 네 글자입니다.
and by just looking at the result as you can see we have here one issue with john and that's because the first character is an empty string so this is really annoying so that's why we use the trim first
5:17:19
그래서 예를 들어 네 글자로 가면, 서브 이름이라고 부릅시다.
just to get rid of all those white spaces and now you can see
5:17:22
우리는 그것을 정적으로 만들 것입니다.
it's working fine so we are not getting the g we
5:17:25
그것이 마리아와 같은 몇 가지 시나리오에서 작동할 것입니다.
have everything after the first character so now instead of having this
5:17:28
정적이었던 것을 변수로 바꿔서 첫 번째의 길이를 사용할 것입니다.
static what you're gonna do we're gonna make it variable so we're gonna go and use the length of the first
5:17:35
그렇게 해서 우리는 충분한 길이를 확보합니다.
name so with that we make sure we
5:17:38
첫 번째 이름 안의 어떤 값이든 추출할 수 있습니다.
have enough length to extract and this can work
5:17:41
이름이 20자일지라도 가능합니다.
for any value inside the first name even if the name is
5:17:44
이제 마틴에 대해 작동하는 것을 볼 수 있습니다.
like 20 characters so let's go and execute and
5:17:48
여기 m 다음에 다섯 글자가 있고, 여기 네 글자가 있습니다.
now you can see for martin it is now working so we have
5:17:51
m 다음에도 있고, 여기 세 글자가 있습니다.
here like five characters after the m and here we have four characters
5:17:54
g 다음에도 작동하고 완전히 동적입니다.
after the m as well and here we have three characters after the
5:17:57
이것이 링크를 함께 사용하는 트릭입니다.
g so it is working completely and it is full dynamic so this is the trick by using the links together with the
5:18:05
한 번에 길이, 트림, 서브스트링을 사용합니다.
substring and as you can see now we are using three functions
5:18:08
서브스트링이 SQL에서 어떻게 작동하는지 보여줍니다.
in one go we have the length we have the trim and we have
5:18:11
여러 함수를 함께 사용하여 복잡한 문제를 해결합니다.
the substring and this is what happens in sql we use multiple
5:18:14
작업을 해결하기 위해 여러 함수를 함께 사용합니다.
functions together in order to solve like complex
5:18:17
문자열에서 서브스트링을 추출하는 방법입니다.
tasks so this is how you can extract a substring from
5:18:21
서브스트링에 대한 모든 것입니다.
a string all right so that's all about the substring and
5:18:24
SQL에서 중요한 문자열 함수들을 다뤘습니다.
with that we have covered a lot of very important string functions in sql and now you have enough tools in order to manipulate the string
5:18:31
이제 문자열 값을 조작하는 방법을 배웠습니다.
values in your data okay my friends so with that you have learned how
5:18:34
SQL에서 문자열 값을 조작하는 방법입니다.
to manipulate your string values inside sql using
5:18:37
숫자, 즉 숫자 값을 조작하는 방법을 배울 것입니다.
the string functions now we will move to the second one you
5:18:40
자, 시작해봅시다.
will learn how to manipulate the numbers the numeric values
5:18:43
자, 가자
so let's go okay
5:18:49
자, 이제 이 예를 들어보자 3.516
so now let's have this example 3.516 now
5:18:52
함수 round를 적용하고 싶다고 가정해보자
let's say that you want to apply the function round and you are using
5:18:55
소수점 두 자리로 설정했을 때, 일어날 수 있는 일은
two decimal places so what can happen is going to go and
5:18:58
소수점 아래 두 자리만 남기는 것이다
keep only two digits after the decimal point
5:19:01
그래서 5와 1 그리고 소수점 뒤 세 번째 자리
so five and one and the third digit after the decimal
5:19:05
6이 숫자가 올림될지 결정할 것입니다.
six it will decide whether the number gonna round up
5:19:08
아니면 그대로 유지될지 그리고 이제 6은
or stay as it is and now since six is higher than
5:19:11
5보다 크기 때문에 SQL이 돌아갈 것입니다.
five so that means sql gonna go around
5:19:14
숫자를 올려서 51 대신 52를 얻습니다.
the numbers up so instead of having 51 we
5:19:17
그리고 그 후 세 번째 자리는 0으로 초기화될 수 있습니다.
will get 52 and after that the third digit can reset to
5:19:21
그래서 출력에서는 3.52를 얻습니다. 이제 소수점 한 자리만 반올림했다고 가정해 봅시다.
zero so in the output you will get 3.52 now let's say that you have done round but only for one decimal place now
5:19:28
한 자리만 유지할 것이고 그것은
is going to go and keep only one decimal place and that is
5:19:31
5와 두 번째 자리가 이번에는 결정할 것입니다.
the five and the second digits this time gonna decide whether
5:19:35
올림할지 말지 그리고 이제 1은
we round up or not and now since one is less than
5:19:38
5보다 작기 때문에 올림할 필요가 없고 5는 그대로 유지됩니다.
five there is no need to round up and the five gonna stay
5:19:41
그래서 6으로 바뀌지 않고 올림이 없으므로 5 뒤의 자리는 0으로 초기화됩니다. 그래서 3.5를 얻습니다. 이제 0으로 반올림한다고 가정해 봅시다.
as it is it will not turn to six so there is no round up and the digits after the five gonna reset to zero so we're gonna get 3.5 now let's say that you say around zero.
5:19:51
그래서 소수점 뒤에 어떤 자리도 보고 싶지 않다는 의미입니다.
So that means I don't want to see any digits after the decimal point.
5:19:54
그래서 이제 SQL이 소수점 뒤 첫 번째 자리, 즉 5를 확인할 것입니다.
So now SQL going to go and check the first digit after the decimal point, the five, this
5:20:00
그것이 3이 4로 바뀔지 결정할 것입니다.
I'm going to decide whether the three going to turn to four or not.
5:20:03
그리고 이제 5가 있으므로 숫자를 반올림하기에 충분합니다. 왜냐하면 5 이상이면 숫자를 반올림하기 때문입니다.
And now since we have five, it is good enough to round the number because either five or above five going to round the numbers.
5:20:10
그래서 이것이 올림이 될 것이고 SQL은 마지막에 4를 반환할 것이며 소수점 뒤의 모든 자리는 0으로 초기화될 것입니다.
So that's why it's going to be a roundup and SQL going to return at the end four and all the digits after the decimal point going to be reset to zero.
5:20:18
그래서 이것이 SQL에서 round 함수가 작동하는 방식입니다. 이제 SQL에서 이를 수행하는 방법을 살펴보겠습니다.
So this is exactly how the round function works in SQL. So now let's see how we can do that in SQL.
5:20:24
좋습니다, 이제 숫자 함수에 대해 연습해 봅시다. 우리가 할 수 있는 것은 SQL select를 작성하는 것입니다.
OK, so now let's go and practice about the number functions. So what we can do, we're going to write SQL select.
5:20:29
하지만 이번에는 데이터베이스에서 어떤 데이터도 선택하지 않을 것입니다.
but this time we'll not select any data from the database we're
5:20:32
정적 값을 사용하여 연습할 것입니다. 예를 들어
gonna practice using our static value like for example the
5:20:35
값 3.516을 사용하여
value 3.516 so let's
5:20:39
실행해 보겠습니다. 그래서 지금 이 소수점을 가진 숫자가 있습니다.
go and execute it so with that i have this decimal number now
5:20:42
이제 이 숫자 3.516을 반올림해 봅시다.
let's go and start practicing the round function so
5:20:45
이번에는 두 자리까지 반올림하고 가봅시다.
now let's go around this number 3.516 and
5:20:49
이번에는 소수점 두 자리로 반올림하겠습니다.
this time we are rounding two decimals so let's go
5:20:52
두 자리로 반올림하겠습니다. 이제 실행해봅시다.
and call it rounds two and let's go and execute
5:20:55
출력에서 두 자리로 반올림하고 있습니다.
it so as you can see in the output we are rounding two decimal
5:20:59
여기서 두 자리를 얻었습니다. 여섯이 올라가게 됩니다.
places and we have the two because as we learned the six gonna
5:21:02
이제 하나에 대해서도 같은 작업을 해봅시다.
go and round it up now let's go and do the same
5:21:05
하나에 대해서도 반올림하겠습니다.
thing for one so let's round one
5:21:08
출력에서 반올림하고 있습니다.
execute and as you can see in the output we are rounding
5:21:12
소수점 한 자리로 반올림하겠습니다.
to one decimal so we have the five and everything is zero and we don't have six here because the one is lower than five
5:21:19
여기서 소수점이 0이기 때문에
and it will not round up the numbers and let's undround
5:21:22
제로에 의해 그것은
by the zero it is
5:21:25
정수로 반올림하여 네 개와 모든
rounding it to an integer to the four and all the
5:21:28
소수 자릿수가 제로이고 우리가 네 개를 가지는 이유는
decimal digits are zero and we have four because we have
5:21:31
다섯과 다섯이 숫자를 반올림할 것이기 때문입니다. 그래서 당신이 볼 수 있듯이
five and five gonna round up the number so as you can
5:21:34
정말 멋지고, 이것이 SQL에서 숫자를 반올림하는 방법입니다. 이제 정말 멋진 또 다른 숫자 함수가 있습니다. 그것은 APS 또는 절대값이라고 합니다.
see it is really nice and this is how we round numbers in sql now there is another number function which is really cool called aps or the absolute
5:21:46
그것이 할 일은 모든 음수를
what it's gonna do it's gonna go and convert any negative number to
5:21:49
양수로 변환하는 것입니다. 그러니 제가 무슨 뜻인지 보여드리겠습니다. 가서
a positive so let me show you what i mean let's go and say
5:21:52
우리가 마이너스 10을 가지고 있다고 가정해 보겠습니다. 이것은 음수입니다. 하지만
we have like minus 10 so this is a negative number but
5:21:56
제가 abs라고 말하면, 그러면 마이너스의 절대값인
if i say abs so the absolute of the minus
5:21:59
10을 얻을 것입니다. 그러면 양수 숫자를 얻을 것입니다.
10 what i will get i will get a positive number
5:22:02
그래서 이것은 어떤 숫자의 절대값을 주는 것과 같거나
so it's like giving us the absolute of any number or in
5:22:05
다른 말로 하면 음수를 양수로 변환하는 것과 같고, 만약 숫자가 이미 양수라면 아무 일도 일어나지 않습니다. 그래서 제가 10의 절대값을 말하면 10도 얻을 것입니다.
other words it is like converting the negative to a positive and if the number is already positive nothing gonna happen so if i say the absolute of the 10 i will get as well a 10.
5:22:16
그래서 이것은 정말 멋지고 중요한 함수로, 많은 시나리오에서 숫자를 변환하는 데 필요합니다.
So this is really nice and cool function that is really important in order to transform numbers in many scenarios.
5:22:21
예를 들어 데이터베이스에 실수가 있는 경우, 예를 들어 마이너스 매출이 있다고 가정해 보겠습니다. 마이너스 매출이 있다는 것은 말이 되지 않습니다.
Like if you have mistakes on your database, like let's say a minus sales, it makes no sense to have sales that is minus.
5:22:28
그래서 데이터를 수정하기 위해 우리는 APS를 사용하여 모든 음수를 양수로 변환할 수 있습니다.
So in order to correct the data, we can use the APS in order to convert all the negative numbers to a positive.
5:22:34
그래서 이것은 배우기 정말 멋지고 쉽고 간단한 함수입니다. 좋아요, 친구들, 그래서 숫자 함수에 대한 모든 내용은 여기까지입니다.
So this is really nice, cool and easy function to learn. All right, my friends, so that's all for the numeric functions.
5:22:39
우리는 두 가지 매우 간단한 함수를 다뤘습니다. 이제 다음 주제에서는 SQL에서 날짜와 시간을 조작하는 방법에 대한 많은 함수가 있습니다.
We have covered two very simple functions. And now in the next topic, we have a lot of functions about how to manipulate the date and time in SQL.
5:22:47
자, 시작해봅시다. 날짜란 무엇인가요?
So let's go. So what is a date?
5:22:53
달력을 살펴보고 아무 날짜나 선택하면
If you take a look at calendar and you pick any
5:22:56
예를 들어, 2025년 8월 20일과 같은 날짜는
dates, for example, August 20th, 2025, this
5:23:01
생일이나 직장에서의 프로젝트 마감일과 같은 이벤트를 나타낼 수 있습니다.
date could represent an event like a birth date, or a project deadline at your work.
5:23:13
주로 세 가지 구성 요소가 있습니다. 첫 번째 부분은 연도를 나타내는 네 자리 숫자입니다.
And mainly it has three components. The first part is a four digit number indicating the year.
5:23:18
다음 구성 요소는 월입니다. 일반적으로 우리는 월을 1에서 12 사이의 숫자로 나타냅니다.
Then the next component, it is the month. So normally we represent the month with a number between 1 and 12.
5:23:25
마지막 구성 요소는 일입니다. 이는 월에 따라 1에서 31 사이의 숫자입니다.
And the last component is the day. This is a number between 1 and 31, depending on the month.
5:23:31
이제 데이터베이스에서는 이 세 가지 구성 요소의 구조를 날짜라고 부릅니다. 이것이 SQL에서 날짜를 의미하는 것입니다.
Now in database, we call this structure of those three components a date. So this is what we mean with dates in SQL.
5:23:38
자, 이제 다음으로 넘어갑시다. 시간은 하루의 특정 시점을 나타냅니다.
All right, so now let's move to the next one. What is time? Time refers to a specific point within a day.
5:23:44
예를 들어, 우리는 18시 55분 45초가 있습니다.
Like for example, we have 18 o'clock, 55 minutes, and 45 seconds.
5:23:49
이 구조에도 세 가지 구성 요소가 있습니다. 첫 번째는 시간을 나타냅니다.
So this structure has as well three components. The first one we call it the hours.
5:23:53
이는 하루의 시간을 나타내는 0에서 23 사이의 숫자입니다. 다음은 분입니다.
It is as well a number between 0 and 23, indicating the hour of the day. Then the next one, it is the minutes.
5:24:00
이는 0에서 59 사이의 숫자입니다. 마지막 구성 요소로는 초가 있습니다.
This is a number between 0 and 59. Moving on to the last component, we have the second.
5:24:05
이는 다시 0에서 59 사이의 숫자입니다.
This is again the same thing, a number between 0 and 59.
5:24:10
이제 이 세 가지 구성 요소로 이루어진 구조를 데이터베이스와 SQL에서 시간을 나타내는 것입니다. 이것이 우리가 시간을 의미하는 것입니다.
So now this structure with those three components, we call it in databases and SQL a time. So this is what we mean with the time.
5:24:17
마지막 유형으로 넘어가면, 날짜와 시간을 결합하여 나란히 놓으면 새로운 구조와 새로운 이름이 데이터베이스에 생깁니다.
Now to the last type, if you go and combine both the date together with the time and you put them side by side, you will get a new structure and a new name in the databases.
5:24:27
우리는 이를 일반적으로 타임스탬프라고 부릅니다. 이 이름은 Oracle, Postgres 및 MySQL과 같은 많은 데이터베이스에서 사용됩니다.
And we call it usually timestamp. This name is used in many databases like Oracle, Postgres and MySQL.
5:24:34
그러나 SQL 서버에서는 이를 위한 다른 이름이 있습니다. 우리는 이를 날짜 시간이라고 부릅니다. 다시 말해, 매우 간단합니다.
But in the SQL server, we have another name for that. We call it date time. So again, it's very simple.
5:24:39
날짜, 시간 또는 타임스탬프는 날짜 정보와 시간 정보를 함께 가지고 있습니다.
the date, time or timestamp has the date information together with the time information.
5:24:44
이 예제에서는 왼쪽에서 오른쪽으로 여섯 개의 구성 요소가 있습니다. 그리고 이 구조에는 계층이 있습니다.
So here in this example, we have six components from left to right. And here we have like hierarchy in this structure.
5:24:49
우리는 가장 높은 것부터 시작합니다. 그것은 연도입니다.
So we start with the highest, which is the year.
5:24:52
그 다음은 월, 일, 그리고 시간, 분, 초로 계속됩니다.
Then we have the month, the day, and then we continue to the hour, minutes and seconds.
5:24:57
이것들은 SQL에서 날짜와 시간 정보에 대한 세 가지 다른 유형입니다.
So those are the three different types about date and time informations in SQL.
5:25:02
우리는 날짜만 있거나 시간만 있거나 날짜 시간으로 함께 있습니다.
We have the date alone or the time alone or together in the date time.
5:25:07
좋습니다, 이제 데이터베이스에서 날짜와 시간 정보를 검색해 보겠습니다.
All right, let's explore now the data that we have inside our database searching for date and time informations.
5:25:13
이제 주문 테이블로 가보겠습니다. 확장하면 날짜 데이터 유형을 가진 두 개의 열이 있습니다.
Now let's go to the table orders. And if you go and expand it, you will find here two columns having the data type date.
5:25:19
주문 날짜와 배송 날짜가 있습니다.
So we have the order dates with the date and as well, the shipping date
5:25:24
데이터 유형 날짜이며 마지막 열의 생성 날짜를 확인해 보세요.
the data type dates and if you check the last column the creation
5:25:27
이것도 날짜 및 시간입니다. 이제 정보를 쿼리하여 구조를 이해해 보겠습니다.
date this one is date time too so now let's
5:25:30
주문 ID, 주문 날짜, 배송 날짜 및 생성 시간을 선택하겠습니다.
go and query those informations in order to understand the structure i'm just going to select the order id the order dates and the ship date and the creation time
5:25:44
판매 주문에서 이 큰 데이터에서
from sales orders and from this big
5:25:47
이제 실행해 보겠습니다. 두 주문을 확인해 보세요.
so let's go and execute it now if you go and check both order
5:25:50
주문 날짜와 배송 날짜를 확인하면 여기에는
date and ship date you can find that here we have only
5:25:53
날짜에 대한 구조 또는 정보가 있습니다.
the structure or the information about the dates and we have
5:25:56
시간에 대한 정보는 없습니다. 그래서 여기에는 연, 월,
nothing about the time so again here we have a year month and
5:26:00
일이 있습니다. 그래서 데이터 유형이 날짜입니다. 이제
day and that's why they have the data type date now let's go
5:26:03
생성 시간을 확인해 보겠습니다. 날짜 정보가 있습니다.
and check the creation time not only we have the date information
5:26:06
시간 정보도 있습니다. 그래서 날짜 정보로 시작합니다.
but as well we have that time information so it starts
5:26:09
연, 월, 일 그리고 시간, 분, 초가 있습니다.
with the date information year month day and then we
5:26:12
초의 분수, 밀리초 등이 있습니다. 이것이 데이터베이스의 날짜 및 시간 형식입니다.
have hour minute and seconds and then we have fractions of the seconds milliseconds and so on so this is how the date time or timestamp looks like in databases and this is how the date looks like
5:26:28
좋습니다, 친구들. 이제 SQL에서 우리는
all right my friends now in sql i can say that we
5:26:31
쿼리할 수 있는 세 가지 다른 소스가 있습니다.
have three different sources in order to query the
5:26:34
첫 번째는 데이터베이스에 저장된 날짜입니다.
dates the first one is dates that are stored inside
5:26:38
주문 날짜, 배송 날짜, 생성 시간 등입니다.
our database like we saw here in those columns like
5:26:41
이 모든 것은 날짜 정보를 포함하는 열입니다.
the order date shipping date creation time all those are
5:26:44
우리 데이터베이스에 저장되어 있습니다. 이것이 첫 번째 소스입니다.
columns that holds dates informations and they
5:26:47
쿼리에서 가져올 수 있는 날짜입니다. 이제
are stored inside our database so this is the first source of
5:26:50
그것들을 제거하고 생성 시간에 집중하겠습니다.
dates that we can get inside our queries let me just remove
5:26:53
실행해 보겠습니다. 이것이 저장된 날짜 및 시간 정보입니다.
those stuff and let's stick with the creation time so let's just
5:26:56
이것을 실행하면 날짜와 시간 정보가 저장됩니다.
execute it so those are date and time informations stored
5:26:59
우리 데이터베이스 내부에서 두 번째 유형은 쿼리에서 사용할 수 있는 하드코딩된 날짜 문자열입니다. 예를 보여드리겠습니다.
inside our database the second type is a hard-coded date string that we can use inside our queries let me show you an example so now if we go to a new line i can go and define a date like this
5:27:12
2025년 8월 20일입니다.
So 2025, August 20th.
5:27:15
이 문자열에서는 모든 행에 대해 정적 날짜를 하드코딩했습니다.
So that in this string, we have hard coded a date that is static for all rows.
5:27:21
하드코딩이라고 부르겠습니다. 이제 실행해 보겠습니다.
Let me just call it hard coded. And let's go and execute it.
5:27:25
출력에서 모든 행에 대해 정적 날짜를 얻을 수 있습니다.
Now we can see in the output, we're going to get a static date for all rows.
5:27:30
이 값은 우리 데이터베이스에 저장되지 않습니다.
So this is going to be the same for all rows inside our table. So this value is not stored inside our database.
5:27:36
이 값은 쿼리에 추가하고 하드코딩한 것입니다.
This value I just added to our query and hard coded it.
5:27:40
때때로 쿼리에서 나중에 계산에 사용할 날짜를 정의합니다.
So sometimes in queries, we define our dates that's going to be used maybe later in calculations and so on.
5:27:45
이제 쿼리에서 날짜를 얻는 세 번째 방법은 getDate 함수를 사용하는 것입니다.
Now, the third source of getting dates inside our query is using the function getDate.
5:27:51
GetDate는 SQL에서 사용하는 첫 번째이자 가장 중요한 함수입니다.
GetDate is the first and the most important function that we use in SQL.
5:27:55
쿼리를 실행하는 순간의 현재 날짜와 시간을 반환합니다. 한번 해보겠습니다.
It's going to go and return the current date and time at the moment of executing the query. So let's try that out.
5:28:02
새 줄을 가져오겠습니다. getDate입니다. 매우 간단합니다. 함수 내부에 값을 받지 않으므로 비어 있습니다.
I'm going to go and get a new line. So getDate. It's very simple. It doesn't accept any values inside the function, so it's going to be empty.
5:28:10
오늘이라고 부르겠습니다. 이제 실행해 보겠습니다.
so let's call it today all right let's go and execute it
5:28:13
물론 get date로 인해 다른 결과를 얻을 것입니다.
and of course we're gonna get different results because the get date
5:28:16
지금은 제가 이 영상을 녹화하고 있는 날짜와 시간입니다.
now is the date and the time that i'm recording this
5:28:19
현재 2024년 7월 18일입니다.
video so currently it is july 18 2024
5:28:23
각 행에 대해 항상 동일한 값을 얻을 것입니다.
and i'm recording this around 20 pm so as
5:28:26
쿼리 실행에 따라 달라집니다. 이 튜토리얼 동안 get date에 대해 많은 것을 배울 수 있습니다.
you can see this is gonna be as well repeated for each row we're gonna get always the same value so again this depends on the execution of that query so during the tutorial you can learn a lot about that get date and we can use it in a a lot of functions.
5:28:38
쿼리 내부에서 데이터 정보를 얻는 세 가지 방법입니다.
So those are the three different sources of getting data information inside your query, either from a column inside our database or hard coded using a string.
5:28:47
세 번째 방법은 get date를 사용하여 쿼리 실행 순간의 현재 날짜와 시간을 얻는 것입니다.
And the third one is using the get date in order to get the current date and time informations at the moment of the query execution.
5:28:55
좋습니다. 이제 SQL에서 날짜와 시간에 대한 명확한 이해가 생겼습니다.
Nice. Now we have a clear understanding what is date and time in SQL.
5:29:02
다음 질문은 SQL 함수를 사용하여 이러한 정보를 조작하는 방법입니다.
The next question is how to manipulate those informations using SQL functions.
5:29:08
좋습니다. 이제 2025년 8월 20일의 날짜가 있습니다.
Okay, now we have our date August 20th, 2025.
5:29:11
날짜로 할 수 있는 것 중 하나는 날짜의 다양한 부분을 추출하는 것입니다.
One of the things that we can do with the date is we can go and extract different parts of the dates.
5:29:16
예를 들어, 우리는 오직 연도에만 관심이 있습니다. 그래서 우리는 연도 부분만 추출할 수 있습니다.
For example, we are interested only on the year. So we can go and extract only the year part.
5:29:21
또는 월에 관심이 있다면, 월을 추출할 수 있고 8월을 얻을 수 있습니다. 물론, 우리는 날짜를 추출할 수 있고 20을 얻을 것입니다.
Or if you are interested in the month, you can go and extract the month and you will get August. And of course, we can go and extract the day and we will get that 20.
5:29:28
이것이 우리가 할 수 있는 첫 번째 일입니다. 우리는 날짜의 부분을 추출할 수 있습니다.
So this is the first thing that we can do. We can extract the parts of
5:29:31
이제 우리가 할 수 있는 또 다른 일은 날짜 형식을 변경하는 것입니다.
dates now another thing that we can do is we can go and change
5:29:35
날짜 부분 사이에 작은 하이픈을 두는 대신
the date format so instead of having like
5:29:38
슬래시를 사용하여 분리할 수 있습니다. 우리는 먼저
a small minus between those date parts we can go and
5:29:41
8월, 그 다음 20일, 그리고
split them using slash we can even start first with
5:29:44
연도를 짧은 형식으로만 표시할 수 있습니다. 25 또는
the month august then 20 the day and then the
5:29:47
연도는 25년의 짧은 형식만 가지고 있습니다.
year but having only the short form of the year 25 or
5:29:50
우리는 형식을 변경할 수 있으며, 특별한 문자가 필요 없다고 말하고, 공백으로 남겨둘 수 있습니다. 그래서 날짜 형식을 변경하고 조작하고 있음을 알 수 있습니다.
we can go and change the format where we say we don't need any special character we just leave it as a space so you can see we are changing and manipulating the format of the date
5:29:59
우리가 할 수 있는 또 다른 범주나 작업은 날짜입니다.
Another category or task we can go and do date
5:30:02
계산을 하여 날짜를 가져와서 더할 수 있습니다.
calculations so we can go and take our date and add to
5:30:05
예를 들어, 3년을 더하거나,
it for example three years or we can go and find the
5:30:08
두 날짜 간의 차이를 찾을 수 있습니다. 마치 뺄셈을 하는 것처럼.
differences between two dates like we are doing a subtraction
5:30:12
또는 마이너스를 한다고 가정하면, 예를 들어 30일을 얻을 수 있습니다. 그래서 우리는 추가하거나 빼거나 두 날짜 간의 차이를 찾을 수 있습니다. 마치 날짜에 대한 계산을 하는 것과 같습니다.
or let's say a minus and we will get for example 30 days so we can go and add stuff subtract stuff or find differences between two dates it's like we are doing calculations on the dates.
5:30:21
이 날짜로 할 수 있는 마지막 작업은 이 날짜를 테스트하거나 검증하는 것입니다. SQL이 이해하는 실제 날짜인지 확인합니다.
Now to the last thing that we can do with this date is we can go and test this date or validate it whether it is a real date that SQL understands.
5:30:30
그래서 우리는 테스트를 진행할 수 있으며, 출력으로 true 또는 false, 또는 0과 1을 얻을 것입니다.
So we can put it on the test and to add the output we're going to get true or false or zero and one.
5:30:35
여기에서 볼 수 있듯이, SQL에서 날짜를 조작하는 다양한 방법이나 범주가 있습니다.
So as you can see here we have different ways or let's say categories on how to manipulate our dates in SQL.
5:30:41
이제 우리는 다양한 날짜 및 시간 기능을 네 가지 범주로 그룹화할 것입니다.
Now we're going to go and group up the different date and time functions under four categories.
5:30:46
첫 번째 범주이자 가장 중요한 범주는 부분 추출입니다.
The first category and the The most important one, we have the part extraction.
5:30:50
여기에서 이 작업을 수행하기 위해 사용할 수 있는 약 7개의 다양한 기능이 있습니다.
And here we have around seven different functions that we can use in order to do this task.
5:30:55
또 다른 범주로는 형식 및 캐스팅이 있습니다. 이 범주 아래에는 세 가지 다른 기능이 있습니다.
Another category, we have the format and casting. And here we have three different functions underneath this category.
5:31:01
형식, 변환 및 캐스트가 있습니다. 그리고 세 번째 범주는 날짜의 계산입니다.
We have the format, convert and cast. And then the third category, we have the calculations of the dates.
5:31:06
우리는 date add와 date diff라는 두 가지 기능이 있습니다.
We have two functions, date add and date diff.
5:31:09
마지막 범주인 검증에는 is dates라는 하나의 기능만 있습니다. 그래서 볼 수 있듯이 많은 스케일 기능이 있습니다.
And the last category, the validation, we have here only one function called is dates. So as you can see, we have a lot of scale functions.
5:31:16
우리는 13개의 날짜 및 시간 함수가 있습니다.
we have 13 date and time functions that you're
5:31:19
이 튜토리얼에서 날짜와 시간을 조작하는 방법을 다룰 것입니다.
going to cover in this tutorial and how to manipulate the date and time
5:31:22
SQL의 정보이며, 이를 네 가지 다른 카테고리로 그룹화할 수 있습니다. 이제 가장 큰 카테고리인 부분 추출부터 시작하겠습니다.
informations in sql and this is how we can group them into four different categories let's start now with the biggest category we have the part extraction we're going to cover all those seven functions in details on how to extract parts
5:31:38
좋아요, 친구들, 이제 SQL에서 날짜의 부분을 추출하는 세 가지 매우 간단한 함수를 다룰 것입니다.
all right friends now we're going to cover three very easy quick functions in sql to extract the parts of the dates.
5:31:44
그래서 매우 간단합니다. 날짜 함수는 날짜에서 하루를 반환할 수 있습니다.
So they are very simple that day function can return a day from a date.
5:31:49
같은 방식으로, 월은 날짜에서 월을 반환할 수 있습니다.
And in the same way, the month can return the month from a date.
5:31:53
그리고, 연도는 날짜에서 연도를 반환합니다.
And guess what the year gonna return a year from a date.
5:31:57
좋아요, 이제 그들이 어떻게 작동하는지 이해하기 위해, 2025년 8월 20일과 같은 날짜가 있습니다.
Okay, so now in order to understand how they work, we have a date like this one 2025 August 20th.
5:32:04
때때로 전체 날짜에 관심이 없고, 이 날짜에서 일부만 얻고 싶을 수 있습니다.
Sometimes you are not interested in the whole date, you would like to get only a part from this date.
5:32:09
그래서 날짜의 두 자리 숫자 20을 추출하기 위해 day 함수를 사용합니다.
So you go and use the function day in order to extract the two digits 20.
5:32:15
이제 다른 시나리오에서는 월 정보에 관심이 있을 수 있습니다. 그래서 두 자리 숫자 08을 얻고 싶습니다.
Now, in other scenario, you might be interested in the month information. So you would like to get those two digits 08.
5:32:21
그래서 우리는 month 함수를 사용하여 월 정보를 추출하여 08을 얻을 수 있습니다.
So we can use the function month in order to extract the month information in order to get the August. So 08.
5:32:29
그리고 연도 정보만 필요할 때의 상황이 하나 더 있습니다.
And one more situation where you want to have only the year information.
5:32:33
그래서 당신은 2025라는 네 자리 숫자에 관심이 있습니다.
so you are interested in the four digits 2025 so
5:32:36
그래서 연도 함수를 사용하여 추출할 수 있습니다.
you can go and use the function year in order to extract
5:32:40
출력에서 이를 적용하면 2025를 얻을 수 있습니다.
it so in the output if you apply it you will get 2025 so
5:32:43
매우 간단합니다. 이것이 이 세 가지 함수가 작동하는 방식입니다.
it's very simple this is how those three functions work
5:32:46
좋아요, 이제 이 세 가지 함수의 구문을 확인해 보겠습니다. 매우 쉽습니다.
all right now let's check the syntax of those three functions it's pretty easy
5:32:49
그래서 항상 이렇게 있습니다. 'day'라는 키워드가 있습니다.
so we have it always like this a keyword called day this
5:32:53
이것이 함수 이름이며, 하나의 매개변수만 허용합니다. 그것은 날짜입니다.
is the function name and then it accepts only one parameter it is the date the same things for the others we have a function
5:32:59
다른 함수들도 마찬가지로 하나의 매개변수만 허용합니다.
called month and they accept as well only one parameter the
5:33:02
연도에 대해서도 같은 방식입니다. 구문은 매우 간단합니다.
date and as well for the year the same thing so the syntax is very
5:33:06
하나의 값, 즉 날짜만 허용합니다.
straightforward it accepts only one value the date and
5:33:09
우리는 바의 이름처럼 함수 이름이 있습니다.
we have the function name like the name of the bar
5:33:12
우리가 추출하고자 하는 것입니다. 이제 이 함수를 사용해 보겠습니다.
that we want to extract all right so now let's try out those functions i
5:33:15
열 생성 시간으로 작업할 것입니다.
will be working with the column creation time so let's
5:33:18
예를 들어 생성 시간에서 연도를 추출해 보겠습니다.
try for example extracting the year from the creation
5:33:22
연도 함수로 생성 시간에서 연도를 추출할 것입니다.
time using the year function so it's going to be very simple it's be
5:33:25
이와 같이 연도라고 부르겠습니다.
year and then creation time like
5:33:29
이제 실행해 보겠습니다.
this and let's call it year that's it
5:33:32
생성 시간에서 2025년만 있습니다.
let's go and execute it now as you can see it's very simple we have only
5:33:35
그 결과 새로운 열이 생겼습니다.
one year 2025 from the creation time
5:33:38
그 열에는 연도 정보만 있습니다.
so with that as you can see we got a new column where we have only
5:33:41
생성 날짜에서 온 정보입니다.
the year informations inside it and this information come from
5:33:44
이제 월에 대해서도 같은 작업을 해보겠습니다.
the creation date so we have only 2025 now
5:33:48
월 생성 시간이라고 부르겠습니다.
let's go and do the same for the month so we we can have the same
5:33:51
이제 실행해 보겠습니다.
thing month creation time let's
5:33:55
출력 결과와 함께 월 번호도 있습니다.
call it month so let's execute it now as you can see
5:33:58
여기 1월, 2월, 3월이 있습니다.
the output we got as well the number of the month so
5:34:01
이 정보는 생성 시간에서 추출되었습니다.
we have here january february and march and those information
5:34:04
같은 방식으로 일 함수도 사용하겠습니다.
as well are extracted from the creation time and
5:34:08
그렇게 해서 생성
the same thing using the day function so let's go
5:34:11
시간을 일이라고 부르겠습니다.
and use that so creation
5:34:14
출력 결과에서 일 부분을 확인할 수 있습니다.
time and we call it day so now
5:34:17
생성 시간에서 1, 5, 10일이 있습니다.
as you see the output we have the day part from
5:34:20
모든 정보는 생성 시간에서 왔습니다.
the creation time so here we have one five ten and so
5:34:24
날짜 부분은 날짜의 특정 부분을 숫자로 반환합니다.
on and all those informations come from the creation time so as you can see those three functions are very simple and quick in order to extract parts from a date or date time
5:34:38
이제 예제로 돌아가서, 우리는 일, 월, 연도를 추출하는 방법을 배웠습니다.
all right so what is date part date part gonna go and return specific part of the date as a number Alright, so now back to our example, we have learned how to extract the day, month and year.
5:34:48
물론, 하루 안에 더 많은 정보를 추출할 수 있습니다.
But of course, now in a day, we have more informations that we could extract, not only the three.
5:34:53
예를 들어 주나 분기를 추출할 수 있습니다.
We could extract, for example, the week, right? The quarter.
5:34:57
그래서 모든 정보가 저장됩니다
So all those informations are as well stored
5:35:00
이 날짜에서는 값을 볼 수 없습니다
in this date we cannot see it like as a value
5:35:03
하지만 SQL에서는 추출할 수 있습니다
but inside the sql you can extract the
5:35:06
주와 분기를 추출할 수 있지만 전용 함수는 없습니다
week and quarter but we don't have a function dedicated
5:35:10
그런 것들은 일반적으로 사용되지 않기 때문입니다
for those stuff because they are not commonly used
5:35:13
연도와 월, 일처럼 여전히 날짜 부분을 사용하여 정보를 추출할 수 있습니다
like the year and month and day but still we can extract those information using the date parts for example we
5:35:19
예를 들어 날짜 부분이라고 말하고 부분을 지정할 수 있습니다
can say date part and we can specify the part
5:35:23
주로서 그리고 이 예제에 대해 반환될 것입니다
as a week and with that is going to return for this example
5:35:26
34 그리고 아마도 다른 상황에서는 관심이 있을 것입니다
34 and maybe in other situation you are interested
5:35:29
분기에서 맞습니다, 그래서 이렇게 날짜를 지정할 수 있습니다
in the quarter right so you can specify it like this date
5:35:32
부분 분기이므로 우리는 분기의 부분에 관심이 있습니다
part quarter so we are interested in the part of quarter
5:35:36
출력에서 3을 얻을 수 있습니다, 이것이 날짜 부분의 힘입니다
and in the output you will get three so this is exactly the power of the date part you can go and extract way more parts that is available in these dates.
5:35:46
연도, 월, 일에 대한 날짜 부분에 대해 주목할 점이 하나 더 있습니다
And one more thing to notice about the date part, year, month, and day,
5:35:50
모두 항상 정수로 출력됩니다
all of them are always generating the output and integer in number.
5:35:54
그래서 분기 3, 주 34, 일 20, 2025 등이 있습니다
So we have the for the quarter three, for the week 34, the day 20, 2025, and so on.
5:36:00
그래서 모든 정보는 정수입니다. 정수는 이러한 함수의 출력 데이터 유형입니다
So all of those informations are integer. So integer is the data type of the output of these functions.
5:36:07
자, 날짜 부분의 구문을 살펴보겠습니다. 함수 이름, 날짜 부분으로 시작하고 두 개의 매개변수를 받습니다
Okay, so let's have a look to the syntax of the date part. It starts with the function name, date parts, and it accepts two parameters.
5:36:14
첫 번째는 우리가 추출하고자 하는 부분입니다. 무엇을 원하나요?
The first one is the part that we want to extract. So we want to define what do you want?
5:36:19
우리는 월, 일, 연도 등을 원합니다. 두 번째 매개변수는 날짜 자체입니다
We want the month, the day, the year, and so on. And the second parameter is the date itself. So let's have an example.
5:36:25
우리는 날짜 부분이라고 말할 수 있고, 주문 날짜에서 월을 추출하고 싶습니다
We can say date part, and we would like to extract the month from the order date.
5:36:30
그래서 부분은 월이고, 주문 날짜는 추출하고자 하는 날짜입니다
So the part is the month, and the order date is the date that you want to extract from.
5:36:35
그래서 우리는 부분을 월로 지정하고 있습니다. 이제 SQL에서는 부분을 지정하는 또 다른 방법이 있습니다
So with that, we are specifying the part as a month. Now in SQL, there is another way on how to specify the parts, we can go and use like an abbreviation of the month.
5:36:44
우리는 월의 약어를 사용할 수 있습니다
So if you specify instead of month, instead of writing the whole thing, you write mm, you will get the same results.
5:36:50
그래서 월 대신 전체를 쓰는 대신 mm을 쓰면 같은 결과를 얻을 수 있습니다
So it's like abbreviation and shortcut in order to write scripts. But I rarely see that in the implementations.
5:36:55
그래서 스크립트를 작성하기 위한 약어와 단축키와 같습니다. 하지만 구현에서는 거의 보지 못했습니다
I always tend to write completely like this month because it's more like standards if you are switching between different databases.
5:37:02
보시다시피, 매우 간단합니다. SQL에 두 가지를 제공해야 합니다. 어떤 부분을 추출할지와 추출할 날짜입니다.
So as you can see, it's very simple. You have to give SQL two things, which part you want to extract and the dates that you want to extract from.
5:37:09
좋습니다. 이제 생성 시간에서 날짜 부분을 사용하여 다양한 부분을 추출해 보겠습니다.
Okay, so now we're going to go and extract different parts from the creation time using the date part.
5:37:13
예를 들어, 다시 연도를 추출해 보겠습니다. 그러니 가서 그렇게 해봅시다. 날짜 부분입니다.
Let's start, for example, by extracting the year again. So let's go and do that. Date parts.
5:37:20
그리고 어떤 부분이 필요한지 지정해야 합니다. 그래서 이렇게 연도를 작성할 것입니다.
And then we have to specify which part we need. So we're going to write year like this.
5:37:25
그리고 다음은 값이 될 것입니다. 그래서 생성 시간이 될 것입니다.
And then the next one is going to be the value. So it's going to be the creation time.
5:37:32
그래서 연도로 부르겠습니다. 그리고 날짜 부분이라고 합시다. 가서 실행해 봅시다.
So let's call it year. And let's say date parts. Let's go and execute it.
5:37:37
이제 출력에서 생성 시간에서 추출된 연도를 다시 볼 수 있습니다.
So now at the output, you can see we got as well again the years that is extracted from the creation time.
5:37:43
그래서 연도 함수와 동일할 것입니다. 그래서 둘 사이에 차이가 없습니다.
So it's going to be identical to the year function. So there is no differences between them.
5:37:47
둘 다 정수이며 연도 정보를 포함하고 있습니다. 이제 다른 부분을 시도해 보겠습니다.
Both of them are integer and it holds the year informations. Now we can go and try different parts.
5:37:53
예를 들어, 전체를 복사하고 월을 추출해 보겠습니다.
For example, let's copy the whole thing and let's extract, for example, the month.
5:37:58
여기에서 월로 변경하고 실행으로 이름을 바꿉니다.
So you can go over here and change it to month and let's rename it execute.
5:38:05
출력에서 우리는 또한 동일한 월을 얻었다는 것을 볼 수 있습니다.
so at the output you see we got as well the monsters is identical
5:38:08
날짜 함수와 동일하며 같은 방식으로
as well to the function month and the same thing for the
5:38:11
날로 변경하고 있습니다.
day so we are just changing the parts
5:38:14
출력에서 우리는
and in the output we are getting the
5:38:17
부분을 얻고 있으며, 여기에서 우리는 또한 날짜가 동일하다는 것을 볼 수 있습니다.
parts so here we have as well the days it is identical to the
5:38:20
날짜 함수이므로 지금까지 날짜 부분에서 새로운 것이 없습니다.
day function so so far we don't have something new from the date part
5:38:24
우리는 이미 다른 함수에서 가지고 있기 때문입니다. 하지만 이제
because we have it already from the other functions but now
5:38:27
연도, 월, 일 이외의 다른 부분을 추출해 보겠습니다. 예를 들어, 시간을 가져옵니다.
we're gonna go and extract other parts that are not year month and day so for example let's
5:38:33
여기에서 날짜 부분을 가지고 있고, 여기에서 시간이라고 말하고 이렇게 부릅시다.
go and get the hours so we have the date part and here as a part you say hour and let's call it here
5:38:42
시간도 마찬가지로 가서 실행해 보겠습니다. 이제 볼 수 있습니다.
as well hour let's go and execute it now you can see
5:38:45
출력에서 새로운 전용 열이 있습니다.
in the output we have a new dedicated column that
5:38:48
시간 정보만 표시되며, 여기에서 12가 있습니다.
shows only the information from the hour so we have here 12
5:38:51
23 등등이며, 이러한 정보는 시간에서 오며, 분, 초 등을 정의할 수 있습니다. 하지만 이제 분기와 같은 흥미로운 것을 가져가 보겠습니다.
23 and so on and those informations comes from the time and the same thing you can define minutes seconds and so on But now let's go and get something interesting like the quarter.
5:39:02
그래서 복사해 보겠습니다. 그리고 시간 대신 분기를 가져옵니다.
So let's go and duplicate it. And instead of hour, let's get quarter.
5:39:08
이 정보는 생성 시간에 표시되지 않지만 추출할 수 있습니다. 그래서 분기를 부르겠습니다.
So this information, it's not displayed in the creation time, but it can go and extract it. So let's call it quarter.
5:39:16
이제 실행해 보겠습니다. 출력에서 분기라는 새로운 필드가 생겼습니다.
And let's go and execute it. Now, as you can see in the output, we have one new field called quarter.
5:39:22
그 안에는 모든 날짜가 1분기 범위에 있기 때문에 모두 1입니다.
And inside it everywhere, we have one because all those dates are in the range of the quarter one.
5:39:27
보고 및 분석에 정말 놀랍습니다.
so as you can see this is amazing of course for reporting and analyzes
5:39:31
다른 것을 해보겠습니다.
let's go and have something else like
5:39:34
여기서 요일입니다.
the weekday so we are over here
5:39:37
분기를 요일로 부르겠습니다.
quarter and let's call it weekday and
5:39:40
이것을 요일로 이름을 바꾸겠습니다.
rename as well this to weekday so
5:39:43
모두 실행해 보겠습니다. 이제 다른 것을 가져오겠습니다.
let's go and execute it all right so now let's go and get something
5:39:46
예를 들어 주를 가져오겠습니다.
else like for example the week so i just
5:39:50
여기서 분기 대신 주를 작성하겠습니다. 주 번호를 가져오고 싶습니다.
duplicate it over here instead of quarter let's write week so i would like to get the weak number so let's go and execute it so now on the output as you can see we got it
5:40:00
생성 시간에서 주 번호를 보여주는 필드입니다. 이 날짜는 1주에서 왔습니다.
indicated field that show us the week number from the creation time. So we can see this date come from the week number one.
5:40:07
이 두 날짜는 2주에서 왔습니다. 그게 전부입니다.
Those two come from week number two and so on. So that's it.
5:40:10
여기서 날짜 부분에서 얻는 모든 정보는 숫자입니다.
As you can see, guys, all those informations that you are getting from the date part are numbers.
5:40:15
연도, 월, 일 외에도 더 많은 정보를 추출할 수 있습니다.
And now we can extract way more informations than only the year, month and day.
5:40:20
분기, 주 등과 같이 필드 자체에 직접 표시되지 않더라도 말입니다.
And even if those informations are not displayed directly in the field itself, like the quarter weeks and so on.
5:40:31
이제 날짜 부분과 매우 유사한 기능이 있습니다. 날짜 이름입니다.
All right, so now we have very similar function to the date part. We have the date name.
5:40:35
여기서 유일한 차이점은 날짜 부분의 이름을 반환한다는 것입니다.
So the only difference here is that it returns the name of the date part. All right, so now back to our example.
5:40:41
한 날짜에서 다양한 유형의 부분을 추출할 수 있다는 것을 배웠습니다.
We have learned we can extract different types of parts from one date. But we learned as well that all of them are numbers.
5:40:49
예를 들어, 8 대신에 월의 이름을 추출하고 싶습니다.
How about we would like to extract the name of the month. So instead of eight, I would like to get the name of the month like August.
5:40:56
20 대신에 요일 이름을 가져오고 싶습니다.
Or instead of the 20, I would like to get the day name. Like here in this example, it can be Wednesday.
5:41:02
부분의 이름을 얻으려면 날짜 이름 함수를 사용해야 합니다.
So in order to get the name of the parts, we have to use the function date name.
5:41:07
예를 들어, 월 부분을 사용하여 날짜 이름 함수를 사용하면 8을 얻지 못합니다.
So for example, if you use the function date name using the part month, you will not get eight in the output.
5:41:12
8월이라는 월의 전체 이름을 얻을 것입니다.
You will get the full name of the month, August. So as you can see, we are getting a string, a full name.
5:41:18
요일에 대해 날짜 이름을 사용하면 20을 얻지 못합니다.
And as well, the same thing, if you use date name for the weekday, you will not get 20 like the day function.
5:41:25
요일의 이름인 수요일을 얻습니다. 그리고 여기서 출력은 문자열입니다. 보시다시피 매우 간단합니다.
You will get the name of the day, Wednesday. And as well here, the output is string. So as you can see, it's very simple.
5:41:30
부품의 이름을 얻기 위해 날짜 이름을 사용하고 있습니다. 그리고 여기서 출력의 데이터 유형은 문자열입니다.
We are using the date name in order to get the name of the parts. And the data type of the output here is a string.
5:41:37
정수가 아닙니다. 보시다시피, 우리는 모두 같은 작업을 수행하는 다양한 유형의 함수가 있습니다.
It is not an integer. So as you can see here, we have different types of functions that all of them are doing the same job.
5:41:44
하나의 날짜에서 부품을 추출하고 있습니다.
We are extracting parts from one date.
5:41:47
자, 이제 데이터 이름 구문을 확인하면 날짜 부분과 동일해질 것입니다.
OK, so now by checking the data name syntax, it's going to be identical to the date part.
5:41:53
우리는 단지 함수 이름을 바꾸고 있습니다. 나에게는 부품과 날짜를 정의해야 합니다.
So we are just switching the function name. It needs for me to define the part and as well the dates.
5:41:59
출력에서 다른 데이터 유형을 얻고 있다는 점이 유일한 차이입니다. 여기서는 정수 대신 문자열을 얻고 있습니다. 알겠습니다.
The only difference is that we are getting different data type at the output. So here we are getting a string instead of integer. All right.
5:42:05
자, 이제 날짜 이름을 확인해 보겠습니다. 날짜 부분과 매우 유사합니다. 이렇게 될 것입니다. 생성 시간으로도 작업할 것입니다.
So now let's check the date name. It is very similar to the date part. So we're going to have it like this. We're going to work as well with the creation time.
5:42:13
우리는 날짜 이름이라고 말할 것입니다. 그리고 그 후에 부품을 정의해야 합니다. 예를 들어, 월로 가보겠습니다.
So we're going to say date name. And then after that, we have to define the parts. So let's go, for example, with the month.
5:42:19
그리고 우리의 필드는, 평소와 같이, 생성 시간입니다. 이렇게 월 날짜 이름이라고 부르겠습니다.
And our field is, as usual, the creation time. And let's call it month date name like this.
5:42:28
그게 다입니다. 이제 실행해 보겠습니다. 여기로 가면
so that's it let's go and execute it now if you go
5:42:31
출력에서 우리는 월을 볼 수 있지만 이번에는
to the output over here you can see we have the month but this time
5:42:34
숫자가 아니라 월의 전체 이름을 가지고 있습니다.
we don't have numbers we have the full name of the month
5:42:37
그래서 우리는 1 대신 1월, 2월, 3월을 가지고 있습니다.
so we have january february march instead of having one
5:42:40
2, 3. 이것이 날짜 이름과 날짜 부분 간의 큰 차이입니다.
two three so this is the big difference between the date
5:42:44
날짜 부분에서는 숫자를 얻고 날짜 이름에서는 부품의 이름을 얻습니다. 그래서 같은 작업을 해보겠습니다.
name and date part date part you get numbers date name
5:42:47
부품의 이름을 얻습니다. 그래서 같은 작업을 해보겠습니다.
you get the name of the part so let's do the same thing
5:42:50
날짜에 대해 우리는 이름을 얻고 싶습니다.
for the day we would like to get the name of
5:42:53
날짜의 전체 이름을 얻기 위해 우리는 날짜로 갈 수 없습니다.
the day so i'm just duplicating it but now in order to
5:42:56
우리는 주의 날을 부품으로 사용할 것입니다.
get the full name of the day we cannot go with the day we're
5:42:59
그게 다입니다. 나는 그것을 주말이라고 부를 것입니다.
gonna go with the week day as a part so
5:43:02
이제 실행해 보겠습니다. 출력에서 우리는
that's it i will call it weekday so
5:43:06
여기 주말이라는 새로운 열이 있고 그 안에
let's execute it now as you can see in the output we have
5:43:09
여기 새로운 열이 있습니다. 이름은 weekday이며 그 안에
here a new column called weekday and inside it we have the
5:43:12
숫자 대신 요일의 이름이 있습니다. 그래서 여기 수요일, 일요일, 금요일 등이 있습니다. 요일의 전체 이름은 물론 요일과 함께 갑니다. 그걸 해보러 가봅시다.
name of the day instead of a number so here we have wednesday sunday friday and so on so the full name of the day go of course with the day let's go and try that out
5:43:24
그래서 이것은 월의 날이고 물론
so this is the day of the month and of course the
5:43:27
월의 날은 이름이 없고 SQL은 물론
day of the month has no name and sql of course can return
5:43:31
숫자를 다시 볼 수 있으니 1, 5, 10, 20 그리고
the numbers again so you can see 1 5 10 20 and
5:43:34
계속해서 여전히 날짜의 날과
so on but still there is a difference between the day from
5:43:37
날짜 부분에서의 날 이름과의 차이가 있습니다. 날짜 부분에서는 정수를 얻고 있으니, 이 정보를 새 테이블에 저장하면 정수로 저장됩니다.
the day name and the day from the date parts in the date parts we are getting integers so if you store this information in a new table it's going to be stored as an integer
5:43:47
하지만 날짜 이름에서 얻는 날은
but in the day that you are getting from the date name it
5:43:50
숫자이지만 여전히 문자열로 저장될 수 있습니다.
is a number but still it can be stored as a string
5:43:53
값이므로 그 숫자의 데이터 유형은
value so the data type of those numbers is a
5:43:57
문자열이고 날짜 부분에서의 날의 데이터 유형은
string and the data types of the day from the date part
5:44:00
정수이며 예를 들어 추출하면 같은 일이 발생할 수 있습니다.
is an integer and the same thing can happen if you extract for example
5:44:03
연도를 추출하면 연도의 전체 텍스트가 없는 것입니다.
a year so you don't have like a full text of the year
5:44:06
연도를 추출하면 연도의 전체 텍스트가 없는 것입니다.
so let me just do it like this so
5:44:10
그래서 이렇게 해보겠습니다.
if we say a year you will not get the
5:44:13
연도를 말하면 연도의 이름을 얻지 못하고 여전히 숫자와 자릿수를 얻습니다.
name of the year you're still getting the numbers the digits
5:44:16
하지만 여기 데이터 유형은 문자열입니다. 그래서 이것이
but the data type here is a string so that's it this
5:44:19
날짜 이름과 날짜 부분의 차이입니다.
is the difference between the date name and the date parts for the
5:44:22
월과 주중에 대해 다른 것들에 대한 전체 이름을 얻을 수 있습니다.
month and weekday you will get the full name for the other
5:44:26
숫자를 얻을 수 있지만 문자열 데이터 유형으로
stuff you will get numbers but with the string data type
5:44:29
날짜 이름에 대한 가장 중요한 것은
so the most important thing about the date name is to present
5:44:32
읽기 쉽고 사람에게 읽을 수 있는 정보를 제공하는 것입니다.
easy to read and human readable informations
5:44:35
사용자에게 제공하므로 판매 보고서를 작성한다고 상상해 보세요.
to the users so imagine you are building a report called sales by
5:44:38
월별로 사용자가 숫자로서의 결과를 보여줍니다.
month and then you show to the user the muscles as numbers one
5:44:41
하나, 둘, 셋, 열둘까지. 물론 괜찮지만
two three until twelve this is of course okay but it
5:44:45
이 정보를 전체 텍스트로 제공하면 훨씬 더 좋습니다.
is way more nicer if you present those informations as
5:44:48
그래서 날짜 이름을 사용하여 보여줍니다.
a full text so you go with the date name in order to show instead
5:44:51
1월, 2월, 3월의 전체 이름을 보여주는 것
of one you show january february march and
5:44:54
전체 이름이 훨씬 더 보기 좋을 것입니다.
the full name of the month and this is gonna look way nicer in
5:44:57
사용자를 위한 보고서의 핵심 사용 사례입니다.
reporting for the users so this is the core use case of
5:45:00
날짜 이름이므로
the date name so
5:45:05
날짜 트렁크가 무엇인지 잘라낼 것입니다.
what is date trunk date trunk gonna go and truncate
5:45:09
특정 부분으로 날짜를 잘라내므로 이해해 봅시다.
the date to a specific part so let's understand
5:45:12
이것이 의미하는 바를 확인해 보겠습니다. 날짜 트렁크의 구문은 날짜 부분과 날짜 이름과 정확히 동일합니다. 따라서 추출하려는 부분과 날짜를 정의해야 합니다.
what this means okay now let's check the syntax of the date trunk it's going to be exactly the same like date part and date name so you have to define the part and the date that you want to extract apart from it.
5:45:24
여기서 유일하게 다른 점은 다른 함수 이름을 제공하고 있다는 것입니다.
So the only thing that is different here, we are giving different function name.
5:45:28
보시다시피, 세 개의 함수가 같은 구조를 가지고 있지만, 추출하려는 부분(예: 월, 일, 주, 시간, 분 등)을 제공해야 합니다.
So as you can see, although three functions, like having the same structure, you have to provide which part you want to extract like a month, day, week, hour, minutes, and so on.
5:45:38
그리고 추출하려는 날짜 또는 날짜와 시간입니다.
And the date or date and time that you want to extract apart from it.
5:45:43
물론, 날짜 랭크를 사용하면 출력 날짜 또는 날짜 시간을 얻습니다.
And of course, with the date rank, we are getting at the output date or date time.
5:45:47
좋습니다. 이제 날짜 랭크가 정확히 어떻게 작동하는지 이해해 봅시다. 다음 날짜 시간이 있습니다.
Okay, so now let's understand exactly how the date rank works. We have the following date time.
5:45:52
우리가 배운 대로, 우리는 연도에서 시작하여 가장 높은 계층 구조를 가지고 있습니다.
And as we learned, we have like a hierarchy where we start with the highest from the year.
5:45:56
그 다음으로 월, 일, 시간, 분, 초로 이동합니다. 이 정보를 보면 매우 정확합니다.
Then we move to the month, day, hours, minutes and seconds. And by looking to this information, it is very precise.
5:46:03
이 정보에 대한 정확한 초를 알고 있습니다, 맞죠? 그래서 여기 세부 사항의 수준이 매우 높습니다.
We know exact second for this information, right? So the level of details here is very high.
5:46:09
이 사건의 초를 알고 있습니다. 이제 날짜 랭크를 사용하면 이 정보의 세부 사항 수준을 변경할 수 있습니다.
We know the seconds of this events. So now the date rank can allow us to change this level of details of this information
5:46:17
세부 사항의 수준을 지정하여. 예를 들어, 날짜 트렁크 분을 말해 봅시다.
by specifying the level of details. Let's take for example if we say the day trunk minutes.
5:46:22
즉, 우리는 분 수준에만 관심이 있고 초에는 관심이 없다고 말하고 있습니다.
So we are saying we are interested only at the minutes level we are not interested with the seconds.
5:46:27
그렇다면 연도와 분 사이의 모든 것이 유지될 것입니다.
So what can happen everything between the year and the minutes gonna be kept.
5:46:32
즉, 모든 정보는 변경되지 않지만 초만 리셋됩니다.
That means all those information will not be changed but only the seconds gonna be resetted.
5:46:38
우리는 더 이상 초에 관심이 없습니다. 이것은 우리에게 매우 세부적입니다.
We are not interested anymore with the seconds this is very detailed for us.
5:46:42
그래서 초를 0으로 리셋할 것입니다.
So it's gonna go and reset the seconds to zero
5:46:46
0, 최소 수준은
zero so we are saying the minimum level is the
5:46:49
분이며 이전의 어떤 것도 관심이 없습니다.
minutes and we are not interested anything like before
5:46:52
초를 말하자면, 이제 우리는 분이 있다고 말합니다.
it the seconds let's say now we say you know what the minutes is
5:46:55
매우 상세하게 시간을 기준으로 하고 싶습니다.
very detailed i would like to be at the hours level so
5:46:58
우리는 하루의 기준 시간을 지정합니다.
we specify for the day trunk hour so here things
5:47:01
변경되었습니다. 이제 연도 사이의 정보를 유지할 것입니다.
changed we're gonna keep the informations now between the year
5:47:05
그리고 시간 이후의 모든 것은 초기화될 것입니다.
and the hours and anything after that's gonna be resetted
5:47:08
이제 분과 초가
so now minutes and seconds gonna be
5:47:11
리셋 범위 내에 있으며 SQL이 초기화됩니다.
in the range of the resets and sql gonna go i reset the
5:47:14
55에서 00으로 초기화됩니다. 이제 수준이
55 to zero zero so now the level
5:47:18
조금 낮아졌습니다. 이제 우리는
of details is a little bit lower now we know
5:47:21
시간까지의 정보만 알고 있으며 우리는
only the informations until the hours and we are not
5:47:24
분과 초에 관심이 없으며 이미 알게 되셨을 것입니다.
interested about the minutes and the seconds and i think you already get
5:47:27
날짜 기준일이 무엇인지 말하면
it if you say date trunk day what's
5:47:30
연도와 날짜 사이의 모든 것을 유지하고 전체 시간이 초기화됩니다.
gonna happen is gonna keep everything between year and day and the whole time gonna be resets so the hours minutes and seconds
5:47:39
모든 정보가 00으로 초기화됩니다.
all those informations gonna reset to zero zero
5:47:42
이것을 보면 우리는
so now by looking to this we don't know anything about the
5:47:45
시간에 대한 정보는 알지 못하며
time we know only informations about the dates and now we
5:47:48
나는 월 수준에서 분석을 하고 있습니다.
can go one more step and we say you know what i'm not interested about
5:47:51
여기에서 유지되는 것은 연도와
the days i'm doing analyzes on the month level so
5:47:54
월의 두 가지 정보뿐입니다.
what is here kept is only two informations year and
5:47:57
그 아래의 모든 것은 날짜입니다.
month and everything below that the day
5:48:01
시간은 초기화될 수 있지만 이번에는 SQL이 날짜를 00으로 초기화하지 않습니다.
and the time can be resetted but this time SQL will not reset the day to zero zero because there is no day called
5:48:08
항상 첫 번째 날짜로 시작하므로 초기화할 수 있습니다.
00 it start always with the first date so it can reset
5:48:11
01로 초기화할 수 있으며 날짜 부분과 날짜가
to 01 so the date parts and the dates
5:48:14
00으로 초기화할 수 있습니다. 이제 우리는
can reset to 01 and the date parts in the time
5:48:17
월 수준에 있으며 마지막 단계로 이동할 수 있습니다.
can reset to 00 so now we are at
5:48:20
나는 오직 연도에만 관심이 있으며
the level of the month now you can go to the last step and you say you
5:48:24
나는 오직 연도에만 관심이 있고
know what i'm interested only on the years and i'm doing only
5:48:27
이 수준에서 분석을 하고 있습니다.
analysis at this level at the highest level so you can go
5:48:30
우리는 연도만 유지하고 그 이하의 모든 것은
and say date trunk year and now what's gonna happen is we're gonna keep only the year and everything below that can be
5:48:37
리셋됩니다. 그래서
resetted so between month and the seconds everything
5:48:40
유지되는 유일한 값은 연도입니다.
in a reset so here's skill gonna reset as well the august 201
5:48:44
모든 것이 리셋되므로 이것은 첫 번째입니다.
so the only value that is kept is the year
5:48:47
1월이고 시간은 완전히 리셋되었습니다.
and everything else is resetted so this is the first of
5:48:50
우리는 연도에 대한 정보만 알고
january and the time is completely resetted so now we are
5:48:53
다른 부분은 신경 쓰지 않습니다. 날짜 트렁크는
at the lowest level of details we know only information about the year and we don't care about any other parts so as you can see the date trunk here is not really extracting a part here the trunk is like
5:49:05
리셋하는 것입니다.
resetting stuff so we are navigating through
5:49:08
데이터와 시간의 계층을 탐색하고 있습니다.
the hierarchy of the data and time and we are controlling
5:49:11
어느 수준에서 분석을 하고 있는지
at which level we are doing the analysis so as you can see at
5:49:14
이해하면 그렇게 복잡하지 않습니다.
the end it's not very complicated once you understand how it works and
5:49:17
분석에 매우 유용합니다.
it is very useful in analysis so this is how the date rank
5:49:21
날짜 순위와 생성 시간에 대한 몇 가지 예를 들어보겠습니다.
works in sql okay let's have a few examples about the date
5:49:24
생성 시간의 수준은 초입니다.
rank together with the creation time so as you can see the creation time the level of it is the seconds so we have seconds
5:49:30
분으로 이동하고 싶습니다.
information with the creation time now i would like to move
5:49:33
이 날짜 트렁크를 잘라내겠습니다.
it to the minutes so let's go and do this date
5:49:37
생성 시간의 분 수준에서 잘라내겠습니다.
trunk and we're gonna say let's
5:49:40
시간을 분으로 부르겠습니다.
truncate at the minutes level for the creation
5:49:43
날짜 트렁크를 잘라내겠습니다.
time so let's call it minutes
5:49:46
이제 실행해 보겠습니다.
date trunk so let's
5:49:50
초가 완전히 리셋되었습니다.
go and execute it now if you go and check the output over here and compare it to the creation time you can see here we have zeros at the seconds so as you can
5:49:59
이제 생성 시간 안의 시간 정보에 관심이 없습니다.
we have the seconds completely resetted compared to the creation time.
5:50:03
날짜만 얻고 싶습니다.
Now, let's say that I'm not interested in the time information inside the creation time. I would like only to get the dates.
5:50:09
그래서 그렇게 하려면, 우리는 날짜 트렁크를 사용하여 하루 수준으로 리셋할 수 있습니다.
So in order to do that, we can use the date trunk where we reset to the level of the day.
5:50:15
그럼 이제 복제해 보겠습니다. 여기 두고, 분 대신 하루로 해봅시다.
So let's go and duplicate it. I'm going to put it over here. And instead of minutes, let's say we have a day.
5:50:22
그래서 우리는 연도, 월, 일만 있고 나머지는 모두 0으로 리셋되었습니다.
And let's go and check the output. Now, if you go and check the result over here, you can see all the time informations are reset to zeros and we have here only information about that date.
5:50:32
물론 우리는 최대한으로 가서 연도만 필요하다고 말할 수 있습니다.
So we have year, month and day and everything else is reset to zero.
5:50:37
우리는 날짜 문자열을 가져와서 연도라고 부를 것입니다.
Now of course we can go to the maximum where we say I just need the year. So I don't need anything else. So let's try that out.
5:50:44
이제 실행해 보겠습니다. 여기 출력 결과를 확인하면 연도 외에는 모두 리셋된 것을 볼 수 있습니다.
We're going to take date strung and say year, year and let's call it year.
5:50:50
우리는 연도 정보만 가지고 있고 나머지는 1월 1일로 리셋되었으며 시간도 리셋되었습니다.
So let's go and execute it. Now, if you check the output over here, you can see that everything is resetted beside the year.
5:50:57
보시다시피, 날짜 트렁크의 출력은 항상 날짜 시간으로 제공되며, 우리는 원하는 수준에서 잘라낼 수 있습니다.
So we have only the year information, but everything else is resetted to the 1st of January and the time is as well as resetted.
5:51:05
좋습니다. 이제 데이터 트렁크가 데이터 분석에 놀라운 기능인 이유를 확인해 보겠습니다.
So as you can see, the output of the day trunk is always as a daytime and it helps us as well to navigate through the hierarchy of the daytime and we can truncate at the level that we want.
5:51:15
좋습니다. 이제 이 예제를 들어 creation을 선택하겠습니다.
All right. So now we're going to check why data trunk is amazing function for data analysis.
5:51:21
시간과 우리는
So let's have this example we are saying select creation
5:51:25
시간과 우리는
time and we
5:51:28
우리의 판매 주문 테이블에서 생성 시간을 기준으로 주문 수를 세고 싶으며, 데이터를 생성 시간별로 그룹화하기 위해 그룹 바이를 사용할 수 있습니다.
want to count the number of orders based on the creation time from our table sales orders and we can use the group by in order to group the data by the creation time.
5:51:39
그러니 가서 실행해 보겠습니다. 이제 보시다시피 우리는 어디에서나 하나를 얻을 것입니다. 생성 시간의 세부 수준이 매우 높기 때문입니다. 그 이유는 여기에 초가 있기 때문입니다.
So let's go and excuse it. Now as you can see we're going to get one everywhere because the level of details that granularity of the creation time is very high and that's because here we have the seconds
5:51:50
그리고 우리의 데이터가 작기 때문에 같은 초에 두 개의 주문을 얻지 않을 것입니다.
and since our data is small we will not get like two orders
5:51:53
데이터 분석에서는 빠르게
at the same seconds now in data analytics you would like quickly
5:51:56
다른 세분성에서 데이터를 집계하고 싶습니다. 예를 들어
to aggregate the data at different granularity like for
5:51:59
월 단위로 집계할 수 있습니다. 그래서 매우
example at the month level so you can do that very
5:52:02
빠르게 날짜 트렁크를 사용하여 할 수 있습니다.
quickly using the date trunk and
5:52:05
당신은 '월 단위로 유지하자'고 말하고, '생성'이라고 부릅니다.
you say you know what let's stay at the month and let's
5:52:09
그리고 그룹 파이에 대해서도 같은 작업을 할 것입니다. 그러니 가서 실행해 보겠습니다.
call it creation and we're gonna have the same
5:52:12
이제 출력에서 보시다시피 우리는 단지 세 개의 행만 있습니다. 우리는
thing for the group pie so let's go and execute it so
5:52:15
10개의 행을 가지고 있지 않으며, 그 이유는 우리가 세 개의 월이 있기 때문입니다.
now as you can see at the output we have only three rows we don't have
5:52:18
즉, 우리는 월 단위로 집계했음을 의미합니다.
like 10 rows and that's because we have three months so
5:52:21
대신에
that means we just rolled up to the month level instead of the
5:52:25
초 단위로 월 수준으로 전환했습니다.
seconds and we can see now in the month of january we have four orders february
5:52:29
1월에 주문이 네 개 있습니다. 2월에도 네 개, 3월에는 두 개입니다.
as well four and march we have only two so now we are
5:52:32
이제 우리는 출력의 세부 수준과 세분화에 대해 이야기하고 있습니다.
talking about different level of details in the output and granularity
5:52:35
이제 데이터를 연 단위로 집계해 보겠습니다.
and now you might say let's go and aggregate the data at different level at the year level so you can just change over here the year and execute it and And with that, now we are at the highest level of aggregations.
5:52:46
우리는 연 단위로 집계하고 있습니다. 데이터에는 2025년만 있습니다.
We are at the year level. And since in our data, we have only 2025.
5:52:51
테이블 내의 총 주문 수를 확인해 보겠습니다. 총 10개입니다.
So we will get the total number of orders inside the table. And that is 10. And this is really amazing.
5:52:56
데이터 분석에서는 날짜 내에서 수준을 정의하여 세분화와 집계 수준을 빠르게 변경할 수 있습니다.
In data analytics, you can go and quickly change the granularity and the level of aggregation or details by simply defining the level inside the dates.
5:53:05
이것이 날짜 순위가 놀라운 이유입니다. 분석과 집계를 가능하게 합니다.
So this is why the date rank is amazing. It allows us to do analysis and aggregations by zooming in and zooming out.
5:53:16
이제 마지막 기능에 대해 이야기하겠습니다. 월의 마지막 날을 구하는 것입니다.
Okay, so now we're going to talk about the last function in the part extraction category. We have the end of the month.
5:53:21
이름에서 알 수 있듯이, 월의 마지막 날을 반환합니다.
As the name says, it's going to go and return the last day of a month. So let's see how end of month works.
5:53:28
매우 간단합니다. 2025년 8월 20일을 예로 들어보겠습니다.
This is very simple. So let's take our date, 20th August 2025. If you go now and apply this function to it, what's going to happen?
5:53:36
이 함수는 날짜 정보만 변경합니다. 20일에서 월의 마지막 날로 변경됩니다.
It's going to go and change only the day information. So instead of 20, it's going to go to the last day of the month.
5:53:43
20일을 31일로 변경합니다. 2025년 8월의 마지막 날입니다.
So it's going to go and change the 20 to 31, the last day of the month, August in 2025.
5:53:49
다른 예로 2025년 2월 1일을 살펴보겠습니다.
Let's take another example is the 1st of February, 2025.
5:53:53
월의 마지막 날을 적용하면 1일에서 28일로 변경됩니다.
If you apply the end of the month, it's going to go and change the day from the 1st to 28, the last day of month, February.
5:54:02
보시다시피, 매우 간단합니다. 이미 월의 마지막 날인 예를 들어보겠습니다.
So as you can see, it's very simple. Let's take another example where it is already the last day of the month.
5:54:08
3월 31일이 있습니다. 월의 마지막 날을 적용하면
So we have 31 of March. if you apply the end of the
5:54:11
아무 일도 일어나지 않습니다. 같은 값을 반환합니다.
month here what can happen nothing gonna happen you're
5:54:14
항상 월의 마지막 날의 출력은
gonna get and return the same value so this is how it works
5:54:17
날짜로 나타납니다. 이것이 월의 마지막 날이 작동하는 방식입니다.
and as you can see always the output of the end of the month gonna
5:54:20
매우 간단합니다. 이제 월의 마지막 날 구문에 대해 빠르게 설명하겠습니다.
be as well a date so this is how end of month work
5:54:24
월의 마지막 날은 동일한 구문을 가집니다.
it is very simple all right now quickly about the syntax of
5:54:27
일, 월, 연도를 사용하며, 하나의 매개변수만 받습니다.
the end of the month it's gonna have the exact same syntax
5:54:30
우리의 생성 시간의 월의 마지막 날을 찾아보겠습니다.
like the day month year it accepts only one parameter it is the date so we have to pass here a date in order to find out the end of the month.
5:54:39
이렇게 월의 마지막 날을 찾겠습니다.
So let's go and find the end of the month of our creation time. So end of the month like this.
5:54:46
그리고 우리의 생성 시간을 가져옵시다. 그러니 월의 끝을 봅시다.
And let's have our creation time. So let's see the end of month.
5:54:52
실행해 봅시다. 이제 출력에서 새로운 열, 날짜 열이 보입니다. 그 안에 월의 끝에 대한 값이 있습니다.
Let's go and execute it. Now in the output, you can see we have a new column, a date column. And inside it, we have values about the end of the month.
5:54:59
예를 들어, 여기 1월이 있습니다, 1월, 1월, 등등.
So for example, here we have January, January, January, and so on.
5:55:02
여기서 항상 1월의 끝을 볼 수 있고, 2월과 3월도 마찬가지입니다. 그게 전부입니다.
So you will see always here the end of January and the same thing for February and March. So that's it.
5:55:07
각 날짜의 월의 끝이 필요할 경우 정말 좋은 기능입니다. 아마도 보고서나 분석을 만들고 있을 것입니다.
This is really nice function in case you need the end of the month of each date. Maybe you're creating a report or analysis where you need this information.
5:55:15
그럼, 이제 첫 번째 날짜를 가져오는 방법에 대해 물어볼 수 있습니다. 그런 기능이 있을까요?
And now you might ask me, how about to get the first day of the month? Is there like any function for it?
5:55:20
글쎄요, 없지만 우리가 방금 배운 다른 기능을 사용하여 월의 첫 번째 날짜를 가져오는 방법이 있습니다.
Well, no, but there is a trick in order to get the first day of the month using another function that we just learned.
5:55:26
생각해 보세요, 모든 곳에서 날짜를 하나로 가져오는 방법입니다.
Think about it, how to get the days as one everywhere.
5:55:30
그래서 우리는 1월 1일, 2월 1일, 3월 1일을 가져와야 합니다. 그걸 어떻게 할 수 있을까요?
So we have to get here the first of January, the first of February and the first of March. So how we can do that?
5:55:36
글쎄요, 날짜 트렁크를 사용하여 할 수 있습니다. 어떻게 할 것인지 보여드리겠습니다.
Well, using the date trunk. So let me show you how we're going to do this.
5:55:40
날짜 트렁크를 사용하고 월 수준에서 리셋할 것입니다. 그래서 우리는 날짜가 필요하지 않습니다.
So date trunk and we're going to reset at the level of month. So we don't need the days.
5:55:48
첫 번째로 리셋할 수 있으니, 우리의 필드는
it can reset to the first so our field is
5:55:51
생성 시간이고, 이것이 시작이 될 것입니다.
creation time and this is going to be the start
5:55:55
월의 시작이니, 실행해 봅시다.
of month so let's go and execute
5:55:58
그것을 실행하면 출력에서 월의 시작이 보입니다.
it so now as you can see in the output we have the start of month and
5:56:01
여기서 우리는 모두 1이 보입니다. 왜냐하면 월 수준에서 리셋했기 때문입니다.
you can see we have everywhere here one since we reset at
5:56:04
그것은 우리가 데이터 유형을 변경해야 한다는 것을 의미합니다. 나중에 캐스트 기능을 사용하여 배울 것입니다. 하지만 지금 바로 할 수 있습니다.
the level of month and this is going to give us the first day of the month and now you might say you know what here we have a lot of zeros how to get exactly like the end of the month and that's because the date trunk give us date and time always.
5:56:16
그래서 우리는 캐스트라고 말할 수 있고, 전체를 날짜로 변경하고 싶습니다. 그리고 이제 데이터 유형을 날짜 시간에서 날짜로 변경했습니다.
So that means we have to change the data type and that we're going to learn later using the cast function. But we can go and do it right now.
5:56:23
출력에서 보시다시피, 우리는 날짜 정보만 있습니다. 이제 두 개의 날짜를 얻은 것이 정말 놀랍습니다.
So we can say cast and we want to change the whole thing to date. And now that we change the data type from date time to date.
5:56:30
첫 번째는 월의 시작이고, 두 번째는 월의 끝입니다.
And in the output, as you can see, we have only the date information. So now it's really amazing that you got two dates.
5:56:35
이 정보는 보고서를 생성할 때 유용할 수 있으며, 월의 시작과 끝이 필요합니다.
The first one is the start of the month and the second is the end of the month.
5:56:38
이제 우리는 왜 이러한 부분이 필요한지 질문하는 부분에 도달했습니다.
And those information might be helpful if you are generating reporting and you need to start and the end of the month.
5:56:44
왜 날짜에서 날짜 부분을 추출해야 할까요? 다음 사용 사례를 살펴봅시다.
So now we come to the part where we ask the question, why do we need those parts?
5:56:51
날짜 부분을 추출하는 첫 번째 사용 사례는 데이터 집계 및 보고를 수행하는 것입니다.
Why do we need to extract the date parts from a date? So let's have the following use cases.
5:56:57
때때로 우리는 데이터에 기반한 보고서를 작성하고, 때때로 특정 시간 단위로 데이터를 집계해야 합니다.
The first use case of extracting the part is doing data aggregations and reporting.
5:57:03
때때로 우리는 데이터에 기반하여 보고서를 작성하고 특정 시간 단위로 데이터를 집계해야 합니다.
Sometimes we are building like reports based on our data and sometimes we have to aggregate our data by a specific time unit.
5:57:09
예를 들어, 우리는 연도별 판매를 보여주기 위해 보고서를 작성하고 있습니다.
Like for example, we are building a report in order to show the sales by year.
5:57:14
그래서 우리는 서로 다른 연도가 있고 연도에 따라 데이터를 집계하고 있습니다.
So we have different years and we are aggregating the data based on the year.
5:57:18
또는 분기별로 데이터를 집계하고 싶을 때 더 자세한 내용을 파악하고 싶을 수 있습니다.
Or you want to drill down to more details where you want to aggregate the data by that quarter.
5:57:23
그래서 이 보고서에서는 분기별 판매를 보여주고 있습니다. Q1, 2, 3, 4.
So in this report, we are showing the sales by quarter. Q1, 2, 3, 4.
5:57:28
또는 월별 판매를 보여주는 보고서를 작성하기로 결정하고 그에 따라 데이터를 월별로 집계하기 시작할 수 있습니다.
Or you decide to go in more details where you show the report says sales by month and then you start aggregating your data by the month.
5:57:35
그래서 1월, 2월, 3월 등이 있습니다. 보시다시피, 우리는 이러한 다양한 부분을 사용하여 데이터를 집계할 수 있습니다.
So you have January, February, March, and so on. So as you can see, we can use those different parts in order to aggregate the data based on it.
5:57:43
이러한 다양한 부분은 서로 다른 세부정보로 다양한 분석을 제공할 수 있습니다.
And these different parts can offer us different analyzes with different details.
5:57:47
이제 우리는 다음 작업을 가지고 있으며, 매년 몇 개의 주문이 있었는지를 나타냅니다.
So now we have the following task and it says how many orders were placed each year.
5:57:52
즉, 우리는 데이터를 연도별로 그룹화하고 주문 수를 세어야 합니다. 해결해 봅시다.
So that means we have to group up our data by the year and we have to count the number of orders. Let's go and solve it.
5:57:58
그럼 선택을 진행합시다. 이제 무엇이 필요할까요? 우리는
So let's go with the select. And now what do we need? we need the
5:58:02
주문 날짜가 필요합니다. 이는 언제
order date this is going to indicate when the
5:58:05
주문이 이루어졌는지를 나타냅니다. 그래서 우리는 세어야 합니다.
order is placed so and we have to go and count
5:58:08
주문 수를 세어야 합니다. 그리고 우리 테이블 판매에서
the star so this is going to be number of
5:58:11
주문 수를 세어야 하고 연도별로 그룹화해야 합니다.
orders and from our table sales
5:58:15
주문 날짜별로 그룹화해야 합니다. 그게 전부입니다. 진행합시다.
orders and we have to group up by the
5:58:18
주문 날짜별로 그룹화해야 합니다. 그게 전부입니다. 실행합시다.
order dates so that's it let's go and
5:58:21
실행하면 이제 외부에서 주문 수를 얻고 있습니다.
execute it so now in the outwards we are getting the number of orders
5:58:24
주문 날짜별로 얻고 있습니다. 그래서 우리는
but by the order date so we
5:58:27
아직 완전하지 않습니다. 연도로 가져와야 합니다.
are still not there we have to have it as a year so
5:58:31
전체 날짜 정보가 필요하지 않습니다. 우리는
we don't need the whole date information we need only the
5:58:34
연도 정보만 필요합니다. 그래서 우리는 추출해야 합니다.
year information so that means we have to go and extract
5:58:37
연도 부분을 추출해야 합니다. 그렇게 하기 위해 우리는
the part year in order to do that we can do it
5:58:40
이렇게 할 수 있습니다. 우리는 연도로 진행할 수 있습니다.
like this so we can go with the year and
5:58:43
그렇게 하면 그룹 i에서도 확인할 수 있습니다. 그게 전부입니다.
we have it as well in the group i so that's
5:58:46
가서 실행해 봅시다. 그 결과를 보시면
it let's go and execute it and with that as you can see we got
5:58:49
각 연도의 주문 수를 알 수 있습니다. 우리 데이터에는 2025년만 있으므로
the number of orders for each year and since in our data we have only 2025 we will get only one row so that the task is solved we are now aggregating the data on the
5:58:58
하나의 행만 얻을 수 있습니다. 그래서 작업이 해결되었습니다. 이제
level of the year now let's have another task which is the same but
5:59:01
연도별로 집계하고 있습니다. 이제 같은 작업을 해보겠습니다.
only different parts how many orders were placed each
5:59:05
다른 부분만 다릅니다. 각 월에 몇 개의 주문이 있었는지
month so we have to go and change it to a month it's
5:59:09
변경해야 합니다. 월별로 바꿔야 합니다. 아주 간단합니다.
very simple we're going to use the function month and as well in
5:59:12
함수 month를 사용할 것입니다. 그리고
the group by so let's go and execute it and
5:59:15
그룹화에서 실행해 보겠습니다.
now as you can see in the output we don't have one row now we have three rows
5:59:18
출력에서 보시다시피 이제 한 행이 아니라 세 행이 있습니다.
and that's because we have three months inside our data and for each month we will get the total number of orders so for the january
5:59:26
데이터에 세 달이 있기 때문입니다. 각 달마다 총 주문 수를 얻습니다.
we have four february we have four and march we
5:59:29
1월에는 4개, 2월에는 4개, 3월에는
have two orders now you might say you know what i don't want the monsters
5:59:32
2개의 주문이 있습니다. 이제 당신은 이렇게 말할 수 있습니다.
as a numbers i would like to have the full name of the month so
5:59:35
숫자 대신 월의 전체 이름을 원합니다.
in order to do that we're going to go and use the function date name
5:59:38
그렇게 하려면 함수 date name을 사용해야 합니다.
so let's go and use date name and then we
5:59:41
그래서 date name을 사용하고
have to specify the date part it's going to be the month and
5:59:45
날짜 부분을 지정해야 합니다. 월이 될 것입니다.
the value going to be the order date and we have to have the same thing as well in the group by so let's go and execute it now you can see in the outwards we are getting the full name of the month which is easier to read.
5:59:56
값은 주문 날짜가 될 것이고, 그룹화에서도 동일한 것을 가져야 합니다.
So this is one of the use cases why we need to extract parts.
6:00:00
이제 실행해 보겠습니다. 출력에서 월의 전체 이름을 얻고 있습니다.
from a date in order to aggregate the data on a specific level.
6:00:08
읽기 더 쉬운 형태로.
So now let's have the following task and it says show all orders that were placed during the month of February.
6:00:13
이것은 우리가 부분을 추출해야 하는 이유 중 하나입니다.
So that means we don't need all the orders. We need only a subset of the orders based on the order dates. Now let's go and check the data.
6:00:20
특정 수준에서 데이터를 집계하기 위해 날짜에서.
So select star first from sales orders and let's go and execute it.
6:00:27
이제 다음 작업을 해보겠습니다. 2월에 주문한 모든 주문을 보여주세요.
So now with that, we have our 10 orders. Now, if you check the order date over here, you can see that we have orders in January, February and March.
6:00:34
즉, 모든 주문이 필요하지 않습니다. 주문 날짜를 기준으로 한 부분 집합만 필요합니다.
Now, we are interested only on the orders that were placed in February. So only these subsets.
6:00:40
이제 데이터를 확인해 보겠습니다.
So that means we have now to filter the data based on the month information. So what we're going to do, we're going to have a where clause.
6:00:47
먼저 sales orders에서 star를 선택하고 실행해 보겠습니다.
And now we don't need the whole order date. We need only the part month.
6:00:51
그래서 우리는 월과 주문 날짜를 사용할 것입니다. 그리고 이것은 2와 같습니다.
So we're going to go with the month and order date. And this is going to be equal to two.
6:00:58
출력이 숫자일 수 있으므로 이제 실행해 보겠습니다.
since the output can be in number so let's go and execute
6:01:01
지금 보시다시피 SQL이 데이터를 필터링했습니다.
it now as you can see sql did filter the data and in
6:01:05
출력에는 2월에 주문된 것만 있습니다.
the output we have only the orders were placed in
6:01:08
그래서 이것은 매우 일반적인 사용 사례입니다.
the month of february so this is as well very common use
6:01:11
우리가 부품을 사용하는 이유는 데이터 필터링을 위해서입니다.
case why do we need the parts we use it in
6:01:14
특정 부품의 날짜를 기준으로 데이터를 필터링하기 위해서입니다.
order to filter the data based on specific part
6:01:17
그래서 보시다시피 매우 빠르고 쉽습니다.
of the dates so as you can see it's very quick and easy
6:01:20
여기서 제 추천은 데이터를 필터링할 때 항상 숫자를 사용하는 것입니다.
and here my recommendation is that if you are filtering the data always use the numbers so always use a date function that
6:01:27
정수 검색이 문자나 문자열 검색보다 항상 빠르기 때문입니다.
gives you a number because it's always faster to search for integers instead of searching for a character or for string.
6:01:35
데이터를 검색하거나 필터링하기 위해 날짜 이름 함수를 사용하지 마세요.
So don't use the date name function in order to search or filter for the data.
6:01:38
날짜 부분이나 월, 연도, 일을 사용하는 것이 좋습니다.
It's better to use the date part or month, year and day since you can work with numbers and numbers are always faster to retrieve data and to filter your informations.
6:01:51
이제 많은 함수가 있습니다. 간단히 요약해 보겠습니다.
Okay, so now we have a lot of functions. I would like now to do a quick recap about
6:01:55
결과의 데이터 유형에 대해 배웠습니다.
the data type of their results so as we learned we have
6:01:58
일, 월, 연도, 날짜와 같은 함수입니다.
functions like day month year date
6:02:01
모든 함수의 출력은 정수가 될 것입니다.
parts and the output of all those functions gonna
6:02:05
이제 또 다른 함수가 있습니다.
be integer it's gonna be a number now we have another function
6:02:08
날짜 시간 함수입니다. 이 함수를 사용하면
the date time if you use it the output of this
6:02:11
출력이 문자열이 됩니다. 여기서 이름을 추출하고 있습니다.
function gonna be a string because here we are extracting the name
6:02:14
날짜 부분의 이름을 추출하고 있습니다.
of the date parts and if you go and use the date trunk
6:02:17
날짜 트렁크를 사용하면 항상 날짜 시간이 출력됩니다.
you will get in the output always date time
6:02:20
그래서 날짜와 시간을 모두 얻을 수 있습니다.
too so you are getting both the date and time and the last
6:02:24
배운 마지막 함수는 월의 끝입니다.
function that you learned end of month if you use it in the results
6:02:27
결과에서 날짜 유형을 얻을 것입니다.
you will get the data type dates so this is really important
6:02:30
출력의 데이터 유형을 이해하는 것이 정말 중요합니다.
to understand the data type of the output so that you don't get
6:02:33
예상치 못한 결과를 피하기 위해 출력 데이터 유형을 이해하는 것이 중요합니다.
any unexpected results all right so now you might say you know
6:02:36
많은 함수들이 있으며, 제가 말하는 것처럼 그들은
what those are a lot of functions and like i'm saying they
6:02:39
같은 작업을 수행하고 있습니다. 우리는 날짜의 부분을 추출하고 있습니다.
are doing the same stuff we are extracting the parts of the dates
6:02:42
이제 여러분은 제가 언제 어떤 함수를 사용할지 어떻게 결정하는지 물어볼 수 있습니다.
so now you might ask me how do you decide on when to
6:02:45
이것이 제가 보통 하는 방식입니다. 먼저 어떤 부분을 추출할지 스스로에게 묻습니다.
use which function this is how i usually do it first i ask myself which part i want to extract if i want to extract a date or a month then i ask ask the question, do I need it as an integer, as a number?
6:02:57
날짜나 월을 추출하고 싶다면, 정수로 필요할지, 숫자로 필요할지 질문합니다.
If it's yes, then I go and use the day function or the month function because they are quick and I will get exactly what I need.
6:03:04
그렇다면 저는 날짜 함수나 월 함수를 사용합니다. 왜냐하면 그들은 빠르고 제가 필요한 것을 정확히 얻을 수 있기 때문입니다.
But now if I need the full name of the month or the day, then I go with the function date name.
6:03:10
하지만 이제 월이나 날짜의 전체 이름이 필요하다면, 날짜 이름 함수를 사용합니다.
Now moving back, if I'm interested on the part year, so here we don't have a year name or something, I'm going to go immediately with the function year.
6:03:18
이제 돌아가서, 제가 연도 부분에 관심이 있다면, 여기에는 연도 이름이 없으므로, 즉시 연도 함수를 사용합니다.
But now let's say that I don't need the day, month or year.
6:03:22
하지만 이제 제가 날짜, 월 또는 연도가 필요하지 않다고 가정해 봅시다.
I'm interested in other parts like the week, the quarter and so on.
6:03:26
저는 주, 분기 등 다른 부분에 관심이 있습니다.
Only for this scenario, I go with the function date part. So this is my decision process.
6:03:31
이 시나리오에 대해서만, 저는 날짜 부분 함수를 사용합니다. 이것이 제 결정 과정입니다.
This is how I decide when to use which SQL function in order to extract the parts of the dates.
6:03:42
이것이 제가 날짜의 부분을 추출하기 위해 어떤 SQL 함수를 사용할지 결정하는 방법입니다.
All right, so now I have prepared for you here a list of all parts that we can use inside those three functions, date part, date name and date trunk.
6:03:50
자, 이제 저는 여러분을 위해 이 세 가지 함수, 날짜 부분, 날짜 이름 및 날짜 트렁크에서 사용할 수 있는 모든 부분의 목록을 준비했습니다.
And you can see in this table the different outputs using those different three functions.
6:03:54
그리고 이 표에서 이 세 가지 함수를 사용하여 다른 출력 결과를 볼 수 있습니다.
So, for example, if you go and use the month with the date part, you will get eight. But for the date name, you will get August.
6:04:00
예를 들어, 날짜 부분과 함께 월을 사용하면 8을 얻습니다. 하지만 날짜 이름을 사용하면 8월을 얻습니다.
And for the date trunk, you will get truncated date time at the level of the month where you reset the days and times.
6:04:07
그리고 날짜 트렁크를 사용하면 월 수준에서 잘린 날짜 시간이 표시됩니다.
So this is a full list of all examples. You can go and check it.
6:04:09
그래서 이것이 모든 예의 전체 목록입니다. 여러분은 확인할 수 있습니다.
And one more thing that I prepared for you in order to practice with all those different parts, I have made one big query with all different parts.
6:04:18
그리고 여러분이 이 다양한 부분으로 연습할 수 있도록 준비한 또 다른 것이 있습니다. 저는 모든 다양한 부분으로 하나의 큰 쿼리를 만들었습니다.
So if you go and download the queries of this chapter, you will find the following files. And let's go now and open all date parts.
6:04:25
그래서 이 장의 쿼리를 다운로드하면 다음 파일을 찾을 수 있습니다. 이제 모든 날짜 부분을 열어 봅시다.
So we're going to go inside it. And here we have a long query.
6:04:30
그래서 우리는 그 안으로 들어갈 것입니다. 그리고 여기 긴 쿼리가 있습니다.
So what you're going to do, we can select everything and copy it. And let's go back to our scale and paste it.
6:04:35
그래서 여러분이 할 일은 모든 것을 선택하고 복사하는 것입니다. 그리고 우리의 스케일로 돌아가서 붙여넣습니다.
So let me just zoom out and then let's go and execute the whole thing.
6:04:41
그래서 제가 그냥 축소하고 전체를 실행하겠습니다.
So now in my code, I have just done a union for each possible part.
6:04:45
그래서 이제 제 코드에서 각 가능한 부분에 대해 유니온을 수행했습니다.
For example, for the year, we have date part, date name and date trunk. And I'm using currently the get dates.
6:04:50
예를 들어, 연도에 대해서는 날짜 부분, 날짜 이름 및 날짜 트렁크가 있습니다.
So we are manipulating this one. And then the output can be presented over here. So you can see it like this.
6:04:55
날짜 이름에 대해 연도를 사용하면 2024를 얻습니다. 날짜 이름도 마찬가지입니다.
So if you use the part year for the date name, you will get the 2024. The same thing for the date name.
6:05:01
이것은 날짜 순위에 대한 것입니다. 이를 통해 SQL에서 사용할 수 있는 모든 부분을 하나의 쿼리로 가질 수 있습니다.
And this is for the date rank. And with that, you have all possible parts that you can use in SQL in one query.
6:05:08
이제 이를 통해 다양한 부분의 출력이 무엇인지 배울 수 있습니다. 알겠죠.
So with that, you can learn what are the outputs for different parts. All right.
6:05:12
이제 우리는 날짜의 부분을 추출하는 방법에 대한 모든 기능을 배웠습니다. 알겠죠.
So with that, we have learned all those functions on how to extract the parts of dates. All right.
6:05:18
두 번째 범주로 넘어가서 SQL에서 날짜 정보를 포맷하고 캐스팅하는 방법을 배울 것입니다.
Moving to the second category, we're going to learn how to do formatting and casting for the date information in SQL.
6:05:24
세 가지 함수를 사용합니다. 이제 포맷과 캐스팅에 대해 깊이 들어가기 전에 날짜 포맷이 무엇인지 이해해 주셨으면 합니다.
using three functions. So now before we deep dive to the formatting and casting, I would like you to understand what is date format.
6:05:35
예제로 돌아가면, 여기 날짜와 시간 정보가 있으며, 연도, 월, 일 등의 구성 요소가 있음을 이해했습니다.
So back to our example, we have here the date and time informations and we understood there is components year, month, day and so on.
6:05:42
이제 날짜 시간을 확인하면 숫자와 문자의 조합이 있습니다.
Now if you check the date time, there is combination of numbers and characters.
6:05:46
예를 들어, 2025는 숫자이지만, 월과 연도 사이에는 마이너스가 있으며, 이것은 문자입니다.
For example, the 2025 is a number, but between the month and the year, there is like a minus between them and this is a character.
6:05:54
이제 이것은 매우 특정한 포맷이며, SQL에서는 이 포맷에 대한 코드가 있습니다.
So now this is a very specific format and in SQL we can have a code for this format.
6:06:00
예를 들어 연도부터 시작해 보겠습니다. 여기 네 자리 숫자가 있으며, 네 개의 y로 표현할 수 있습니다.
So for example let's start with the year. We have here four digits and we can represent it with four y.
6:06:07
y, y, y입니다. 우리는 이러한 문자를 포맷 지정자라고 부릅니다.
So y, y, y. And we call those characters as format specifiers.
6:06:12
이것이 연도를 표현하는 방법입니다. 연도와 월 사이에는 작은 마이너스가 있습니다.
So this is how we represent the year. Then between the year and the month there is like this small minus.
6:06:18
그리고 월은 두 자리이며, 두 개의 큰 M으로 표현할 수 있습니다. 그래서 M, M입니다.
And then the month is two digits and we can represent it with two big M. So M, M.
6:06:24
그리고 월과 일 사이에는 마이너스가 있습니다. 그래서 마이너스도 있습니다. 그리고 일은 두 자리로 표현할 수 있습니다, D, D.
Then between the month and the day, there is a minus. So we have as well minus. And then the day can represented with two digits, D, D.
6:06:31
그리고 날짜와 시간 사이에는 공백이 있습니다. 그리고 날짜부터 시작합니다. 그래서 시간은 큰 H로 시작합니다.
And then we have like a space between the date and time. And then we start with the date. So it starts with the hour, big H and big H.
6:06:38
여기서는 24시간 시스템이 있습니다. 그리고 두 개의 점, 작은 m, 작은 m이 있습니다.
Because here we have the system of 24. And then we have double points, small M, small M.
6:06:43
여기서 포맷은 대소문자를 구분합니다. 그래서 작은 m과 큰 M 사이에는 큰 차이가 있습니다.
So as you can see here, the formats are case sensitive. So there is a big difference between small M and the big M.
6:06:50
작은 m은 분을 나타내고, 큰 M은 월을 나타냅니다.
So a small M indicates for a minute and big M indicates for a month.
6:06:55
여기서 대소문자 포맷은 대소문자를 구분합니다. 그래서 두 개의 작은 m은 분을 의미하지만, 두 개의 큰 M은 월을 의미합니다.
So as you can see here, the case format is case sensitive. So two small M means minutes, but two capital M means month.
6:07:03
그런 다음 두 개의 점과 작은 두 개의 S가 있습니다. 그래서 이제 전체 코드를 날짜 포맷이라고 부릅니다.
Then double point and small two S. So now the whole code is called the date format.
6:07:09
이것이 이 값의 날짜 포맷 표현입니다.
So this is the date format representation of this value.
6:07:12
이제 세계에는 날짜를 표현하는 다양한 방법이 있습니다.
Now in the world, there are different representations on how to represent a date.
6:07:17
예를 들어 SQL에서는 국제 표준 ISO 6801이 있습니다. 그리고 날짜 포맷은 우리가 배운 것과 같습니다.
So for example, in SQL, we have the international standard ISO 6801. And the date format is like we have learned.
6:07:24
먼저 연도로 시작합니다. 연도는 네 자리, 월은 두 자리, 일은 두 자리입니다.
First, it starts with the year. So four digits for the years minus two digits for the month minus two digits for the day.
6:07:31
그래서 연도, 월, 일입니다. 하지만 미국에서는 다른 기준이 있습니다. 그래서 먼저 월부터 시작합니다.
So year, month, day. But in the USA, we have different standards. So first, it starts with the month.
6:07:38
그래서 MM이 있습니다. 그리고 그 다음에는 일이 따라옵니다. 그래서 우리는 일이 있습니다.
So we have MM. And then after that, it is followed with the day. So we have then the day.
6:07:43
그리고 그 다음에는 마지막에 연도가 있습니다. 그래서 이것이 미국에서 사용되는 표준 형식이며 유럽에서는 날짜를 다르게 표현합니다.
And after that, at the end, we have the year. So this is the standard format that is used in USA and in Europe we have different representations of the day.
6:07:51
그래서 먼저 작은 것부터 시작합니다. 그래서 일부터 시작하고, 그 다음에 월, 그리고 마지막에 연도입니다.
So it starts first with the small, so it starts with the day, then the month, and then the year.
6:07:57
그래서 이것은 국제 표준과 정확히 반대입니다.
So this is exactly the opposite of the international standards.
6:07:59
그래서 보시다시피 우리는 하나의 표준이 없습니다. 우리는 날짜를 표현하는 다양한 방법이 있습니다.
So as you can see we don't have one standard, we have different ways on how we represent dates.
6:08:04
하지만 SQL에서는 SQL 서버가 국제 표준의 형식을 따릅니다.
But in SQL, the SQL server is following the format of the international standards.
6:08:10
그래서 SQL 서버는 항상 연도 다음에 월로 시작합니다.
So SQL server start always with a year then month
6:08:13
그 다음에 일이 있습니다. 그래서 우리 SQL에서 사용되는 모든 날짜입니다.
then day so all dates that are used in our sql
6:08:16
데이터베이스는 이 형식을 따를 수 있습니다. 알겠죠?
database can be following this format okay
6:08:23
그래서 날짜 형식이 무엇인지 이해한 후 이제 포맷팅과 캐스팅에 대해 이야기해 보겠습니다.
so after we understand what is date format now let's talk about
6:08:26
포맷팅과 캐스팅에서 포맷팅이란 값을 하나에서 다른 것으로 변경하는 것입니다.
formatting and casting so what is formatting is changing
6:08:29
데이터가 어떻게 보이는지를 변경하는 것이므로 예를 들어 날짜가 있습니다.
the format of value from one to another so we are
6:08:32
그래서 국제 표준을 따르며 연도로 시작합니다.
changing how the data looks like so for example we have our date
6:08:35
그 다음에 월, 그리고 일이 있습니다. 이제 우리는 포맷을 변경할 수 있습니다.
so it's following the international standards start with year
6:08:38
함수 포맷을 사용하여 정의할 수 있습니다.
month then day now we can go and change the format using
6:08:42
다른 날짜 형식으로 시작하여 월이 먼저 오고
the function format where we can go and define a
6:08:45
빼기 대신 슬래시가 있고 그 다음에
different date format like it starts with a month and then
6:08:48
일 슬래시 연도입니다. 그래서 자동으로 이렇게 얻을 것입니다.
we have like slash instead of minus and then the
6:08:51
연도는 네 자리가 아니라 두 자리입니다. 그래서 SQL에 제공할 형식을 설정하고 다른 형식으로 갈 수 있습니다.
day slash year so in the auto we're gonna get it like this and
6:08:54
여기서 세 개의 대문자 M이 있고 그 다음에 네 자리 숫자가 있습니다.
even the years is only two digits not four so here we are providing for sql the format that we would like to see the data with or you can go with other format
6:09:02
연도와 그 사이에는 공백이 있습니다. 그래서 출력에서
where you have three big m and then four digits for the
6:09:05
월 이름의 약어를 얻을 것이고 그 다음에
year and between them is just space so in the output you
6:09:08
공백과 연도가 있습니다. 그래서 이것은 데이터를 포맷하는 한 가지 방법입니다.
will get abbreviation of the month name and then
6:09:11
공백과 연도가 있습니다. 그래서 이것은 데이터를 포맷하는 한 가지 방법입니다.
space and the year so this is one way on how to format data
6:09:14
그러나 스케일에는 데이터를 포맷하는 데 도움이 되는 또 다른 기능이 있습니다.
but in the scale there is another function that help us to format
6:09:17
데이터를 변환하는 것이며, 여기서는 제공하지 않습니다.
data and that is convert so here we provide not
6:09:20
형식 자체를 제공하며 스타일 번호를 제공합니다. 예를 들어 스타일 번호 6은 이렇게 표시할 수 있습니다.
the format itself we provide style number so for example the style number six so it can show it like this day space and after that we have the
6:09:29
그 후에 월의 약어와 두 자리 숫자가 나옵니다.
abbreviation name of the month and then two digits
6:09:32
연도 또는 다른 스타일인 112를 사용하면
of the year or if you use another style the 112 then
6:09:35
연도, 월, 일이 구분 없이 표시됩니다.
you will get the year month day without any separation
6:09:39
그들 사이에 있으며, 물론 날짜와 시간뿐만 아니라 스타일을 지정할 수 있습니다.
between them and of course not only the date and time we can style we
6:09:42
숫자도 시작할 수 있으며, 여기서 형식 함수를 사용할 수 있습니다.
can start as well numbers and here we can use the function format in
6:09:45
숫자의 형식을 변경하기 위해서입니다. n개의 숫자 값을 사용하면
order to change the format of the number so if you are using the format
6:09:48
값이 쉼표로 구분됩니다. 또는 통화를 위해 c를 사용하면
of n numeric values then the value is going to be separated
6:09:51
달러 기호를 얻거나 p를 사용하면
with comma or if you use c for the currency then
6:09:54
백분율을 얻을 수 있으며, 마지막에 백분율 기호가 있습니다.
you will get the dollar sign or if you go and use p then
6:09:58
백분율을 얻을 수 있으며, 마지막에 백분율 기호가 있습니다.
you will get the percentage and at the end you have the percentage character so
6:10:01
우리가 숫자의 형식도 변경할 수 있다는 것을 알 수 있습니다.
as you can see we can as well change the format of the numbers not
6:10:04
날짜뿐만 아니라, 이것이 우리가 포맷팅이라고 말하는 것입니다.
only the dates so this is what we mean by formatting we are
6:10:07
값의 모양을 변경하는 것입니다. 이제
just changing how the value looks like now in the
6:10:10
다른 한편으로 캐스팅은
other hand the casting the casting can go and change
6:10:14
데이터 유형을 하나에서 다른 것으로 변경할 수 있습니다.
the data type from one to another so for example if we have the value one two three as a string we can go and convert it
6:10:22
예를 들어, 문자열로 된 값 123을 가지고 있다면, 변환할 수 있습니다.
from the data type string to an integer so in the
6:10:25
문자열에서 정수로 데이터 유형을 변경할 수 있습니다.
output we'll get as well one two three but as a number or
6:10:28
출력에서는 더 이상 날짜가 아닙니다.
we can go and change the data type from dates to a
6:10:31
문자열 값이 됩니다. 우리는 변경할 수 있습니다.
string so in the output it is not anymore dates
6:10:34
문자열에서 날짜로 데이터 유형을 변경할 수 있습니다.
it is a string value all the way around we can change
6:10:37
하나에서 다른 것으로 데이터 유형을 변경할 수 있습니다.
the data type from a string to a date so
6:10:40
하나에서 다른 것으로 데이터 유형을 변경할 수 있습니다.
as you can see we can change the data type from one to another
6:10:44
우리는 두 가지 함수를 사용하여 데이터 유형을 변경할 수 있습니다.
and we can use that using two functions the
6:10:47
첫 번째 함수는 가장 유명한 캐스트 함수입니다.
first one is and the most famous one is cast function
6:10:50
SQL 서버에서는 변환 함수를 사용할 수도 있습니다. 이것이 우리가 캐스팅이라고 부르는 것입니다.
or in sql server we can use as well the convert function in order to change the data type so this is what we mean with casting changing the data type from one to another
6:11:04
좋습니다. 첫 번째 함수인 포맷을 시작해 보겠습니다. 포맷이란 무엇인가요?
all right so let's start with the first function the format so what is format
6:11:07
이름에서 알 수 있듯이 날짜나 시간 값을 포맷합니다. 즉, 날짜와 시간의 모양을 변경하는 것입니다.
as the name suggests it formats a date or time value so it's like we are changing how the date and time looks
6:11:15
좋습니다. 포맷의 구문을 확인해 보겠습니다. 여기서는 두 개의 매개변수를 받고 세 번째는 선택 사항입니다.
Okay, so let's check the syntax of the format and here it accepts two parameters and the third one is optional.
6:11:21
첫 번째로 값을 제공해야 합니다. 날짜나 숫자가 될 수 있습니다. 두 번째로 포맷을 제공해야 합니다.
So the first one we have to provide a value. It could be a date or a number and the second one we have to provide the format.
6:11:27
여기서는 이 값의 새로운 모양, 새로운 포맷을 지정하고 있습니다. 이제 세 번째는 선택 사항입니다.
So here we are specifying the new look the new format for this value. Now the third one it is optional one.
6:11:33
문화입니다. 문화란 날짜, 시간 또는 숫자 값을 보여주는 것을 의미합니다.
It is the culture. Culture means show me the value whether it's date time or number.
6:11:38
특정 국가나 지역의 스타일로 이 값을 보여주세요.
Show me this value in the style of a specific country or region.
6:11:43
각 국가, 각 지역마다 다른 포맷이 있습니다. 여기서 특정 지역 포맷으로 변경할 수 있습니다.
So each country, each region has different formats. So here we can go and change it to a specific region format.
6:11:50
하지만 말씀드린 대로 선택 사항입니다. 예를 들어 보겠습니다. 여기서 주문 날짜를 다음 포맷으로 포맷하라고 말하고 있습니다.
But as I said, it is optional. Let's have an example. So here we are saying, go and format the order date using the following format.
6:11:57
DD, 일, 슬래시, 월, 슬래시, 연도입니다.
So DD, day, then slash, then we have the month, then slash, then the year.
6:12:02
SQL은 이 새로운 포맷으로 포맷할 것입니다. 보시다시피, 선택 사항이므로 문화를 지정하지 않았습니다.
So SQL is going to go and format this with this new format. And as you can see, we didn't specify any culture since it's optional.
6:12:08
또 다른 옵션을 보겠습니다. 주문 날짜를 이 포맷으로 포맷하고 싶다고 말할 수 있습니다. 일본 스타일을 추가하고 싶습니다.
Let's see another option where we can say, you know what? I would like to have the order date formatted with this format, but we would like to go and add the style of Japan.
6:12:16
여기서 일본의 코드나 스타일을 지정하고 있습니다.
So we are specifying here the code or the style of Japan.
6:12:20
물론 날짜에만 사용하는 포맷을 사용할 수 있지만 숫자를 포맷하는 데도 사용할 수 있습니다.
And of course, we can go and use the format that only for the date, but as well for formatting the numbers.
6:12:26
여기서 값을 지정하고 있습니다. 포맷은 D이며, 문화 옵션도 활성화했습니다.
So here we are specifying the value. The format is D and as well, we have activated the culture option.
6:12:31
프랑스 스타일을 사용하고 있습니다. 이것이 포맷의 구문입니다. 이 옵션을 사용하는 것은 그리 일반적이지 않습니다.
We are using the style of France. So this is the syntax of the format. Using this option is not really common.
6:12:38
이 포맷이나 누군가가 사용하는 것을 거의 보지 못했습니다.
So I rarely see this format or someone using it.
6:12:41
첫 번째 예는 문화가 기본값으로 설정되거나 문화를 전혀 사용하지 않는 프로젝트에서 가장 많이 사용됩니다.
So the first example is the most used one in the projects where we have the culture as default or we are not using the culture at all.
6:12:49
물론 아무것도 지정하지 않으면 기본 문화인 EN-US를 사용합니다.
And of course, if you don't specify anything, it's going to go and use the default culture, which is E N U S.
6:12:55
이것이 포맷의 구문에 대한 모든 것입니다. 좋습니다. 이제 포맷을 사용하여 몇 가지 예를 들어 보겠습니다.
So this is all about the syntax of the format. All right. So now let's have a few examples using the format.
6:13:00
생성 시간을 포맷할 것입니다. 이렇게 포맷할 것입니다.
So we're going to go and format the creation time. So we're going to do it like this format.
6:13:05
우리가 포맷하는 것은 생성 시간입니다. 이제 원하는 대로 지정할 수 있습니다.
And what we are formatting, we are formatting the creation time. And now you can go and define any specified you want.
6:13:12
예를 들어, DD와 같이 해보겠습니다. 그래서 출력을 확인해 보겠습니다.
For example, let's say DD like this. So let's go and check the output.
6:13:18
실행해 보세요. 이제 DD를 사용하면 날짜 정보를 얻을 수 있습니다.
So execute it. Now, if you are using DD, you will get the day information.
6:13:23
이 지정자를 사용하면 날짜에 대한 두 자리 숫자를 얻고 있습니다. 그리고 선행 0도 얻고 있습니다.
So we can see if you are using this specifier, we are getting two digits about the day. So and as well, we are getting the leading zero.
6:13:29
우리는 01, 05를 얻고 있습니다. 이 모든 정보는 날짜 정보입니다. 이제 다른 것을 시도해 보겠습니다.
So we are getting the zero one, zero five. And all those informations are the day information. Now let's go and try something else.
6:13:36
하나의 D를 더 추가해 보겠습니다. 그래서 여기서 3D로 해보겠습니다. 이제 실행해 보겠습니다.
Adding one more D. So let's have it 3D on here as well. So let's go and execute it.
6:13:43
이제 출력을 확인하면 날짜의 이름을 얻고 있습니다. 완전하지는 않지만 날짜의 짧은 이름이나 약어를 얻고 있습니다.
So now if you check the output, we are getting now the name of the day. It is not full. So we are getting like a short name of the day or abbreviated one.
6:13:51
이것은 때때로 캘린더를 만들 때 유용합니다. 하나의 D를 더 추가해 보겠습니다.
So this is sometimes nice if you are creating like a calendar or something. Let's go and add one more D.
6:13:56
우리는 4D를 가질 것입니다. 이제 이 결과를 확인해 보겠습니다.
So we're going to have 4D. And let's go and check the result for this one.
6:14:02
이제 출력에서 날짜의 전체 이름을 얻고 있습니다. 정말 좋습니다. 이제 날짜 형식을 완전히 조정할 수 있습니다.
Now in the output we are getting the full name of the day. So it's really nice. Now we are getting full flexibility on how to format our day.
6:14:10
이제 계속 진행해 보겠습니다. 다른 것을 가져오겠습니다. 모든 것을 복제하겠습니다. 이제 월로 가겠습니다.
Okay so now let's keep playing. Let's get something else. I'm just gonna go and duplicate everything. And I will go with the month now.
6:14:17
이것은 2M, 3M 및 4M입니다.
So this is 2M, 3M and 4M.
6:14:23
이렇게 해보겠습니다. 이제 실행해 보겠습니다. 이제 같은 내용을 얻고 있지만 월에 대한 것입니다.
Let me do it like this. So let's go and execute it. Now as you can see we are getting the same stuff but for the month.
6:14:30
MM을 사용하면 두 자리 숫자를 얻고, 3M을 사용하면 월의 약어를 얻습니다.
So M M we will get the two digits and 3 M we will get the abbreviated name of the month.
6:14:36
M을 사용하면 월의 전체 이름을 얻습니다. 날짜 형식에서 날짜 부분을 추출하는 것과 같습니다.
And for M we will get the full name of the month. So it's like we are extracting the date part from the format.
6:14:43
M을 사용하면 월의 전체 이름을 얻습니다. 이렇게 사용하지는 않습니다. 날짜에 필요한 전체 형식을 작성할 것입니다.
But of course, we don't use it like this. We will go and write the whole format that we need for a date.
6:14:49
예를 들어, 이 형식을 미국 형식으로 변경해 보겠습니다. 그렇게 하려면 여기로 가겠습니다.
So, for example, let's go and change this format to the USA format. So in order to do it, we're going to go over here.
6:14:55
형식을 다시 설정해 보겠습니다. 생성 시간을 설정하겠습니다.
So let's say formats again, the creation time.
6:15:00
이제 미국 형식을 작성할 것입니다. mm이 될 것입니다.
and now we're going write the format of usa so it's gonna be
6:15:03
그 후에 월 다음에 마이너스 기호가 오고, 날짜가 오고, 그 후에 연도가 올 것입니다. 그래서 시간 연도입니다. 그게 전부입니다. 미국이라고 부르겠습니다.
mm then after that then after the month we're gonna have like a minus then day and then after that we're gonna get the year so for time year and that's it let's call it usa
6:15:14
형식이므로 실행해 보겠습니다.
formats so let's go and excuse it and
6:15:17
이제 출력에서 새로운 열이 생겼고 날짜를 볼 수 있습니다.
now you can see in the output we got a new column where we see now the date
6:15:21
정보는 미국 기준으로 시작합니다.
information but as a usa standards so it starts
6:15:24
월 다음에 날짜가 오고, 그 후에 연도가 옵니다.
with the month then the day and then afterward we got
6:15:27
연도이며, 유럽의 표준 형식을 생성하기 위해 같은 작업을 할 수 있습니다.
the year and of course we can do the same thing in order to generate the
6:15:30
유럽의 표준 형식이므로 복제하겠습니다.
standard format of europe so what we're gonna do
6:15:33
그냥 복사할게요. 이제
i'll just duplicate it and now the
6:15:36
형식이 날짜부터 시작한 다음 달로
format of that's gonna start with the day then the month
6:15:40
연도까지 이어집니다. 이제 출력을 확인하면
and then the year so now if you check the output you
6:15:43
일에서 시작하고 그 다음에 월, 그 다음에 연도가 나옵니다. 보시다시피 날짜 형식을 생성 시간에서 새로운 것으로 변경하고 있습니다.
can see it starts with day minus then we have the month then minus the year so as you can see we are changing the format of the date from the creation time to something new.
6:15:52
좋습니다. 이제 다음 작업이 있습니다. 생성 시간을 다음 형식으로 표시하라고 합니다.
All right. So now we have the following task and it says show creation time using the following format.
6:15:58
이제 매우 이상한 형식이 있습니다. 그래서 '일'이라는 단어로 시작합니다.
Now we have a very weird format. So it starts with the word day.
6:16:02
그 후에 요일의 약어와 월의 약어가 있습니다. 이것은 분기 정보이고, 그 다음에 연도가 나옵니다.
Then after that, we have the abbreviation of the day and then abbreviation of the month. This is the quarter information, then the year.
6:16:09
그 후에 시간이 있고, PM인지 AM인지 말할 것입니다.
And after that, we have that time and we're going to say whether it's PM or AM.
6:16:14
조금 이상한 형식입니다. 어디서나 볼 수는 없지만,
So it's a little bit weird format that you don't see it everywhere,
6:16:17
그래도 이런 사용자 정의 형식을 만드는 연습을 하고 싶습니다.
but still we want to practice on how to construct such
6:16:20
단계별로 진행하겠습니다. 첫 번째는
custom formats so let's do it step by step i'm gonna
6:16:23
여기서 새 줄로 이동합니다. 첫 번째는
go over here and a new line so the first one is like
6:16:26
일입니다. 그에 대한 형식은 없습니다. 그냥
day so we don't have any format for that it's just
6:16:30
문자와 같습니다. 이건 모든 형식에 대해 정적일 것입니다.
like characters so this one's gonna be static for
6:16:33
모든 형식에 대해 정적일 것입니다. 그래서 우리가 할 것은
all the formats so what we're gonna do we're gonna say with
6:16:36
문자열로 '일'이라고 말하는 것입니다. 그래서
a string this is the day so let's
6:16:39
실행하겠습니다. 그래서 우리는 모든 곳에서 정적 값을 얻었습니다.
go and execute it so with that we got the static value everywhere
6:16:42
'일'이라는 단어가 있습니다. 그래서 그게 전부입니다.
we have the word day so that's it and
6:16:45
그 후에 공백이 있습니다. 그래서 그 후에 포함하겠습니다.
after that we have a space so i'm gonna go and include it after
6:16:49
문자열의 '일' 뒤에 공백이 있습니다.
the day in the string so we have a day then space
6:16:52
그 후에 요일 이름의 약어가 필요합니다. 그래서 우리가 할 것은
and after that we need the abbreviation of the
6:16:55
먼저 더하기 연산자로 가는 것입니다.
day name so what we're gonna do we're gonna go first with the plus operator
6:16:58
문자열을 연결하기 위해서입니다.
in order to concontinate the strings so
6:17:01
생성을 위한 형식 함수가 필요합니다.
we need the format function for the creation
6:17:04
우리가 필요한 것은 짧은 이름입니다. 그래서 'd'를 세 번 사용합니다. 실행해 보겠습니다.
time and what do we need we need the short name so it's gonna be three times the d let's go and execute it let me
6:17:12
여기 사용자 정의 형식을 말하자면
just say here custom formats so
6:17:15
출력에서 우리는 여기 날짜가 있고 그 후에
now as you can see in the output we have here the day then afterward we
6:17:18
공간이 있고 그 다음은 약어입니다
have space and then the abbreviation of the
6:17:21
날짜의 이름이므로 지금까지 좋아 보입니다
name of the day so it looks so far good now
6:17:24
그 후에 우리는 공간이 필요하고 약어가 필요합니다
after that what do we need we need space and then the abbreviation
6:17:27
월의 약어이므로 우리는 모든 것을 함께 추가할 수 있습니다
of the month so we can go and add all those stuff together
6:17:31
여기 형식으로 두 개의 형식을 만들 필요가 없습니다
with the format here so we don't have to create two formats so
6:17:35
공간과 월의 약어는 3m입니다
space and the abbreviation of the month is 3m
6:17:38
그래서 가서 테스트해 보겠습니다. 좋아요, 이제 보시다시피
so let's go and test it great so now as you can see
6:17:41
우리는 월의 약어도 나란히 얻었습니다
we got the abbreviation of the month as well side
6:17:44
나란히 있으므로 지금까지 이 부분을 다뤘습니다
by side so we so far we have covered this part now
6:17:48
우리는 두 번째 부분으로 이동해야 하므로 여전히 공간이 필요합니다
we have to move to the second part so we still need a space
6:17:51
그리고 q1, q는 정적일 수 있습니다
and then q1 well the q can be static
6:17:54
그래서 우리는 이 형식을 확장할 수 없습니다
so we cannot go and extend this format we have to
6:17:57
새로운 것을 시작해야 하므로 나는 여기서 더하기를 추가하고 새 줄을 추가할 것입니다
start a new one so what i'm gonna do i'm just gonna add a plus here and a new line so what do we need we need first a space between the month
6:18:06
그리고 분기 사이에 공간을 추가해야 합니다
and the quarter so let's go and add space and we need the q as a static value like this let me just
6:18:13
이렇게 이동하고 이제 그 후에 우리는 이것이 필요합니다
move it like this and now after that we need this one like
6:18:16
이것이 맞습니다. 이제 분기 정보를 필요로 하고 우리는 가지고 있지 않습니다
this right so now we need the quarter informations and we don't have
6:18:20
그것을 위한 형식이 없기 때문에 우리는 부분 추출 함수를 사용해야 합니다
format for that that's why we have to go and use the part extraction functions and the one that we're going to use since we are using string i will go with the date name
6:18:29
그래서 분기를 추출하고 있습니다
so quarter and we are extracting from the
6:18:33
생성 시간입니다. 그래서 가서 테스트해 보겠습니다
creation time so let's go and test it so
6:18:36
이제 출력에서 우리는 어디에나 q1이 있는 것을 볼 수 있습니다
now in the output you can see we have everywhere a q1 and that's because
6:18:39
모든 날짜가 q1에 있습니다. 좋아요, 이제 우리는
all of those dates are in q1 all right so now we are
6:18:42
지금까지 형식의 중간 지점에 있습니다
so far halfway in our format so now next
6:18:45
우리가 필요한 것은 공간과 연도 정보, 그리고 시간 정보입니다
what do we need we need like a space and then the year information and then the time information so now in order to go and get space
6:18:52
우리는 매우 간단하게 연결할 것입니다.
we're going to do it very simply concatenate and
6:18:56
이제 우리는 공백을 가질 것이고, 새로운 줄로 넘어갑니다.
we're going to have space now let's go to a new line
6:18:59
연도를 얻기 위해서도 형식을 사용할 것입니다.
and in order to get the year i will go with the format as well
6:19:02
형식이 무엇인지, 우리는 무엇을 가질 것인지.
so format and what do we have we're going to have the
6:19:05
생성 시간을 다시 어떻게 포맷할 것인지.
creation time again so how
6:19:08
우리가 필요한 것은 연도입니다.
are we going to format it now what do we need we need the year so it's
6:19:11
네 번의 y와 그 뒤에 공백과 형성 시간을 가질 것입니다.
going to be four times the y and after that we have like space and then the time of formation we still can't do that inside the format right so we're going to have
6:19:19
여기서 다음으로 우리는 시간을 가질 것입니다.
space here and then next what do we have we have the hours so
6:19:22
hh, 작은 h가 될 것입니다.
it's gonna be hh the small h because here we are talking about
6:19:25
pm과 am, 24시간 시스템이 아닙니다.
the pm and am it's not the 24 hour system
6:19:28
그 후에 우리는 점을 가질 것입니다.
and then after that what do we have the points double points
6:19:32
그 후에 초가 올 것입니다.
then the minutes gonna be small 2m and
6:19:35
이 부분은 여기 있고, 이제 필요한 것은 공백입니다.
then after that the seconds so far this is exactly
6:19:38
pm 식별자가 필요합니다.
this part over here and now what is missing is space and
6:19:42
이제 실행해 보겠습니다. 이제 작동하는 것을 볼 수 있습니다.
the pm the designator so in order to do that we're gonna have a space as well and then small two times tt All right, so we are almost there.
6:19:50
우리는 연도, 공백, 시간, 분, 초 및 공백을 가집니다.
Let's go and execute it. Now you can see it is working.
6:19:53
그 후에 식별자가 있습니다. PM과 AM입니다.
So we have the year, then space, the hours, minutes, seconds and space.
6:20:00
이렇게 SQL에서 형식을 만들어낼 수 있습니다.
Then we have the designator. So this is PM and this is AM, which is correct. So that's it. We are done.
6:20:07
SQL에서 날짜를 포맷하는 것이 정말 재미있습니다.
This is how we can create those crazy formats in SQL using the help of format or maybe date name or maybe some static values like we just added here.
6:20:15
프로젝트에서 자주 사용하는 형식의 사용 사례입니다.
So I think it's really fun formatting the dates in SQL.
6:20:22
부분 추출과 비슷하지만, 보고서에서 날짜를 표현하는 방법에 대한 사용자 정의가 더 많습니다.
Now, one use case for the format that I frequently use in my project is using it to format the date before doing aggregations.
6:20:30
예를 들어, 월별 판매 보고서를 표시할 수 있습니다.
So it's like part extraction, but here we have more customizations on how we represent the date at the reports.
6:20:37
형식을 이렇게 변경한 후, 데이터 집계를 수행하면 월별 판매에 대한 멋진 보고서를 얻을 수 있습니다.
So we can show a report like sales by month, where we display, for example, the date as abbreviation name of the month, Jan, and as well two digits for the year 25.
6:20:46
형식을 사용하여 빠른 집계를 해 보겠습니다.
So once we change the format like this, and then do data aggregations, we will have a nice report about the sales by month.
6:20:52
이제 주문 날짜와 주문 수를 세어보겠습니다.
So let's have a quick aggregations using the format. So we're going to go and say select,
6:20:57
이제 주문 날짜를 세고 판매 주문 테이블에서 주문 수를 집계한 후 그룹화합니다.
And now the order dates and counts the number of orders from our table sales orders and then group by.
6:21:08
하지만 주문 날짜를 사용하기 전에 형식을 지정해야 합니다. 주문 날짜를 가져와서 실행해 보겠습니다.
But now before we start using the order date, we have to go and format it. And then if you take the order dates, let's go and execute it.
6:21:14
보시다시피 세부 사항의 수준이 매우 높고 10개의 행이 있습니다. 매일 하나의 주문이 있습니다.
So as you can see, the level of details is very high and we have here 10 rows. And for each day, we have like one order.
6:21:21
이제 날짜 부분을 사용하여 하나의 부분을 추출하고 집계할 수 있다는 것을 배웠습니다.
Now we learned we can go and use the date part in order to extract one part and then aggregate on it.
6:21:26
이제 그 대신 형식 함수를 사용하겠습니다.
now instead of that we're going to go and use the format function so
6:21:30
형식을 변경해 보겠습니다. 그것이 주문 날짜입니다.
let's go and change the format and it is the order date
6:21:33
우리의 형식은 이렇게 될 것입니다. 세 자리입니다.
and our format gonna be like this so three big
6:21:36
그리고 연도에 대해 두 자리를 사용합니다.
m and then two digits for the year that's
6:21:39
그리고 여기에서 주문 날짜에도 필요합니다.
it and let's call it order dates and
6:21:42
그룹 I와 여기에서 쉼표가 있습니다. 이제 실행해 보겠습니다.
we need this as well for the order date over here for
6:21:45
출력에서 보시다시피 세 개의 월이 있으며 여기에서 주문 수를 집계하고 있습니다.
the group i and here a comma so that's it let's go
6:21:48
각 월에 대해 이제 날짜 부분과 비슷하지만, 이제 형식을 사용자 정의하고 있습니다.
and execute it so in the output as you can see over here we have three months and here we're having the aggregation the number of orders
6:21:54
원하는 형식으로 사용자 정의하고 형식을 사용할 수 있습니다.
for each month so now it's like the date part but now we are
6:21:57
날짜의 세분성을 변경하기 위해 형식을 사용합니다.
customizing the format as we want so we can use the
6:22:00
그렇게 하려면 이제 집계를 수행합니다.
format in order to change the granularity of the date
6:22:04
형식을 변경하기 위해 실제 프로젝트에서의 실제 사용 사례를 보여드리겠습니다.
in order to do that aggregations now
6:22:10
이제 우리의 데이터는 다양한 기술에 저장될 수 있습니다. 데이터는 CSV 파일에 저장되거나 API 호출을 통해 가져올 수 있습니다.
i'm going to show you a real use case for the formatting in real projects
6:22:13
우리가 일반적으로 하는 것은 이러한 다양한 소스에서 데이터를 중앙 저장소로 추출하는 것입니다.
now our data could be stored in different technologies like the data could be stored in csv file or we can get our data using an api call or in very common scenario our data could be stored in database
6:22:24
날짜에 대해 서로 다른 형식을 받을 수 있습니다. 이는 분석에 문제가 됩니다.
So now what we usually do, we go and extract the data from these different sources into one central storage.
6:22:30
우리가 할 일은 형식을 하나의 표준 형식으로 정리하는 것입니다.
It could happen that you are getting different formats for the dates. And of course, this is a problem for analytics. You cannot present different formats for the dates.
6:22:37
즉, 들어오는 데이터를 새로운 형식으로 포맷해야 합니다.
What you're going to do, we're going to go and clean up the formats into one standard format.
6:22:41
하나의 표준 형식이 있으면 분석 및 보고서에서 사용할 수 있습니다.
So that means we have to format the incoming data to a new format.
6:22:46
이는 데이터 준비 및 데이터 정리에서 매우 일반적인 사용 사례입니다.
And once we have one standard format, we can use it in analytics and reports.
6:22:50
이제 SQL에서는 다양한 날짜 및 시간 지정자가 있습니다.
So this is very common use case in data preparation and in data cleanup by formatting different formats into one standard format.
6:23:02
제가 말했듯이, 이들은 대소문자를 구분하며 각각 다른 의미를 가집니다.
Now, in SQL, we have many different date and time specifiers.
6:23:07
그리고 제가 말했듯이, 대소문자를 구분하며 각각은 다른 의미를 가지고 있습니다.
And as I said, they are case sensitive and each one of them has a different meaning.
6:23:11
그래서 저는 여러분을 위해 사용할 수 있는 모든 가능한 지정자를 준비했습니다.
So I prepared for you as well all possible specifiers that we can use with the formats.
6:23:15
뿐만 아니라, 이 장에서 찾을 수 있는 쿼리로 돌아가면 날짜 형식을 찾을 수 있습니다.
Not only that, if you go back to the queries that you can find in this chapter, you can find here date format.
6:23:21
모든 날짜 형식은 내부로 들어가면 전체 쿼리를 복사한 다음 SQL로 돌아가 실행할 수 있습니다.
So all date formats, if you go inside it, you can go and copy the whole query and then go back to SQL, then execute it.
6:23:28
여기에서 현재 날짜를 조작하고 있는 실시간 예제를 찾을 수 있습니다.
You can find here a live example because I'm manipulating now the get date.
6:23:33
여기에서 사용할 수 있는 모든 가능한 날짜 지정자의 목록을 찾을 수 있습니다.
So you can find here a list of all possible date specifiers that you can use with the formats.
6:23:39
그래서 저는 여러분이 SQL에서 가능한 것을 이해하기 위해 이러한 다양한 날짜 형식으로 연습해 보라고 말하고 싶습니다.
So I would say go and practice with those different date formats in order to understand what is possible in SQL.
6:23:45
우리가 날짜 형식의 변환이 가능하다는 것을 배웠듯이, 숫자의 형식도 함수 형식을 사용하여 변경할 수 있습니다.
So as we learned that all we can change the format of the date, we can change as well the format of the number using the function formats.
6:23:51
이 형식의 지정자로 사용할 수 있는 다양한 가능성입니다.
And those are the different possibilities that you can use as a specifier for this format in order to change the format of the numbers.
6:23:58
그리고 저는 이러한 다양한 지정자를 하나의 큰 쿼리로 준비했습니다.
And as well, I have prepared all those different specifiers in one big query.
6:24:02
내부로 들어가서 복사한 다음 SQL에 붙여넣고 실행하면, 숫자 형식을 변경하기 위한 모든 다양한 가능성을 찾을 수 있습니다.
So if you go inside it and copy it and then put it in SQL and execute it, you will find here all different possibilities that we have as a specifier to change the format of the numbers.
6:24:18
좋아요, 변환이란 무엇인가요? 매우 간단합니다. 우리는 가서 변경할 것입니다.
all right so what is convert it's very simple we're gonna go and change
6:24:21
값을 다른 유형으로 변경하고, 또한
the value to a different type and as well at
6:24:24
동시에 값을 형식화하는 데 도움이 됩니다.
the same time it helps formatting the value okay
6:24:27
변환의 구문을 확인해 보겠습니다. 이렇게 보입니다.
so let's check the syntax of the convert and it looks like this it
6:24:30
함수 변환으로 시작하며 두 개의 매개변수를 받습니다. 첫 번째는 데이터 유형입니다.
starts with the function converts and it accepts two parameters the data type first since we can use this function in order to cast the data types So you can use a string integer dates and so on.
6:24:42
그런 다음 값을 지정해야 합니다. 어떤 값을 변환해야 할까요?
And then we have to specify the value. So which value should be casted?
6:24:46
마지막 매개변수는 선택 사항으로, 값의 형식 스타일을 정의합니다.
And the last parameter, it is optional one where you define the style of the format of the value.
6:24:52
아주 간단한 예를 들어 보겠습니다. 우리는 변환을 말하고 있습니다.
Let's have this very simple example. We are saying convert
6:24:55
정수형 데이터 타입으로 변환하고, 값은
to the data type integer int and the value that
6:24:59
문자열로서 변환해야 할 것은 123입니다.
should be converted is one two three as a string so it's
6:25:02
정수로 변환할 것이며, 변환해야 할 값은
going to convert it to integer we are saying convert to
6:25:05
주문 날짜입니다. 따라서 주문 날짜는 날짜여야 합니다.
a varchar and the value that should be converted is
6:25:08
날짜에서 varchar로 변환할 것이며, 형식 또는 스타일 34를 사용합니다.
the order date so the other date should be a date so
6:25:11
여기서 우리는 스타일, 형식을 지정하고 있습니다.
we're going to convert it from date to varchar using the format or the style of 34 so here we are specifying a style a format
6:25:19
이 값에 대해 물론 선택 사항입니다.
for this value and of course it is optional and
6:25:23
아무것도 사용하지 않으면 기본값은
if you are not using anything the default value that's
6:25:26
0이 사용됩니다. 이것이 구문입니다.
going to be used is zero so this is the syntax of
6:25:29
SQL에서 변환하는 방법입니다. 자, 이제 몇 가지 예를 살펴보겠습니다.
the convert in sql all right so now we have a few examples on
6:25:32
변환하는 방법에 대한 예를 들어보겠습니다. 예를 들어 문자열을 정수로 변환합니다.
how to work with the convert so let's go and convert
6:25:35
예를 들어 변환한다고 가정하고, 목표 데이터 유형은 정수입니다. 값은 예를 들어 123과 같습니다.
for example string to integer so we're going to say for example converts so what is the target data type it's going to be the integer and the value it's going to be like for example one two three so
6:25:47
이렇게 문자열을
and let's call it like this string to
6:25:50
정수로 부르고 함수는 변환입니다.
integer and the function is convert so
6:25:53
이제 열 이름에서 괄호를 사용하고 있습니다. 그 이유는
now in the column name as you can see i'm using here brackets and that's because
6:25:56
빈 공간 등을 사용하고 있기 때문입니다. 이렇게 하면
i'm using like empty spaces and so on and with that
6:25:59
이름을 지정하는 데 더 많은 자유를 얻을 수 있습니다. 이것은 단순한 이름입니다.
i will get more freedom on how to name things so this is just
6:26:02
이름이므로 함수나 무언가가 아닙니다.
a name so this is no function or something let's
6:26:05
이제 보시다시피 작동할 것입니다. 문자열 값을 정수로 변환하고 있으며, 출력은 이 숫자 1, 2, 3이 문자열이 아니라 정수 데이터 유형입니다.
go and excuse it now as you can see it's going to work so we are converting from a string value to an integer and the output this one two three here is not string this is the data type of integer.
6:26:17
좋습니다. 이제 문자열에서 날짜로 변환하는 또 다른 예제를 살펴보겠습니다.
All right. So now let's have another example where we want to convert from string to date.
6:26:21
목표는 날짜와 값이 될 것입니다. 이 값을 평소처럼 가져옵니다.
So the target is going to be the date and the value. Let's have this value as usual.
6:26:27
그리고 우리는 문자열에서 날짜로 변환하는 함수를 호출할 것입니다. 알겠습니다.
And we're going to go and call it string to date convert. Okay.
6:26:35
이제 실행해 보겠습니다. 출력에서 이 정보를 날짜로서 얻을 것입니다.
So let's go and execute it. Now in the output, we will get this information, this string as a date.
6:26:40
그렇게 해서 우리는 데이터 유형을 문자열에서 날짜로 변환했습니다. 이제 문자열에서 날짜로 변환하고자 하는 또 다른 예제를 살펴보겠습니다.
And with that, we have converted the data type from string to date. Now let's have another example where we want to convert
6:26:46
날짜 시간을 날짜로 변환하는 것입니다. 생성 시간이
the date time to a date as you remember the creation time is
6:26:49
날짜 시간이며, 우리는 그것을 날짜로만 갖고 싶습니다.
a date time and we would like to have it as only date so
6:26:52
그러니 변환해 보겠습니다. 우리는 그것이
let's go and convert and we would like it to
6:26:55
날짜가 되기를 원하지만 이번에는 '생성 시간'이라는 열이 될 것입니다.
be as well dates but this time it's going to be a column called
6:26:59
이름을 부여합시다.
creation time and let's give it the name
6:27:02
우리는 날짜를 변환하고 있습니다.
so we are converting dates
6:27:05
시간을 날짜로 변환하지만, 물론 여기서는 선택해야 합니다. 판매 주문에서 그게 전부입니다.
time to dates but of course here we have to go and select so from sales orders that's it
6:27:12
이제 실행해 보겠습니다. 출력에서 보시다시피
let's go and execute it now as you can see in the output we
6:27:15
날짜만 얻었고, 생성 시간을 선택하겠습니다.
got only date i'm gonna go and select the creation time in
6:27:19
쿼리에서도 마찬가지입니다. 이제 생성 시간이
the query as well so now as you can see the creation time was
6:27:22
날짜 시간 이전이므로 시간 정보도 있습니다.
before a date time so we have that time information as well
6:27:26
하지만 변환을 사용하여 형변환을 하면
but if you go and cast it using the convert and
6:27:29
날짜만 만들게 되므로 SQL이 날짜로 변환할 것입니다.
make it only date so sql gonna go and convert it to date
6:27:32
그러면 시간에 대한 모든 정보가 사라집니다. 지금까지
and you're gonna lose all the informations about the time so so far
6:27:35
여기서 하는 것은 단순히 형변환을 하는 것이므로
what you are doing here is just casting so we are changing the
6:27:38
데이터 유형을 하나에서 다른 것으로 변경하고 있습니다. 하지만 변환에서는
data type from one to another but in the convert we can
6:27:41
두 가지를 모두 할 수 있습니다. 형변환과 포맷팅을 할 수 있으니, 어떻게 하는지 보겠습니다.
do both we can do casting and formatting so let's see how we
6:27:44
그 정보를 제거하겠습니다.
can do that i will just get rid of those information at
6:27:47
시작 부분에서 생성 시간으로 가서
the start so creation time and now we're gonna go and
6:27:51
생성 시간의 날짜 시간을 변환하여
convert the date time of the creation time to
6:27:54
문자열로 변환하고 포맷을 지정하겠습니다.
a varchar to a string and as well to give it the format
6:27:57
미국 표준 형식으로 변환하는 방법을 보겠습니다.
of the usa standard format so let's see how we can do that we're
6:28:01
변환을 시작하겠습니다. 이제
gonna start with converts we are changing now to a
6:28:04
varchar로 변경하고 있습니다. 이것이 새로운 데이터 유형입니다.
varchar so this is the new data type and
6:28:07
값은 생성 시간이며, 스타일을 지정하지 않으면
the value is the creation time and now if i don't give it a
6:28:10
표준 형식으로 유지됩니다. 하지만 우리는
style it's going to stay with the standard format but we would like to have the
6:28:14
미국 표준을 원합니다. 이를 위해
usa standards so in order to do that we're
6:28:17
형식의 스타일을 추가하겠습니다. 그래서 32가 될 것입니다.
going to go and add the style of the format so it's going to be 32
6:28:20
그게 전부입니다. 이렇게 이름을 지정하겠습니다.
so that's it let's have a
6:28:23
미국 표준처럼, 우리는 32 스타일을 사용하고 있습니다.
name like this so usa standard and
6:28:28
우리는 32의 스타일을 사용하고 있습니다. 가자
we are using the style of 32 let's
6:28:31
이것은 다시 이름일 뿐이므로 기능이 아닙니다. 가자
go with that this is just a name again so it's not a function let's
6:28:35
가서 실행하고 이제 출력에서 새로운 필드를 얻었습니다.
go and execute it and now in the output we got a new field and the
6:28:38
이 필드의 데이터 유형은 varchar이므로 날짜가 아닙니다.
data type of this field is a varchar so it's not a date or
6:28:41
날짜 시간이며 이제 날짜가 다음을 사용하여 형식화되었습니다.
date time and as you can see the date now is formatted using
6:28:45
이 스타일은 미국 표준 형식 32입니다.
this style the 32 the usa standard formats so
6:28:48
월, 일, 연도 순서로 시작합니다.
it starts with a month then a day and then a year
6:28:51
이제 표준 형식을 얻기 위해 같은 작업을 해보겠습니다.
so now let's go and do the same thing in order to get the standard
6:28:54
유럽의 형식이므로 전체를 복사하겠습니다.
format in europe so i will just go and copy the whole thing
6:28:58
스타일을 변경하겠습니다. 대신
i will just change the style so instead
6:29:01
32 대신 34로 진행하겠습니다.
of 32 we're gonna go with the 34 and
6:29:04
이름도 변경하겠습니다.
so we'll just change the name as well so so
6:29:08
스타일을 변경하고 있습니다. 이제 실행해보겠습니다.
we are just changing the style let's go and execute it now
6:29:11
같은 것을 얻었고, char도 있습니다.
as you can see we got the same thing we have as well of our char and
6:29:14
형식이 다르므로 여기에서 일자가 있습니다.
the format now is different so we have here the day
6:29:17
그 다음에 월, 그 다음에 연도가 있습니다.
and then the month and then the year so this is how you work with the convert function you can use it in order to do only casting or not only that you can do
6:29:26
형식이 다르므로 여기에서 일자가 있습니다.
casting and as well formatting so you have both things in one function
6:29:34
사용 가능한 스타일에 대해 이야기하자면, 많은 스타일이 있습니다.
and now if you're talking about which styles are available we have many
6:29:37
변환 안에서 사용할 수 있는 스타일이 있습니다.
styles that you can use inside the convert so i have prepared
6:29:40
날짜 전용 스타일과 다른 스타일이 있습니다.
for you a list of all styles that you can use with the convert
6:29:43
시간 전용 스타일과 날짜 시간 전용 스타일이 있습니다.
so we have styles only for the dates and another styles
6:29:46
여기에서 '모든 문화 형식'이라는 파일을 찾을 수 있습니다.
only for the time and styles for only date time now in the download folders you can find here one file called all culture formats
6:29:55
여기에서 제가 준비한 쿼리를 찾을 수 있습니다.
And here you can find one query that I've prepared where you
6:29:58
여기에서 다양한 문화와 예제를 찾을 수 있습니다.
can find inside it the different cultures and the examples
6:30:01
복사하고 SQL로 돌아가서 붙여넣겠습니다.
so let's go and copy it and let's go back to sql paste
6:30:04
결과를 확인해 보겠습니다.
it and let's see the results so now if you check the output
6:30:07
첫 번째 열은 사용된 문화입니다.
we got the first column is the cultures that is used so we
6:30:10
우리는 문화의 첫 번째 열을 가지고 있습니다.
have a lot of cultures like around 17s and you can see how the
6:30:14
여기서 숫자 형식이나 날짜 형식이 이 문화에 따라 어떻게 형식화되는지 볼 수 있습니다.
numbers are formatted or the date is formatted based on this culture so it's really fun you can check here for example how the format in Japan or Korea or France and the German one.
6:30:23
스크롤을 내리면 아랍어, 러시아어 등을 찾을 수 있습니다.
If you scroll down, you can find the Arabic, the Russian and so on.
6:30:27
각 날짜의 형식이 그 문화에 따라 어떻게 변하는지 볼 수 있습니다.
So you can see the formats of each date is changing based on that culture. So I would say have fun.
6:30:33
그렇다면 캐스트 함수란 무엇인가요?
Go and try those different cultures formats in order to format your numbers or dates.
6:30:41
값을 다른 데이터 유형으로 변환하는 것입니다.
So what is the cast function? It's going to go and convert a value to a different data type.
6:30:46
하나의 데이터 유형을 다른 데이터 유형으로 변환합니다.
So it turns one data type to another. All right. So now let's check the syntax of the cast. I really like this one.
6:30:52
SQL에서 일반적인 형식이나 구문이 아닙니다.
It is not a typical like format or syntax in SQL.
6:30:56
캐스트는 함수이며, 그 안에는 두 가지가 필요합니다.
So it says the cast is the function and then inside it, we need two things, but it's not separated like with the comma as we learned before with all other functions, but this time it's separated with the keyword as.
6:31:08
자연스러운 영어처럼, 값의 데이터 유형을 캐스트한다고 말하는 것입니다.
So it's like the natural English. You are saying cast the value as a data type.
6:31:13
값을 새로운 데이터 유형으로 캐스트하고 있습니다.
So you are casting the value to a new data type. So let's have this very simple example.
6:31:17
여기서 값 1, 2, 3을 정수로 캐스트합니다.
We have here cast the value one, two, three as integer.
6:31:22
이전에는 문자열이었고 정수로 변환될 것입니다.
So previously it is string and it's going to be converted to integer. So as you can see, it's very simple.
6:31:27
이 예제에서는 이 문자열 값을 날짜로 캐스트한다고 말하고 있습니다.
Now in this example, we are saying cast this value, this string value as a date. So convert it from string to date.
6:31:33
캐스트에서는 값의 형식이나 스타일링 옵션이 없습니다.
So as you can see with the cast, we don't have here any option of formatting or styling the values.
6:31:38
하나의 데이터 유형에서 다른 데이터 유형으로 캐스트하는 데 전념하고 있습니다.
So it's only dedicated for casting the value from one data type to another one. So this is the syntax of the cast.
6:31:45
매우 간단하고 정말 좋은 함수입니다.
It is very straightforward and really nice function. Okay. So now let's have a few examples about the cast.
6:31:50
문자열에서 정수로 값을 변환해 보겠습니다.
So let's go and convert a value from a string to integer. So it's very simple. We're going to say cast. So now we need the value.
6:31:58
하나, 둘, 셋으로 가겠습니다.
So let's go with a one, two, three. So we have here a string, and then we're going to say as, and then we have to define the data type.
6:32:04
데이터 유형은 정수가 될 것입니다.
So the data type is going to be integer. So that's let's
6:32:08
이름을 이렇게 문자열에서 정수로 지정합시다.
give it the name like this string to integer
6:32:11
이제 실행해 보겠습니다.
let's go and execute it now as you can see we got the value
6:32:14
정수 데이터 유형으로 변환되었습니다.
but with the data type integer from string to integer now
6:32:17
정수에서 문자열로 캐스트해 보겠습니다.
let's do the way around we cast from integer to string so
6:32:20
하나, 둘, 셋을 캐스트하겠습니다.
we're going to say cast one two three as
6:32:24
우리의 문자로 이름을 줄 것입니다
of our char and we're going to give it the name
6:32:27
정수형을 문자열로 변환하겠습니다. 이제 실행해 보겠습니다.
int to string so let's go and execute it now in the output we have one two three
6:32:34
이번에는 데이터 유형이 varchar입니다.
but this time it has the data type varchar now
6:32:37
날짜로 작업해 보겠습니다. 값을 변환할 것입니다.
let's go and work with a date so we're gonna go and convert
6:32:40
값을 문자열 값으로 변환할 것입니다.
a value a string value to a
6:32:43
날짜로 변환할 값은 일반적인 것입니다.
date so our value gonna be the
6:32:46
날짜로 변환할 것이므로 데이터 유형은 날짜가 될 것입니다.
usual one and we want it from string to date so we're
6:32:50
날짜로 변환할 것이므로 이름을 문자열로 지정하겠습니다.
gonna have the data type as dates so let's give it a name string
6:32:54
이 값을 날짜로 가져오고 싶습니다.
to dates let's go and excuse it now we're gonna have this value with the data type date so that's it
6:33:01
시간으로 가져오고 싶습니다.
now let's say that i would like to have this value but as date
6:33:04
전체를 복사하고 새 줄로 이동하겠습니다.
time so i will just copy the whole thing and
6:33:07
새 줄로 이동하여 날짜와 시간을 입력하겠습니다.
go to a new line and say date time
6:33:11
이름은 문자열에서 날짜 및 시간으로 설정하겠습니다.
two so the name of this is going to be string to date time
6:33:15
출력에서 날짜와 시간 정보를 모두 가져오고 있습니다.
let's go and execute it now in the output as you can see we
6:33:18
하지만 SQL에 시간 정보를 제공하지 않았기 때문에
are getting not only the date but as well we are getting the time information
6:33:21
SQL은 이를 0으로 표시할 것입니다.
but now since we didn't provide sql with any time information
6:33:25
더 많은 캐스팅을 하여 데이터 유형을 날짜 및 시간에서 날짜로 변경하겠습니다.
sql gonna go and show it as zeros now let's do one
6:33:28
이제 생성 시간이 필요하지만
more casting where we change the data type from date time to date
6:33:31
테이블에서 가져와야 합니다. 판매 주문에서
so now we need our creation time but
6:33:35
실행해 보겠습니다. 이제 출력에서
we have to get it from the tables so from sales orders
6:33:38
생성 시간이 날짜 및 시간으로 표시됩니다.
let's go and execute it so now in the output you can
6:33:41
시간 정보에 관심이 없으므로 이 필드를 채우고 싶습니다.
see the creation time is a date time we have the time information but we are
6:33:44
날짜로 가져오고 싶습니다. 간단합니다.
not interested about that time information i would like to have this filled
6:33:47
이제 값은 생성 시간입니다.
as a date so it's very simple what we're gonna do we're gonna say cast
6:33:51
키워드는 as이며 날짜로 필요합니다.
now the value is creation time and
6:33:55
그럼 키워드는 'as'이고 우리는 날짜로 필요하니
then the keyword as and we need it as a date so
6:33:58
날짜에 'date time'이라는 이름을 붙이겠습니다.
we're gonna give it the name date time to dates
6:34:02
그럼 이제 실행해 보겠습니다. 출력에서 볼 수 있듯이
so let's go and execute it now as you can see in the output we
6:34:05
생성 시간을 얻었지만 날짜 정보만 있습니다.
got the creation time but only with the date information
6:34:08
시간에 대한 정보는 없으니
we don't have anything about the time so we get it as
6:34:11
날짜 대신 'date time'으로 얻습니다. 정말 놀랍습니다.
a date instead of date time so that's it this is amazing
6:34:15
SQL 함수는 매우 간단하며 우리는 오직
function sql and it's very simple and we can use it only for
6:34:18
형변환에만 사용할 수 있습니다. 즉, 데이터 유형을 하나에서 다른 것으로 변경하는 것이며, 형식을 변경하기 위해 이 함수를 사용할 수 없습니다. 형변환을 하면 항상 SQL의 표준 형식을 얻게 됩니다.
casting so only to change the data type from one to another and we cannot use this function in order to change the format so if you are casting you will get always the standard format from SQL.
6:34:29
그럼 이제 우리의 함수를 나란히 비교해 보겠습니다.
So now let's go and compare our functions side by side.
6:34:35
세 가지 함수, cast, convert, format이 있습니다. 우리는 두 가지 작업을 할 수 있습니다: 형변환 또는 포맷팅입니다.
So we have our three functions cast convert and formats and we can do two things either casting or formatting.
6:34:43
첫 번째 함수인 cast를 통해 어떤 유형이든 다른 유형으로 변경할 수 있습니다. 제한이 전혀 없습니다.
So by the casting for the first function cast we can change any type to any other type. So there is no restriction at all.
6:34:49
convert도 마찬가지입니다. 우리는 무엇이든 변환할 수 있습니다.
The same thing for the converts the same thing we can convert anything
6:34:52
하지만 format은 문자열로만 변경할 수 있습니다. 즉, 날짜나 숫자와 같은 데이터 유형을 문자열 값으로 변경할 수 있습니다. format의 주요 목적은 데이터 유형을 변경하는 것이 아닙니다.
to anything but for the format we can change only to a string so any data type like date or number to a string value because the main thing for the format is not changing the data type.
6:35:04
값의 형식을 변경하는 것에 대해 이야기한다면, 형변환 함수를 사용하여 형식을 변경할 수 없습니다.
Now, if you are talking about changing the format of the values, you cannot use the cast function in order to change the format.
6:35:10
형변환 함수는 오직 형변환을 위한 것입니다. 이해가 됩니다. convert에 대해서는, 데이터와 시간의 형식을 변경하는 데 사용할 수 있지만, 숫자 형식을 변경하는 데는 사용할 수 없습니다.
So the cast function is only for casting. It makes sense. Now about the convert, we can use it in order to change the format of the data and time, but we cannot use it in order to change the number formats.
6:35:21
그를 위해 우리는 format이라는 전용 함수를 가지고 있습니다. 이를 사용하여 날짜와 시간, 그리고 숫자의 형식을 변경할 수 있습니다.
And for that, we have a dedicated function called format. So we can use it to change the format of the date and time and as well the numbers.
6:35:28
이것이 세 가지 함수 간의 주요 차이점입니다. 알겠죠.
So those are the main differences between those three functions. All right.
6:35:32
이 세 가지 함수로 우리는 날짜 정보에 대한 포맷팅과 형변환을 하는 방법을 배웠습니다.
So with those three functions, we have learned how to do formatting and casting on date informations.
6:35:37
이제 세 번째 그룹으로 넘어가면 날짜 계산이 있습니다.
Now, moving on to the third group, we have the date calculations.
6:35:40
여기에는 두 가지 함수가 있으며 날짜 계산이나 날짜에 대한 수학적 연산을 수행하는 방법이 있습니다.
And here we have two functions and how to do date calculations or mathematical operations on the dates.
6:35:45
좋습니다. 이제 첫 번째 함수인 date add를 시작하겠습니다.
Okay, so now we're going to start with the first function, the date add.
6:35:52
date add란 무엇인가요? date add는 특정 시간 간격을 날짜에 더하거나 빼는 것을 허용합니다.
So what is date add? Date add can allow us to add or subtract a specific time interval to or from a date.
6:36:00
date add가 어떻게 작동하는지 이해해 보겠습니다. 다시 말해, 우리의 날짜는 2025년 8월 20일입니다.
So let's understand how the date add work. So again, we have our date August 20th, 2025.
6:36:06
일부 시나리오에서는 날짜에 연도를 추가하고 싶습니다.
So now in some scenarios, we would like to add years to our dates.
6:36:09
예를 들어, 날짜에 3년을 추가하고 싶다고 가정해 보겠습니다. date add를 사용하여 이를 수행할 수 있습니다.
So for example, let's say I would like to add three years to our date. So we can do that using the date ads.
6:36:15
출력에서 2028년 8월 20일이 됩니다.
So if you do that in the output, you will get 2028 August 20th.
6:36:19
날짜 부분만 변경되었고 3년이 추가되었습니다. 하지만 다른 경우에는 월을 추가하고 싶을 것입니다.
Only the date part is changed and where we have added three years. But in other scenarios, you would like to go and add months.
6:36:26
예를 들어, 8월에 2개월을 추가해 보겠습니다. 출력에서 2025년 10월 20일이 됩니다.
So for example, let's go and add two months to the August. So in the output, you will get 2025 1020.
6:36:33
그렇게 해서 2개월이 추가되었습니다. 물론 날짜에 일수를 추가할 수도 있습니다.
With that, we have added two months. And of course, we can go and add days to our dates.
6:36:38
예를 들어, 날짜에 5일을 추가해 보겠습니다.
So for example, we're going to go and add five days to our dates.
6:36:42
출력에서 같은 해 2025년, 같은 달 8월이지만, 날짜는 25일로 변경됩니다.
So in the output, we'll get the same year 2025, the same month, August, but only the day will be changed to 25.
6:36:48
원래 날짜에 5일을 추가했습니다.
So we have added five days to the original dates.
6:36:51
물론 날짜를 빼는 것도 가능합니다. 날짜 추가라는 함수가 있지만요.
And of course we can go and subtract dates, even though that the function called date add.
6:36:56
예를 들어, 날짜에서 3년을 빼면 이렇게 됩니다.
So for example, we can go and subtract three years from our dates and we will get.
6:37:01
그렇게 하면 2022년 8월 20일이 되거나, 날짜에서 2개월을 빼면 됩니다.
So if you do that, you will get 2022 August 20th, or if you go and subtract two months from our dates.
6:37:07
2025년은 그대로 유지되고, 이번에는 8월 대신 6월로 가서 같은 날 20일이 됩니다.
So it's going to stay the same year 2025. this time instead of August, we will go back to June with the same day 20.
6:37:14
날짜에서 5일을 빼면 같은 일이 발생할 수 있습니다.
And the same thing can happen for the days if you go and subtract five days.
6:37:18
2025년, 같은 달 8월이지만, 날짜는 20일 대신 15일이 됩니다.
So the same year 2025, the same month August, but only the day is going to be instead of 20, it's going to be 15.
6:37:24
날짜 추가를 사용하면 연도, 월, 일수를 빼거나 추가하여 조작할 수 있습니다.
So as you can see with the date ad, you can manipulate the years, the month and the days by subtracting or adding new intervals.
6:37:33
날짜 추가가 작동하는 방식입니다. 이제 날짜 추가의 문법을 확인해 보겠습니다.
So this is how the date ad works. All right, so now let's check the syntax of the date ad.
6:37:37
여기서 조금 더 복잡해지며, 세 가지 정보를 제공해야 합니다.
And here things a little bit more complicated we have to provide three
6:37:41
첫 번째는 추가할 부분입니다.
informations the first one is a part what do you want to add
6:37:44
연도, 월 또는 일수를 추가할 것인지입니다.
do you want to add years or months or days and
6:37:47
두 번째는 간격입니다.
so on then the second one is interval so
6:37:50
얼마나 많은 일수, 연수, 월수를 추가할 것인지입니다.
it's like how many days how many years how many months and
6:37:53
마지막은 날짜입니다. 우리가 조작할 날짜입니다.
then the last one is the date this is the date that we're going to be
6:37:56
간격을 추가하거나 빼는 것입니다.
manipulating by adding or subtracting intervals
6:38:00
다음 예제를 확인해 보겠습니다. 여기서 날짜를 말하고 있습니다.
let's check the following example we are saying here date
6:38:03
추가할 부분은 연도입니다. 이는
add so what is the part here is a year that means
6:38:06
연도 부분만 조작하고 싶다는 의미입니다.
we want to manipulate only the year part then the interval
6:38:09
여기서 두 개가 있으니 긍정적입니다. 우리는 2년을 더하고 싶습니다.
here is two so it is positive we want to add two years
6:38:13
각 주문으로 가서 2년을 더하기 시작할 것입니다.
so it's going to go to each order and start adding two years for
6:38:17
각 날짜 값에 대해 이제 다른 예를 확인해 보겠습니다.
each date value now let's check another example here we are
6:38:20
날짜에 월을 추가한다고 말하고 있습니다. 여기서 우리는
saying date add month so here we want to manipulate the
6:38:23
월 부분을 조작하고 싶습니다. 하지만 여기서는 4개월을 빼겠다고 말하고 있습니다.
month part but here we are saying minus four
6:38:26
즉, 각 주문 날짜의 값에서 4개월을 빼고 싶습니다. 보시다시피, 간격의 값은 긍정적이거나 부정적입니다.
that means we want to go and subtract four months from each value in the order date so as you can see the value of the interval whether it's positive or negative
6:38:36
여기서 우리는 함수가 빼기인지 더하기인지 제어하고 있습니다.
we are controlling here the function whether it is subtraction or
6:38:39
그럼 날짜 추가에 대한 몇 가지 예를 들어 보겠습니다.
addition so let's have a few examples about the date add using
6:38:43
우리의 필드 주문 날짜로, 예를 들어 2년을 더해 보겠습니다.
our field order dates so for example let's go and add two
6:38:46
각 날짜에 대해 2년을 더할 수 있습니다.
years for each date so we can do it like
6:38:49
이 날짜 추가는 우리가 년을 더하고 있다는 것입니다. 그래서
this date ads so we are adding years that's why we're
6:38:52
우리는 연도 부분과 몇 년을 더하고 있는지 확인할 것입니다. 우리는 2년을 더하고 있습니다.
going to go with the part year and how many years we are adding we are adding two
6:38:55
그래서 이것이 우리의 간격이고, 우리의 필드는 주문 날짜입니다. 이제 출력에서 보시다시피, 우리는 날짜를 얻었습니다. 하지만 이 날짜는 항상 주문 날짜보다 2년 더 높습니다.
years so this is our interval and our field our value is the order date so now in the output as you can see we got a date But this date is always two years higher than the order dates.
6:39:06
모든 곳에 C 2027이 있습니다. 이제 각 날짜에 대해 3개월을 더해 보겠습니다.
So everywhere you have C 2027. Now let's go and add maybe three months for each date.
6:39:12
그냥 복사해서 한 달이라고 하겠습니다. 간격을 3으로 변경합시다.
Just going to go and copy it and say a month. Let's change the interval to three.
6:39:17
그리고 우리는 이를 3개월 후라고 부를 것입니다. 이제 여기에서 중단 시간을 확인하면 새로운 날짜가 있습니다.
And we're going to call it three months later. So now if you check the outages over here, we have a new date.
6:39:24
하지만 이제 그것과 주문 날짜 사이의 차이는 항상 주문 날짜보다 3개월 더 많습니다.
But now the difference between it and the order date, we have here always three months more than the order dates.
6:39:31
예를 들어, 여기에는 1월이 있지만 새로운 날짜에는 4월이 있습니다. 다음 날짜는 2월입니다.
So for example, here we have January, but in the new one we have April. And for the next one, we have February.
6:39:37
그리고 새로운 필드에는 내 것이 있습니다. 보시다시피, 우리는 여기에서 월을 추가하고 있습니다.
And in the new field, we have my. So as you can see, we are adding months over here.
6:39:42
보시다시피, 우리는 원래 필드 주문 날짜에 월을 추가하고 있습니다.
So as you can see, we are adding months to our original field order dates.
6:39:46
이제 10일을 빼고 싶다고 가정해 보겠습니다. 그러니 같은 방식으로 해보겠습니다.
Now, let's say that I would like to go and subtract 10 days. So let's go and do the same.
6:39:51
그래서 우리는 날짜 추가를 하게 될 것입니다. 우리는 날짜에 대해 이야기하고 있으니, 10일을 빼는 것이 될 것입니다.
So we're going to have the date ads. Since we are talking about the days, it's going to be the day we can subtract 10 days, so minus 10 for that.
6:40:00
주문 날짜. 그래서 이를 10일 전이라고 부르겠습니다. 실행해 보겠습니다.
order date. So let's call it 10 days before. Let's go and execute it.
6:40:06
이제 우리는 새로운 날짜를 얻었고, 이 날짜는 항상 주문 날짜보다 10일 더 이전입니다.
Now we got as well a new date and this date has always 10 days before the order date.
6:40:12
예를 들어, 주문 번호 7을 가져가 보겠습니다. 주문 날짜에는 15가 있지만, 새로운 열에는 5가 있습니다.
So for example, let's take the order number seven. In the order date, we have 15, but in the new column, we have five.
6:40:19
그래서 원래 필드 주문 날짜에서 10일을 뺐습니다.
So we have subtracted 10 days from the original field order dates.
6:40:23
그래서 보시다시피 날짜를 더하거나 빼는 것은 매우 간단합니다.
So as you can see, it's very simple to add or subtract days, year, months using the date ad.
6:40:33
좋습니다, 그럼 날짜 차이는 무엇인가요? 차이는 두 날짜 간의 차이를 찾는 것입니다.
Alright, so what is date diff? Diff stands for difference and date diff can allow us to find the differences between two dates.
6:40:42
좋습니다, 그럼 SQL에서 날짜 차이가 어떻게 작동하는지 이해해 봅시다.
Alright, so let's understand how the date diff works in SQL. Now imagine we have two dates.
6:40:47
2025년 8월 20일의 주문 날짜와 2026년 2월 1일의 배송 날짜가 있습니다.
We have the order date at 2025, August 20th, and the shipping date is the 1st of February in the next year, 2026.
6:40:56
그럼 주문 날짜와 배송 날짜 사이에 몇 년이 지났는지 물어볼 수 있습니다.
Now we might ask the question how many years have passed between the order date and the shipping date?
6:41:02
이 질문에 답하기 위해 우리는 함수를 사용할 수 있습니다.
So in order to answer this question, we can use the function
6:41:05
날짜 차이를 사용하고 연도를 정의할 수 있습니다.
date diff and we can define the part year If
6:41:08
이렇게 하면 두 날짜를 빼고
you do it like this, it's going to subtract those two dates and
6:41:11
그것은 1을 반환할 수 있습니다. 두 날짜 간의 차이는 정확히 1년입니다.
it can return one So the date difference between those two dates is exactly one year But now if the question is how many months are between the order date and the shipping dates?
6:41:21
그래서 여기서 다시 날짜 차이를 사용할 수 있습니다.
So here again we can go and use the date diff between
6:41:24
주문 날짜와 배송 날짜 사이에 몇 개월이 있는지 물어보면
the order date and the shipping date but we use the part month
6:41:27
이렇게 하면 출력에서 3개월을 얻을 수 있습니다.
if you do it like this in the output you will get three months
6:41:30
그럼 이제 며칠이 있는지 물어보면
and now of course if the question is how many days are
6:41:34
주문 날짜와 배송 날짜 사이에
between the order date and the shipping dates so here we can
6:41:37
날짜 차이 함수를 사용하고 날짜를 지정합니다.
use the function date diff where we specify the day
6:41:40
그 안에서 68을 얻을 수 있습니다. 날짜 차이가 이렇게 작동합니다.
inside it and in the output you will get 68 so this is how the date diff works you go and subtract two different dates and you will get in the output
6:41:49
몇 년, 몇 개월, 며칠인지의 숫자를 얻습니다.
a number how many years how many months how many days
6:41:52
그럼 이제 날짜 차이의 구문으로 넘어갑니다.
so that's it all right now to the syntax of the date diff
6:41:55
여기서도 세 개의 매개변수를 받습니다.
it accepts here as well three parameters so the first one
6:41:59
첫 번째는 일반적으로 연도, 월, 일입니다.
is the parts as usual year month day and
6:42:02
그럼 여기서는 두 날짜가 필요합니다.
then here we need two dates not only one we need two so
6:42:05
시작 날짜와 종료 날짜가 필요합니다.
we need the starting dates and the ending dates
6:42:08
그래서 여기서 가장 최근 날짜와 가장 오래된 날짜가 있습니다.
so that means here we have the youngest dates and the end date is going to be the oldest dates so for example here we have date diff and we are saying find
6:42:17
주문 날짜 간의 연도 차이를 찾습니다.
the differences in years between the order dates
6:42:20
이것은 시작 날짜와 배송 날짜입니다.
this is the start date and the shipping dates
6:42:24
그래서 어떤 날짜가 먼저 발생하는지 알아야 합니다.
so which dates normally happen first we have to order something
6:42:27
주문 날짜가 있고 주문하면 다음에 발생할 수 있는 것은
so we have the order dates and once you order what can happen next
6:42:30
배송 날짜입니다. 그래서 배송 날짜는
is the shipping date that's why the shipping date is as
6:42:33
종료 날짜입니다. 그래서 우리는 그들 사이의 차이를 찾고 싶습니다.
an end date so we want to find the differences between them
6:42:37
년 단위로 또는 물론 차이를 찾고 싶다면
in years or of course if you want to find the differences between
6:42:40
일 단위로 바꿔야 합니다.
them in days we have to go and change the part from
6:42:43
연도에서 일로 바꿔야 합니다. 그래서 보시다시피 구문은 매우 간단하고
year to day so as you can see the syntax is very simple and
6:42:46
매우 논리적입니다. 자, 다음 간단한 작업을 해봅시다.
very logical right all right let's have the following simple task and it
6:42:49
직원들의 나이를 계산하라고 합니다. 그럼 보겠습니다.
says calculate the age of employees so let's see
6:42:52
어떻게 해결할 수 있는지 먼저 모든
how we can solve that we're gonna go and select first all
6:42:55
직원 정보를 선택하겠습니다. 그래서 판매
the informations from employees so sales
6:42:58
및 직원 정보를 실행해 보겠습니다.
and employees okay let's execute it now in
6:43:01
직원들에 대해 나이에 대한 정보가 없지만
the employees we don't have any informations about the age but we
6:43:05
생일이 있으므로 이를 변환할 수 있습니다.
have the birthday so we can go and transform this
6:43:08
생일을 나이로 변환하고 나이를 계산하는 방법은
birthday to an age and of course how we calculate the age we count how many many years between this year and the birthday so that means we have to go and use two functions
6:43:18
현재 연도의 연도를 가져오는 것입니다.
the date diff and the get day in order to have
6:43:21
그래서 우리는 날짜 차이 함수를 사용해야 합니다.
the year of the current year so this means we have to go and use
6:43:24
먼저 몇 가지 정보만 선택하겠습니다.
the function date diff so let's go and do that i'm gonna go
6:43:27
직원과 생일입니다.
first selecting only a few informations so employee
6:43:30
그것과 생년월일이므로
it and birth date so
6:43:34
날짜 차이부터 시작하겠습니다. 나이에 대해 이야기하고 있다면 몇 년인지 계산하는 것이므로 우리는 부분으로 말할 것입니다.
let's start with the date diff so if you are talking about the age we are calculating how many years that's why we're gonna say as a part
6:43:40
연도가 될 것이므로 시작 날짜는
going to be the year so what is the starting date is the
6:43:44
그 사람의 생년월일이므로 생년월일이 될 것입니다.
birth date of the person so it's going to be the birth date
6:43:47
이제 종료 날짜가 필요합니다. 종료에 대한 정보는 여기 없습니다.
and now we need the end date we don't have here anything about the end
6:43:50
종료 날짜는 현재 연도가 될 것입니다.
date the end date going to be the current year so in order
6:43:53
현재 연도를 얻기 위해 날짜 가져오기 함수를 사용할 것입니다.
to get the current year we're going to go with the function get dates
6:43:57
이것이 우리가 원하는 것이므로 닫고 나이를 계산해 보겠습니다.
and with that we are getting the current date information and
6:44:00
이것이 우리가 원하는 것이므로 닫고 나이를 계산해 보겠습니다.
this is exactly what we want so let's close it and let's go and call it an age so it's very simple we are counting how many years between the birth dates and the current dates.
6:44:10
첫 번째 사람은 33세입니다.
So let's go and execute it. So now we are getting the ages. As you can see, the first person is 33.
6:44:16
두 번째 사람은 52세입니다.
The second one is 52 and so on. And now you might getting different values than I'm getting now.
6:44:21
지금은 2024년이고, 이 나이를 얻고 있습니다.
And that's maybe you are doing the course now in 2025 or 2026 and employees can be older than now.
6:44:28
이제 날짜 차이에 대한 또 다른 작업이 있습니다.
Now we are 2024 and I'm getting those ages. So this is how we calculate the age using the help of two functions, the date diff and and the get date.
6:44:37
각 월의 평균 배송 기간을 찾아야 합니다.
Okay, so now we have another task for the date diff and it says find the average shipping duration in days for each month.
6:44:44
단계별로 진행해 보겠습니다.
So here we have a lot of information. Let's do it step by step. Let's first find out the shipping durations in days.
6:44:50
주문 ID를 선택해 보겠습니다.
So let's go and select few information from our table. So select order ID.
6:44:55
주문 날짜와 배송 날짜가 있습니다.
We have the order date, ship date. And I think that's it.
6:45:00
이제 10개의 주문이 있습니다.
So from sales orders. So let's go ahead and excuse it.
6:45:06
주문 날짜와 배송 날짜 사이의 일수입니다.
So now we have our 10 orders. We have the order date and the shipping dates. Now we have to go and create a new field called shipping duration.
6:45:13
주문이 이루어진 날부터 배송일까지의 일수입니다.
So what is shipping duration? It is the number of days between the order dates and the shipping dates.
6:45:21
두 날짜의 차이를 찾아야 합니다.
So how many days it took from the order placement until the day of the shipping.
6:45:25
이제 일수로 보아야 하므로 시작 날짜는 무엇인가요?
So that means we have two dates and we have to go and find the differences between them. We're going to go with the function day diff.
6:45:32
시작 날짜는 주문 날짜입니다.
So now, since we are seeing in days, we have to go with the parts day. So what is the start date?
6:45:38
종료 날짜는 배송 날짜입니다.
The start date is the order date. And what is the end date?
6:45:42
결과를 확인해 보겠습니다.
It's going to be that shipping dates like this. So I'm going to call it day to ship like this.
6:45:50
주문은 1월 1일에 이루어졌습니다.
let's go and execute it so now by checking the result for example for the
6:45:53
1월 5일에 배송되었습니다.
order one it is ordered at the first of january and
6:45:56
두 날짜 사이에 약 4일이 있습니다.
it is shipped on fifth of january so between those
6:45:59
배송 기간은 4일입니다.
two dates we have around four days so four is
6:46:02
주문 날짜와 배송 날짜 사이의 차이는 약 4일입니다.
the shipping duration and if you go to the order number three the
6:46:06
주문 날짜와 배송 날짜 사이의 차이
differences between the order date and the shipping date we have around
6:46:09
약 15일 정도입니다. 그래서 이 부분을 해결했습니다.
15 days so with that we have solved this part shipping
6:46:12
배송 기간을 일수로 계산해야 합니다. 하지만 이제
duration in days but now the task says we have
6:46:15
각 월의 평균 기간을 찾아야 합니다.
to find the average duration for each month
6:46:18
예를 들어 1월을 선택해야 합니다.
so that means we have to go and select for example the month
6:46:21
1월의 평균 기간을 찾아야 합니다.
of january and find the average duration so we have
6:46:24
간단한 집계를 해야 합니다. 날짜로 가서
to go and do a simple aggregation we're gonna go to the date if at
6:46:27
시작하고 평균이라고 말한 후 닫습니다.
the start and say average and we're gonna close it over
6:46:30
여기에서 평균 배송으로 이름을 바꿉니다.
here and let's go and rename it average shipping
6:46:34
이제 월별로 집계해야 합니다.
and now we have to aggregate by the month so we
6:46:38
전체 주문 날짜가 필요하지 않습니다. 주문 날짜의 월이 필요합니다.
don't need the whole order dates we need the month of the order dates so like this we don't need of course
6:46:44
주문 ID는 필요하지 않습니다. 이제 이 차원으로 데이터를 그룹화해야 합니다.
the order id but now we need to group up the data using this dimension the month order dates
6:46:51
그게 다입니다. 실행해 봅시다.
so that's it let's go and execute it so
6:46:55
이제 출력에서 3개월이 보이고 각 월마다
now in the output you can see we have three months and for each month
6:46:58
평균 배송 기간이 있습니다.
we have the average shipping durations in days
6:47:01
첫 번째 월은 약 7일입니다.
so for the first month it is around seven days
6:47:04
2월도 7일이고 3월은 5일로 기간이 짧습니다.
for february is as well seven days and for march we have less duration five days so with that we have solved the task as you can see the date diff is very strong function
6:47:14
날짜 정보를 사용하여 데이터 분석을 수행해야 합니다. 알겠습니다.
in order to do data analytics using the dates information. All right.
6:47:18
이제 다음 작업이 있습니다. 각 주문과 이전 주문 사이의 일수를 찾으세요.
So now we have the following task and it says find the number of days between each order and the previous order.
6:47:24
여기에서 많은 일이 일어나고 있습니다. 단계별로 진행합시다.
So there is a lot of stuff going on over here. Let's do it step by step. Let's start by selecting the basic stuff.
6:47:30
주문 ID 또는 판매 주문 테이블에서 날짜를 선택하세요.
So select order ID or the dates from the table sales orders.
6:47:37
실행해 봅시다. 10개의 주문과 현재 주문 날짜가 있습니다.
Let's go and execute it. So we have our 10 orders and we have the current order dates.
6:47:42
이제 두 주문 날짜 사이의 차이를 찾아야 합니다.
so now we have to find the differences between two dates order dates
6:47:45
현재 주문 날짜와 이전 주문 날짜입니다.
the current one and the previous order dates
6:47:48
현재 주문 날짜는 있지만 각 주문에 대한 이전 주문 날짜는 없습니다.
so in our data we have the current order dates but we don't
6:47:51
각 주문에 대한 이전 주문 날짜가 없습니다.
have the previous order date for each order and
6:47:54
이전 주문 날짜를 계산하기 위해서 기억하나요?
in order to calculate the previous one do you remember about the
6:47:58
윈도우 함수를 사용하여 지연을 사용할 수 있습니다.
window functions we can go and use the lag in order
6:48:01
이전 기록의 값을 접근하기 위해서입니다.
to access a value from a previous records
6:48:04
주문 날짜를 호출할 것입니다.
so let's go and do that the order date i'm just gonna call
6:48:07
현재 주문 날짜를 찾고 있습니다.
it current order dates and let's go and
6:48:10
주문 날짜의 이전 주문 날짜를 찾고 있습니다.
find the previous order dates so we're gonna go with the lag
6:48:13
주문 날짜의 값에 관심이 있습니다.
of the order dates because we are interested
6:48:17
데이터를 정렬해야 합니다.
in the value of the order dates now over we
6:48:20
주문 날짜의 이전 값을 접근하는 데 도움이 됩니다.
have to sort the data so we're gonna sort it by the order date as well so this is gonna help us always to access
6:48:29
이전 주문 날짜라고 부를 것입니다.
the previous value of the order date so we're
6:48:32
이전 주문 날짜를 실행하고 결과를 확인해 봅시다.
gonna call it previous order dates
6:48:35
첫 번째 주문에 대해 이전 데이터가 없습니다.
let's go and execute it and let's check the results for the
6:48:38
두 번째 기록에 대해 null이 발생합니다.
first order we don't have anything previously so that's why we are getting
6:48:41
현재 주문 날짜는 1월 5일입니다.
a null for the second record the current order date
6:48:45
이전 주문 날짜는 1월 1일입니다.
is the 5th of january and the previous one is
6:48:48
이전 주문이 훌륭합니다.
the first of january and this value comes from the previous record
6:48:52
현재 날짜와 이전 날짜 사이의 일수를 찾을 수 있습니다.
the previous order great amazing so with that we have
6:48:55
놀라운 날짜 함수로 할 수 있습니다.
now the two dates the current date and the previous one and now we can go very simply finding the number of days between those two dates
6:49:03
우리는 일수에 관심이 있습니다.
and we can do using the amazing function date
6:49:06
시작일이 무엇인지 확인해야 합니다.
diff so we are interested on the days that's
6:49:09
이전 주문 날짜를 확인할 수 있습니다.
why it's going to be the day so what is the starting day if
6:49:13
시작 날짜이므로 전체를 가져올 것입니다.
you check those two dates you can see that the previous order date
6:49:16
전체 윈도우 함수를 사용하여 적용할 것입니다.
is the starting date so we're going to take the whole
6:49:19
여기서 이전 주문 날짜를 확인할 수 있습니다.
thing the whole window function and put it over
6:49:22
여기서 나는 내 사진을 옮겼고, 이전 주문 날짜와 현재 주문 날짜가 무엇인지 보여줍니다.
here so i just moved my picture so here is the previous order dates and now the end date what's going to be it's going to be the current order date which is our order date like this.
6:49:33
다시 말해, 우리는 이전 날짜와 현재 날짜 사이의 일수를 찾고 있습니다.
So again, we are finding the number of days between the previous dates and the current dates.
6:49:39
그게 다입니다. 이제 닫아봅시다. 나는 이것을 일수라고 부를 것입니다.
So that's it. Let's close it. So I'm just going to call it number of days.
6:49:44
이제 실행해봅시다. 물론 여기에는 null이 있습니다. 따라서 출력에서도 null을 받게 될 것입니다.
So let's go and execute it. Now, of course, we have here null. So we will get as well null in the output.
6:49:51
이제 여기에서 두 날짜 사이의 일수가 정확히 4일인 것을 확인할 수 있습니다.
And now you can check over here how many days between those two dates we have for exactly four days.
6:49:55
그리고 다음 것에 대해서는 약 5일이 있습니다.
And as well for the next one, we have around five
6:49:58
10일과 그 외에도 우리는 작업을 해결했습니다.
days, 10 days and so on so we have solved the task
6:50:01
이제 각 주문 사이의 일수를 알게 되었습니다.
we have now the number of days between each order
6:50:04
그리고 이전 주문과 이 분석 유형은 매우 중요합니다.
and the previous order so this type of analysis is very
6:50:07
우리는 이를 시간 간격 분석이라고 부릅니다.
important in the business we call it time gap analysis and
6:50:11
우리는 윈도우 함수와 날짜 함수인 date diff의 도움을 받아 이를 수행했습니다.
we have done it using the help of the window function and as well the date function date diff so date diff function is amazing function to do data analysis all right so those two functions we have learned how to do
6:50:24
date diff 함수는 데이터 분석을 수행하는 데 놀라운 함수입니다.
mathematical operations on date information or we can call it date calculations.
6:50:27
이제 가장 쉽고 마지막 그룹으로 넘어가겠습니다. 날짜 유효성 검사입니다.
Now, moving on to the easiest and the last group, we have that date validation. And here we have only one function that is dates.
6:50:38
여기에는 단 하나의 함수, 즉 dates가 있습니다.
Okay, so what is is dates? So the is date is very simple. It's going to check whether a value is a date.
6:50:44
그렇다면 is dates는 무엇인가요? is date는 매우 간단합니다.
So it can return one if the string value is a valid dates or a zero if it is not a valid date.
6:50:52
값이 날짜인지 확인합니다.
Okay, so let's check quickly the syntax of the isDate. It's very simple. The keyword isDate is the function name and it accepts only one value.
6:50:58
문자열 값이 유효한 날짜이면 1을 반환하고, 유효하지 않으면 0을 반환할 수 있습니다.
So for example, you can pass a string like this and you can ask SQL, is it a date? So isDate and the value.
6:51:05
isDate의 구문을 빠르게 확인해봅시다. 매우 간단합니다.
And of course, for this example, you will get true or one.
6:51:08
isDate는 함수 이름이며, 단 하나의 값만을 허용합니다.
So you can see we are passing here a string value and we are validating whether it is good enough to be a date or as well, you can go and specify a number like year 2025.
6:51:17
예를 들어, 이렇게 문자열을 전달하고 SQL에 날짜인지 물어볼 수 있습니다.
So is this value a date? and of course SQL
6:51:21
그래서 isDate와 값을 사용합니다.
gonna accept it and say yeah this is a year so you will get as well
6:51:24
물론 이 예제에서는 true 또는 1을 받을 것입니다.
a one so you can pass as well a number or integer so you
6:51:27
여기서 문자열 값을 전달하고 그것이 날짜로 적합한지 검증하고 있습니다.
are just checking the values whether they are suitable
6:51:30
또한 2025년과 같은 숫자를 지정할 수도 있습니다.
enough to be a date so that's all about the syntax of the is date
6:51:33
이 값이 날짜인지 확인해보겠습니다.
okay so now let's have few examples for example let's go and select and
6:51:36
우리는 날짜라고 말할 것이고 값을 확인할 것입니다.
we're gonna say is date and we will check a value so
6:51:39
이 값이 문자열 '일 이 삼'이라고 가정해 봅시다. 날짜 확인 1이라고 부르겠습니다.
let's say this value is a string one two three let's go and call it date check one let's go and
6:51:47
이제 출력에서 '아니오, 날짜가 아닙니다'라고 표시될 것입니다.
excuse it now in the output is going to say no it is
6:51:50
날짜가 아니기 때문에 우리는 값 0을 얻고 있습니다.
not a date and that's why we are getting the value zero which
6:51:53
정확합니다. '일 이 삼'은 날짜가 아닙니다. 다른 값을 선택합시다.
is correct because one two three is not a date let's
6:51:56
동일한 방식으로 날짜를 선택하고 이제
pick another value the same thing is dates and now the
6:51:59
값은 다음과 같습니다. 2025년 8월
value gonna be the following so 2025 august
6:52:03
20일로 날짜 확인이라고 부르겠습니다.
20 so let's call it date check
6:52:07
두 번째로 가서 이제 출력에서 1이 나올 것입니다. 이는 제공된 값이 날짜임을 의미합니다.
two and let's go and excuse it now in the output we will get one that means the value
6:52:13
제공된 값이 날짜이기 때문에 출력에서 1이 나옵니다.
that we have provided is a date and that's why we have
6:52:16
이제 또 다른 예를 들어 보겠습니다. 전체를 가져가겠습니다.
a one in the output because sql is saying this is a date
6:52:19
이제 또 다른 예를 들어 보겠습니다. 전체를 가져가겠습니다.
now let's have another example we're gonna take the
6:52:22
이것은 체크 3입니다.
whole thing so this is a check three
6:52:25
여기서 이것을 제거하고 형식을 변경하고 싶습니다.
and remove this from here but i would like to go and change the format so
6:52:29
하루, 그 다음 달, 그리고 그 다음 해로 시작한다고 가정해 봅시다.
let's say that we start with a day then month and then the
6:52:32
이제 출력에서 0이 보일 것입니다. SQL이 형식을 이해하지 못하기 때문입니다.
year let's go and check now in the output you can see it is zero because sql does not understand the formats so we are not following the standard
6:52:40
데이터베이스와 SQL의 형식이기 때문에 '아니오, 날짜가 아닙니다'라고 표시될 것입니다.
format of the database and SQL and that's why it's going to say
6:52:43
이것은 문자열과 같습니다.
no this is not a date this is like a string
6:52:47
값이 상태 형식을 따를 때만 SQL이 이해할 수 있습니다.
value so this means only if the value is following the
6:52:50
이것이 날짜입니다.
status format SQL can understand this is a date
6:52:53
이제 또 다른 것을 확인해 보겠습니다. 예를 들어, 날짜가
now let's go and check another thing for example let's say it's
6:52:56
연도만 가져가고 2025년으로 하겠습니다.
dates and let's have only the year so 2025
6:52:59
이름을 날짜 확인 4라고 부르겠습니다.
and let's give it the name date check four
6:53:03
이제 실행해 보겠습니다. 출력에서 1이 나올 것입니다. 이는 SQL이 이 값을 날짜로 간주한다는 의미입니다.
let's go and execute it now in the output we will get one so that means SQL considering this value as a date
6:53:10
SQL이 이해할 만큼 똑똑하다는 의미입니다. 제공된 연도 정보가 있으며 SQL이 이를 수용할 수 있습니다.
So that means SQL is smart enough to understand, okay, we have provided a year information and SQL can accept it and say, okay, maybe this is the 1st of January of 2025.
6:53:19
이제 같은 작업을 월에 대해서 해보겠습니다. SQL이 이를 수용할 수 있는지 확인해 보겠습니다.
Now let's go and do the same thing, but for the month. Let's see whether SQL can accept it.
6:53:25
5를 확인해보니 8월입니다. 확인해 보겠습니다.
So check five and we have the month of August. Let's go and check.
6:53:30
이제 SQL은 '아니요, 이 값을 이해할 수 없습니다. 이것은 제로입니다.'라고 말할 수 있습니다. 즉, 제공된 값은 날짜가 아닙니다.
Now SQL can say, no, I don't understand this value. This is zero. So that means this value is provided is not a date.
6:53:37
결과를 확인해보면, SQL은 표준 형식만 이해하고 연도가 날짜인지 확인할 수 있도록 허용합니다.
So by checking those results, as you can see, SQL understand only the standard formats and it allow you as well to check whether a year is a date.
6:53:45
이것이 SQL에서 날짜가 작동하는 방식입니다. 이제 여러분은 '언제 이 작업을 할 것인가?'라고 물어볼 수 있습니다.
So this is how the is date works in SQL. And now you might ask, well, when I'm going to do this, when I'm going to check whether the value is a date or not.
6:53:51
다음 시나리오를 제시하겠습니다. 이제 다음 날짜가 있다고 가정해 보겠습니다. 문자열로 네 개의 값을 가지고 있습니다.
Let me give you this following scenario. Now, imagine that we have the following date. So we have four values as a string.
6:53:57
이제 데이터를 확인하면 표준 형식을 따르고 있지만 값에 문제가 있을 때만 그렇습니다.
And now if you check the data, you can see that we are following the standard formats, but only when value has an issue.
6:54:04
여기 데이터 품질 문제가 있습니다. 이제 우리가 하고 싶은 것은 이 문자열 값을 날짜로 변환하는 것입니다.
So we have here data quality problem. So now what we want to do, we want to go and cast this string value to a date.
6:54:10
이 문자열 값이 그대로 남아있기를 원하지 않습니다. 최종 결과에서 날짜로 가져오고 싶습니다.
We don't want this to stay as a string value. We would like to have it in the final result as a date.
6:54:16
우리가 일반적으로 하는 것은 이러한 값 위에 서브 쿼리를 만드는 것입니다. 이렇게요.
So what we usually do is that we go and have like sub query on top of those values. So like this.
6:54:22
이제 우리가 할 것은 주문 날짜를 날짜로 변환하고 싶다고 말하는 것입니다.
So now what we're going to do, we're going to go and say we would like to go and cast the order dates as dates.
6:54:28
문자열로 원하지 않으며, 이 값들에서 모든 날짜를 호출할 것입니다.
We don't want it as a string and we're going to call it all the dates from these values.
6:54:34
이렇게 만들겠습니다. 이제 실행해 보겠습니다.
So let me just make it like this. And so let's go and execute it.
6:54:39
이제 오류가 발생하고 '모든 것을 날짜로 변환할 수 없습니다. 아마도 손상된 데이터가 있습니다.'라고 말할 것입니다.
Now, it's going to give you an error and say, well, I cannot convert everything to date because you have maybe corrupt data.
6:54:45
물론 이것은 이 행 때문입니다. SQL은 이 문자열을 날짜로 변환할 수 없습니다.
And this is, of course, because of this row. So SQL is not able to convert this string to a date.
6:54:52
물론 지금 예시는 매우 간단합니다. 우리는 그것을 알고 있습니다. 그러나 큰 테이블이 있다면 이러한 문제를 식별하기가 정말 어려울 것입니다.
But of course, now the example is very simple. We know that. But if you have a huge table, it's going to be really hard to identify those issues.
6:54:59
하지만 이제 여전히 이 값을 변환하고 싶습니다.
But now still, I would like to go and convert those value here i
6:55:03
오류가 발생하지 않기를 원하며, 이제 일부 값이 있을 경우
don't want to get an error and now if there is like some values like
6:55:06
여기 손상된 값이 있고 이 값은
here that is corrupt and so on this value could be
6:55:09
null 그래서 SQL이 문자열을 날짜로 변환하도록 강제할 수 있는 방법은 무엇인가요?
null so how we can force sql to convert
6:55:12
데이터 유형을 문자열에서 날짜로 변환하고 이것을 주지 않도록 하는 방법입니다.
the data type from string to date and not give us this
6:55:15
오류가 발생하지 않도록 하기 위해 우리는 is date 함수의 도움을 사용할 수 있습니다. 제가 보통 어떻게 하는지 보여드리겠습니다. 그러니 가서 주문 날짜가 날짜인지 확인해 봅시다.
error and for this we can go and use the help of the function is date let me show you how i usually do it so let's go and say let's Let's check whether the order date is a date.
6:55:26
그러니 이렇게 해봅시다. 그리고 이제 실행하기 전에, 이것을 주석으로 만들겠습니다.
So let's have it like this. And now before we go and execute, I'm going to make this as a comment.
6:55:31
왜냐하면 이렇게 실행하면 오류가 발생할 것이기 때문입니다. 그리고 우리의 선택에서 주문 날짜를 가져옵시다.
Because if I execute it like this, we will get an error. And let's go and get the order date in our select.
6:55:37
그러니 가서 실행해 봅시다. 이제 출력에서 보시다시피, 우리는 문자열 값을 가지고 있습니다. 그래서 아직 날짜가 아닙니다. 그리고 우리의 확인 결과가 있습니다.
So let's go and execute it. Now as you can see in the output, we have our string value. So they are not yet a date. And we have the result of our check.
6:55:44
그래서 보시다시피 첫 번째 행에서 우리는 0을 얻고 있습니다. SQL은 이 값이 날짜가 아니라고 말하고 있습니다.
So as you can see, the first row, we are getting a zero. So SQL saying this value is not a date.
6:55:50
하지만 다른 모든 값에 대해서는 1을 얻고 있습니다. 그래서 그들은 검사를 통과하고 날짜입니다.
But for all other values, we are getting one. So they are passing the check and they are dates.
6:55:54
이제 여러분이 할 일은, 값을 문자열에서 날짜로 변환하라고 말하는 논리를 구축하는 것입니다. 플래그 또는 체크가 1과 같을 때만 변환하도록 하겠습니다.
So now what you're going to do, we're going to go and build a logic where we're going to say, go and cast the value from string to date only if the flag or the check is equal to one.
6:56:05
그래서 이는 우리가 case when 문을 사용할 수 있다는 것을 의미합니다. 어떻게 하는지 보여드리겠습니다. 단계별로 진행해 보겠습니다.
So that means we can go and use the help of the case when statements. Let me show you how we can do that. So let's do it step by step.
6:56:12
우리는 case when이라고 말할 것입니다. 이제 체크가 필요합니다. 주문 날짜가 날짜인지 확인합니다.
We're going to say case when now we need the check. So is dates the order date.
6:56:19
이 체크의 출력이 1과 같다면, 변환을 허용합니다.
So if the output of this check is equal to one, then you are allowed to do the casting.
6:56:23
이 체크의 출력이 1과 같지 않다면, null로 남아 있을 수 있습니다. 테스트를 통과하지 못했다면 null로 두겠습니다.
So let's go and get the cast as a result of this condition.
6:56:27
그래서 우리는 이것의 결과로 변환을 가져올 것입니다.
And if it's not equal to one, then it could stay as a null. So let's have it as a null if it didn't pass the test.
6:56:33
이 값이 1과 같지 않다면, null로 남아 있을 수 있습니다. 테스트를 통과하지 못했다면 null로 두겠습니다.
So and we can call it a new order dates. So now let's go and execute it.
6:56:39
그래서 우리는 새로운 주문 날짜라고 부를 수 있습니다. 이제 실행해 보겠습니다.
Now, as you can see, we are not getting error from SQL.
6:56:42
이제 보시다시피 SQL에서 오류가 발생하지 않습니다.
So now if you take the output for the invalid dates, we are getting a null. So we are not getting an SQL error.
6:56:48
이제 유효하지 않은 날짜에 대한 출력을 가져오면 null을 얻고 있습니다. SQL 오류가 발생하지 않습니다.
And now only if these string values are valid dates, it's allowed to be casted.
6:56:53
이 문자열 값이 유효한 날짜인 경우에만 변환이 허용됩니다.
So with that, you can go and cast a string value to a date, even though that you have bad data quality.
6:56:59
이것으로 문자열 값을 날짜로 변환할 수 있습니다. 데이터 품질이 나쁘더라도 가능합니다.
And this is very important step in order to prepare the data before doing analyzes. And it helps us as well to find data quality issues.
6:57:06
데이터를 분석하기 전에 준비하는 데 매우 중요한 단계입니다. 데이터 품질 문제를 찾는 데도 도움이 됩니다.
So for example, we can go over here and say, you know what, let's go and search for all issues. So we're going to go and take the is date.
6:57:13
예를 들어, 여기서 모든 문제를 검색하자고 말할 수 있습니다. 그래서 우리는 is date를 가져올 것입니다.
So let's go and and get the check and i'm gonna say let me see
6:57:16
그래서 체크를 가져오고, 제가 보겠습니다.
all string values that are invalid that are failing the
6:57:20
유효하지 않은 모든 문자열 값이 실패하고 있습니다.
test so let me execute it and with that we are getting this record
6:57:23
테스트를 실행해 보겠습니다. 그러면 이 레코드를 얻고 있습니다.
and now imagine we have a lot of data so it's now it's really easy
6:57:26
이제 많은 데이터가 있다고 상상해 보십시오. 이제 정말 쉽습니다.
to identify those issues by just using the s
6:57:29
이 문제를 식별하는 것은 매우 쉽습니다.
date so this is as well amazing way in order to identify data
6:57:33
이렇게 해서 데이터 품질 문제를 식별하는 놀라운 방법입니다.
quality issues now of course you might say you know what i don't want to see here null maybe let's get a dummy value well it's very easy we
6:57:39
물론 여러분은 여기서 null을 보고 싶지 않다고 말할 수 있습니다. 더미 값을 가져오자고 할 수 있습니다.
go over here and say else so and we can go and get for example very large value something like this
6:57:47
그래서 우리는 여기서 else라고 말하고, 예를 들어 매우 큰 값을 가져올 수 있습니다.
that is easy to identify so now with that instead of getting nulls
6:57:50
이것은 식별하기 쉽습니다. 이제 null 대신에 이러한 더미 값을 얻을 수 있습니다.
inside your data you can get such a dummy value so
6:57:53
이제 sdates의 사용 사례와 이 함수의 이유를 이해했습니다.
now you understand the use case of the sdates and why this function
6:57:56
데이터 정리를 하는 데 이 함수가 얼마나 놀라운지.
is amazing doing data cleanup all
6:58:03
그렇다면 우리는 13가지의 날짜 및 시간 기능을 다뤘습니다.
right so with that we have covered 13 different date and time
6:58:07
SQL에서 날짜 부분을 추출하는 방법을 배웠습니다.
functions in sql so we have learned how to extract the
6:58:10
우리는 어떤 것을 언제 사용해야 하는지도 배웠습니다.
date parts using seven different functions and we have
6:58:13
데이터 집계와 필터링을 수행하기 위해서입니다.
learned as well when to use which one so they are amazing in order
6:58:16
하나의 날짜 형식을 다른 형식으로 변경하는 방법을 배웠습니다.
to do data aggregations and as well filtering and
6:58:19
또한 데이터 유형을 변경하는 방법도 배웠습니다.
then we have learned how to change the date format from one
6:58:22
우리의 날짜에 대해 수학적 연산을 수행하는 방법을 배웠습니다.
to another and as well how to change the data types and then
6:58:25
날수를 더하거나 빼는 방법입니다.
we learned how to do mathematical operations on our dates
6:58:29
날짜에서 연도와 월을 더하거나 빼는 방법입니다.
so how we can add or subtract days
6:58:32
우리가 차이를 찾을 수 있는 날짜 차이 함수입니다.
years months from a date or the amazing function
6:58:35
두 날짜 사이의 일수 또는 연수를 찾을 수 있습니다.
the date diff where we can go and find the differences
6:58:38
우리가 가진 값이 날짜인지 확인할 수 있습니다.
in days or years between two days and the last
6:58:41
날짜인지 아닌지를 검증할 수 있습니다.
one we can go and validate whether the values that we have are
6:58:44
데이터 분석을 수행하기 위한 놀라운 함수들입니다.
dates or not so as we learned date functions are
6:58:47
보고서를 작성하기 위한 함수들입니다.
amazing functions in order to do data analysis and
6:58:51
SQL에서 날짜와 시간 값을 조작하는 방법에 대해 배웠습니다.
reporting all right my friends so with that we have learned a lot of
6:58:54
이제 다음 섹션에서는 NULL 함수에 대해 이야기할 수 있습니다.
very important sql functions on how to manipulate the
6:58:57
NULL이란 무엇인가요? 포럼을 작성하고 있다고 상상해 보세요.
date and time values in your database using sql now in the next section we can start talking about the null functions in order to handle the nulls inside your tables so let's go
6:59:11
필수 입력 필드와 선택 입력 필드가 있습니다.
so what are the nulls imagine you are filling out a forum and
6:59:15
선택 필드는 보통 답변하지 않고 비워둡니다.
there will be usually like fields that are required and another
6:59:18
양식을 작성하고 등록을 클릭하면 데이터가 데이터베이스 테이블에 삽입됩니다.
fields that are optional so what usually happens we leave those optional fields unanswered so we don't provide any values and we leave it empty and now once we are done
6:59:28
답변과 값을 제공한 필드는 테이블에 채워지고, 답변하지 않은 필드는 값이 없습니다.
When filling out the form and we click on register, the data will be inserted into database tables.
6:59:33
데이터베이스에서 NULL은 아무것도 없음을 의미합니다.
So now what can happen, the fields where we have provided answers and values can be filled inside the table while the unanswered fields will have no value and this is what we call in SQL, a null.
6:59:45
데이터베이스에서 null은 아무것도 없음을 의미합니다.
So in databases, null means nothing, unknown.
6:59:48
그것은 어떤 것과도 같지 않으며, 0이나 빈 문자열, 공백과도 같지 않습니다.
It is not equal to anything, so it is not equal to zero or empty string or blank space.
6:59:55
null은 단순히 아무것도 아닙니다. 값이 없음을 알려줍니다.
Null is simply nothing. It tells us there is no value and it is
7:00:00
이것은 내가 이 값이 무엇인지 모르겠다고 말하는 것과 같습니다.
It's like saying, I don't know what this value is. So this is what a null means in SQL.
7:00:10
좋아요, 친구들. 이제 데이터 내 null을 처리하는 특별한 SQL 함수에 대해 깊이 파고들겠습니다.
All right, friends. So now we're going to do a deep dive into special SQL functions on how to handle the nulls inside our data.
7:00:17
어떤 시나리오에서는 테이블에 null이 있고, 이를 제거하고 새로운 값으로 교체하고 싶습니다.
Now, in some scenarios, we have nulls inside our tables, and we would like to go and remove it and replace it with a new value, like, for example, 40.
7:00:26
SQL에서는 이를 위해 두 가지 함수가 있습니다. 첫 번째는 null이고 두 번째는 coalesce입니다.
And in order to do that, in SQL, we have two functions. The first one called is a null and the second one called coalesce.
7:00:33
이제 테이블에 40과 같은 값이 있고 이를 null로 만들고 싶다고 가정해 보겠습니다.
But now let's say that we have another scenario where we have a value inside our table like the 40 and we want to go and make it as a null.
7:00:40
이제 우리는 정반대의 작업을 하고 있습니다. 값을 null로 교체하고 있습니다.
So now we are doing the exact opposite. We are replacing the value with a null.
7:00:45
이를 위해 SQL 함수 null if가 있습니다. 두 시나리오에서 우리는 항목을 교체하고 있습니다.
And for that, we have the SQL function null if. So as you can see, with those two scenarios, we are replacing stuff.
7:00:51
null에서 값으로 또는 값에서 null로.
So from null to value or from value to null.
7:00:55
이들은 데이터베이스 내 데이터를 조작하는 데 매우 유용합니다.
So they are really helpful in order to manipulate the data inside our databases.
7:01:00
이제 아무것도 조작하지 않고 확인만 하고 싶습니다.
Now moving on to another scenario where we don't want to manipulate anything. We want just to check. So we don't want to replace or convert anything.
7:01:07
데이터베이스에서 null 값이 있는지 확인하고 싶습니다. 이를 위해 isNull이라는 함수가 있습니다.
We want just to check in our database whether we have a null value. And for that we have a function called isNull.
7:01:14
is와 null 사이에는 공백이 있습니다. 이는 첫 번째 함수와 다릅니다.
But between the is and null there is like space. It is different than the first function. So if you apply isNull you're gonna get a Boolean.
7:01:21
이 시나리오에서는 true를 얻을 것입니다. 두 번째 옵션으로 값이 null이 아닌지 확인할 수 있습니다.
True or false. For this scenario you will get true. Or the second option, you can go and check whether the value is not null.
7:01:27
is not null을 사용할 수 있습니다. 이 예에서는 false를 얻을 것입니다.
So we can use is not null. And for this example, you're going to get false. So in the output, we are getting a Boolean, true or false.
7:01:34
이 키워드는 데이터 내 null을 확인하는 데 정말 놀랍습니다.
So those keywords are really amazing in order to check whether we have nulls inside our data.
7:01:40
이것은 SQL에서 null을 처리하기 위한 모든 함수의 큰 그림입니다.
So this is the big picture of all functions that we have in SQL in order to handle the nulls.
7:01:45
이제 이러한 함수들을 하나씩 이해해 보겠습니다.
So now let's go and understand those functions one by one. So let's start with the first function is null.
7:01:54
is null은 null을 특정 값으로 교체하지 않습니다. 구문은 매우 간단합니다.
is not going to go and replace a null with a specific value. Now, the syntax of the is null is very simple.
7:02:01
is null 키워드를 사용하고 두 개의 인수를 받습니다.
We're going to use the keyword is null and it accepts two arguments. First, the value and then the second, the replacement value.
7:02:08
예를 들어, shipping address라는 열에 대해 is null을 사용할 수 있습니다.
So let's have an example. We can go and use the is null for the column called shipping address. So we are checking the nulls inside it.
7:02:15
SQL이 null을 만나면 이를 unknown 값으로 교체합니다.
And if SQL encounters any null, it's going to go and replace it with the value unknown.
7:02:20
이것은 null에 대한 기본값이 될 것입니다.
So this is going to be like a default value for the nulls.
7:02:24
따라서 첫 번째 값은 열이고 두 번째 값은 항상 알 수 없는 값이 됩니다.
So the first value is a column and the second value is like static, always going to be the unknown if we find any nulls.
7:02:31
물론 다른 시나리오에서는 항상 알 수 없는 값으로 두고 싶지 않습니다.
Now, of course, in other scenarios, we don't want to have it always like the unknown.
7:02:35
우리는 첫 번째 열을 도와줄 다른 열을 사용하고 싶습니다.
We would like to use another column to help the first one. So let's have this scenario.
7:02:41
이제 이 구문으로 배송 주소의 값을 확인하고 있습니다.
So now with this syntax, we are checking the values of the shipping address.
7:02:44
그리고 null을 찾으면 청구 주소에서 대체 값을 가져옵니다.
And if we find any nulls, it's going to get the replacement from the billing address.
7:02:49
이 예제에서는 두 개의 열이 있습니다. 여기에는 고정 값이 없습니다.
So here in this example, we have two columns. We don't have here any static value.
7:02:54
배송 주소가 null인 경우에만 청구 주소의 값을 가져옵니다.
We will get the values of the billing address only if the shipping address is null.
7:02:59
따라서 다른 열의 도움으로 null을 대체하고 있습니다.
So we are replacing the nulls using the help of other column.
7:03:03
첫 번째 시나리오에서는 null을 고정 값으로 대체하고 있습니다.
And in the first scenario, we are replacing the nulls with a static value, the default value.
7:03:09
이것이 어떻게 작동하는지 배우기 위해 아주 간단한 예를 들어 보겠습니다.
So let's have a very simple example in order to learn how this works. So what we are doing, we are checking whether the value is null.
7:03:15
값이 null인지 확인하고 있습니다.
If it's yes, then we're going to go and get the value from the replacement.
7:03:19
그렇다면 대체 값에서 값을 가져오겠습니다.
and if the value is not null then show the value
7:03:22
값이 null이 아니면 그 값을 표시합니다.
itself so we have the following example we are going to check the
7:03:25
우리는 배송 주소에서 값을 확인할 것입니다.
values from the shipping address and if there is nulls
7:03:28
null이 있으면 기본 값으로 대체합니다.
then go replace it with the default value in a so
7:03:32
SQL이 이 간단한 예제를 실행하는 방법을 봅시다.
let's see how sql is going to go and execute this very simple example we
7:03:35
두 개의 주문이 있습니다. 첫 번째 주문의 배송 주소를 확인하고 있습니다.
have two orders the first order we are checking the shipment
7:03:38
주소의 값이 null입니다.
address is the value of this address is null
7:03:41
아니요, 값이 있으므로 SQL은 동일한 값을 반환합니다.
well no we have a value a so that's why sql is going to go and return the same value so in the
7:03:48
출력에서 값을 얻을 수 있습니다.
outputs we will get a so if it's not null
7:03:51
이제 두 번째 주문으로 이동합니다.
it can return the same value so now it's going to move to the second
7:03:55
여기 배송 주소가 null입니다.
order and here we have the shipment address as a null
7:03:58
값이 null이면 대체 값을 가져옵니다.
so what can happen here if the value is null then we're going to get the replacement value so what is the replacement value is the na
7:04:06
출력에서 null을 얻지 않을 것입니다.
so that's why in the output we will not get
7:04:09
우리는 기본 값을 얻을 것입니다.
a null we will get the na so if you check the result what happens we're going to get the addresses from the shipping address but only if we have a null
7:04:18
기본값을 얻을 것입니다. 이것이 중요합니다.
we will get like default value it's very important to understand if
7:04:21
출력에서 기본값을 사용하고 있다면
you are using the default value in the output you
7:04:24
null을 얻지 않을 것입니다. 자, 다른 예를 들어봅시다.
will never get a null all right so let's have another example for
7:04:27
기본값을 사용하지 않는 두 번째 시나리오에서
the second scenario where we are not using a default value we
7:04:31
열을 사용하고 있습니다. 지원 열이 있습니다.
are using a column so we have a supportive column that's going to be
7:04:34
확인할 것입니다. 이 시나리오에서는 배송 주소와 청구 주소가 null인지 확인합니다.
checked so in this scenario we are saying is null shipping address and billing address so we have two columns and of course the logic can be the same right so we are checking
7:04:43
한 번만 확인하겠습니다. 이 예제가 어떻게 실행될지 봅시다.
only once let's see how is going to execute this example
7:04:46
이번에는 세 개의 주문이 있고 주소가 있습니다.
we have this time three orders and we have addresses from the
7:04:49
배송과 청구에서 주소를 가져옵니다. SQL은 항상
shipments and as well from billing so now sql is always
7:04:52
배송 주소에 초점을 맞추고 있습니다. 첫 번째 열이기 때문에
focusing on the shipping address since it is the first column so we are not checking the billing address at all so it starts with the first
7:04:59
주문이 null인지 확인합니다. 아니요, 값이 있습니다.
order is it null well no we have the value
7:05:02
그래서 출력에서도 얻을 수 있습니다. SQL은 청구 주소에서 아무것도 얻지 않습니다.
a so we will get it as well in the output and sql will not get anything from the billing address so we will get a so that's it for the first order
7:05:12
이제 SQL은 두 번째 주문으로 이동할 수 있습니다.
now sql can go to the second order and this time we're gonna have
7:05:15
null입니다. 규칙에서는 배송 주소가 null이면
a null so now in the rule we are saying if the shipping address is a null go get the value from the billing address so this time
7:05:23
청구 주소에서 값을 가져가라고 합니다.
gonna go to the replacement right so we will get the value
7:05:27
출력에서 c를 얻을 것입니다. 배송 주소가
c in the output because the shipping address
7:05:30
null입니다. 이제 세 번째 행으로 이동합시다.
is null now let's move to the third row as you can see here we have
7:05:33
다시 null입니다. 그래서 값을 가져올 것입니다.
again null so it's good gonna go and get the value
7:05:36
청구 주소에서 값을 가져옵니다. 하지만 이 시나리오에서는
from the billing address but here in this scenario the
7:05:40
청구 주소도 null입니다. 그래서 우리는
billing address is as well null that's why we
7:05:43
출력에서 null 값을 얻을 것입니다.
will get the value null in the output so as
7:05:46
세 번째 주문에서 항상 값이 있을 것이라는 보장이 없습니다.
you can see having the replacements values from a column there is no guarantee that there will be always a value Like here in the third order, it is a null.
7:05:56
그래서 null도 출력에서 얻을 것입니다.
That's why we will get null as well in the output. So if you think you are using isNull to replace all the nulls by having two columns,
7:06:04
정적 값을 사용해야 합니다.
you might end up as well having a null in the output if the replacement having nulls.
7:06:09
SQL이 isNull을 실행하는 방법입니다.
So if you want to make sure you don't get any nulls in the output, you have to go and use a static value.
7:06:15
그래서 SQL이 isNull을 실행하는 방식입니다. 모든
So this is how SQL executes the isNull. all
7:06:22
그렇다면 coalesce는 무엇인가요? coalesce는
right so what is coalesce coalesce is gonna go and return
7:06:25
첫 번째 비어 있지 않은 값을 반환합니다.
the first non-null value from a
7:06:28
모든 목록을 나열합니다. 이제 coalesce의 구문은
list all right so now the syntax of that coalesce is way
7:06:31
is null보다 더 나은데, 여기서는
better than the is null here it accepts like a
7:06:34
여러 값의 목록을 허용합니다. 예를 들어, 값 하나가 있습니다.
list of many values so here for example we have value one
7:06:37
둘, 셋, 넷, 다섯을 추가할 수 있습니다. 원하는 만큼 추가할 수 있습니다. 여기서 확인할 값의 목록을 만들고 있습니다.
two three you can add four five as much as you want so we are creating here a list of values to be checked so for example we
7:06:45
여전히 is null처럼 사용할 수 있습니다. 배송 주소가 있는 곳에서
still can use it like the is null where we have the shipping address
7:06:48
null을 정적 값으로 대체하는 곳입니다.
where we replace the null with static value
7:06:52
알 수 없는 값 또는 우리가 배운 대로 두 개의 열을 사용할 수 있습니다.
the unknown or as we learned we can go and use two columns
7:06:55
배송 주소와 청구 주소입니다. 지금까지는
shipping address and the billing address so so far it's like the
7:06:58
is null과 동일한 사용 사례이지만, 이제 호출 목록은
same use case as the is null but now of course the call list
7:07:01
단지 두 개로 제한되지 않고 세 개를 사용할 수 있습니다.
is not only limited to two we can go and use three
7:07:04
배송 주소를 확인하라고 말하고 있습니다. null이면 청구 주소를 확인하고, 그것도 null이면 마지막에
so we are saying go check the shipping address if it's null then go check the billing address if it's as well null then use at the end
7:07:12
기본값, 정적 값, 알 수 없는 값을 사용합니다. 보시다시피
the default value the static one the unknown so as you can see
7:07:15
cowlis로 두 개 이상의 값을 사용할 수 있습니다.
we can use more than two values with the cowlis okay
7:07:18
이제 cowlis를 이해하고 이것이 어떻게 작동하는지 알아봅시다.
so now let's understand the cowlis and how this works now
7:07:22
작업 흐름은 is null과 유사합니다. 이 예제에서는
the workflow is something similar to the is null so in
7:07:25
두 개의 열, 배송 주소와 청구 주소가 있습니다.
this example we have two columns shipping address and the billing address
7:07:29
목록으로 간주되며, 왼쪽에서 오른쪽으로 확인을 시작합니다.
it's going to consider it as a list and we're going to start checking from
7:07:32
배송 주소의 첫 번째 값을 확인할 것입니다. null인지 확인하고, 아니면
left to right so i'm going to check the first value from the shipping address whether it's null if no it's not
7:07:38
null이면 값을 가져올 것입니다.
null then we're gonna go and get the value one so we
7:07:41
배송 주소에서 값을 가져올 것이고, 만약 그렇다면
will get the value from the shipping address and if yes
7:07:44
null이면 값을 가져올 것입니다.
it is null then it's gonna go and get the value
7:07:47
두 개의 값을 가져올 것이고, 배송 주소에서 값을 가져올 것입니다. 이제 유사한 데이터가 있습니다. 세 개의 주문이 있습니다. 이스라엘이 어떻게 실행할지 봅시다.
two so we're gonna get the value from the shipping address now we have the similar data we have three orders let's see how israel gonna execute it so it's gonna start with the first row and it's gonna focus on the shipping address
7:07:58
여기서 값이 null이 아니므로 우리는 A로 설정합니다. 그래서 값을 1로 가져올 것입니다. 배송 주소에서 값을 가져오고 다른 것은 확인할 수 없습니다.
so here the value is not null so we have it as an a so that's why we will get the value one so we will get the value from the shipping address and nothing else can be checked.
7:08:10
이제 두 번째 행으로 넘어갑니다. 이번에는 배송 주소가 null입니다.
Now moving on to the second row this time the shipping address is null.
7:08:14
SQL은 두 번째 열에서 값을 가져올 것이고, 그 값은 C가 될 것입니다.
So SQL gonna go and get the value from the second column and it's gonna be the C right.
7:08:19
출력에서 우리는 C를 얻게 됩니다. 이제
So in the output we will get C. Now
7:08:22
마지막 예제로 넘어갑니다. 우리는 null로 설정되어 있고 SQL은
to the last example we have it as a null and SQL gonna go
7:08:26
두 번째 열에서 값을 가져올 것이고 이번에는
and get the value from the second column and this time
7:08:29
우리는 또한 null을 가져올 것입니다. null 함수처럼
we're get as well and null like that is null function
7:08:32
결과적으로 우리는 정확히 같은 결과를 얻고 있습니다.
so as the results we are getting exactly the
7:08:35
null이므로 이 시나리오에서는 상관이 없습니다.
same result as is null so for this scenario it doesn't matter
7:08:38
null이든 kawalis를 사용하든 상관이 없습니다. 이제 물론 우리는
whether you use is null or kawalis so now of course we are
7:08:41
여전히 그것에 만족하지 않습니다. 왜냐하면 나는 null을 보고 싶지 않기 때문입니다.
still not happy with that because i don't want to see any nulls
7:08:44
출력에서 여전히 청구 주소를 사용해야 합니다.
in the output and i will still need to use the billing
7:08:47
정적 값 대신 청구 주소의 모든 값을 가져오고 싶습니다. 그리고 기본 값도 원합니다.
address instead of any static values so i would like to have everything the values from the billing address and as well i would like to have at the and a default value so that I don't have any nulls in the output.
7:08:59
어떻게 해결할 것인가? 이제 우리는 하나의 함수에 여러 값을 포함할 수 있는 계정 목록의 힘을 사용할 수 있습니다.
So how are we going to solve it? So now we can use the power of the account list where we can include multiple values in one function.
7:09:06
우리가 할 일은 배송 주소를 먼저 가져오고, 그 다음에 청구 주소를 가져오고, 마지막에 기본 값을 가져오는 것입니다.
So what we're going to do, we're going to have the shipping address first, then the billing address, and at the end, we're going to have the default value.
7:09:13
이제 세 개의 값 목록이 생겼습니다. 물론 우리의 워크플로우는 조금 더 커질 것입니다.
So we have now a list of three values. And of course, our workflow is going to be a little bit bigger.
7:09:18
다시 말해, 여기서는 왼쪽에서 오른쪽으로 시작할 것입니다. 먼저 값 1을 확인할 것입니다.
So again, here it's going to start from the left to the right. So first, we're going to go and check the value one.
7:09:23
값이 null이면 값 2를 확인할 것입니다.
if it is null then it's gonna go as well checking the value
7:09:26
값 2도 null이면 마지막 값을 가져올 것입니다.
two and if the value two is as well null we will
7:09:30
마지막 값은 값 3이 될 것이므로 이제
get the last value it's gonna be the value three so now let's
7:09:33
새로운 coalesce를 사용하여 예제를 다시 실행할 것입니다.
run the example again using the new coalesce so the first
7:09:36
우리가 확인할 첫 번째 값은 배송 주소입니다.
thing we're gonna go and check the first value which is the shipping address
7:09:39
기록 번호 1에 대해 이제 값을 확인할 수 있습니다.
for the record number one so now as you can see the value is
7:09:42
null이 아니므로 우리는 여기서 A를 가지고 있습니다. 그래서 발생할 일은
not null so we have here an a so what's gonna happen we're gonna get the value a as well in the output so that means
7:09:49
이것이 활성화되고 우리는 아무것도 확인하지 않을 것입니다.
this one gonna be activated and we will not check anything
7:09:53
이것은 활성화될 것이고 우리는 다른 것을 확인하지 않을 것입니다
else so that means in the output it's gonna be like this and the first value is returned and everything else will
7:10:00
그래서 출력에서 이렇게 될 것이고 첫 번째 값이 반환되며 나머지는
be ignored so sql will not check anything so as you can see
7:10:03
무시될 것입니다
we are returning the first non-null
7:10:07
그래서 SQL은 아무것도 확인하지 않을 것입니다
value so now let's move to the second order now we're gonna check
7:10:10
그래서 보시다시피 첫 번째 값이 null인지 확인할 것입니다
again the first value is it null well yes as you can
7:10:13
그래서 우리는 여기 null이 있습니다. 이는 우리가 오른쪽에서 이 경로를 활성화할 것임을 의미합니다
see we have here a null so that means we're gonna go and activate this path over here on the right side so now sql will not go blindly putting anything from the billing address in the results
7:10:24
그래서 SQL은 청구 주소에서 결과에 아무것도 넣지 않을 것입니다
first sql has to check it so sql gonna check it whether
7:10:27
먼저 SQL이 그것을 확인해야 합니다
it's null or not sql gonna go and return it
7:10:30
SQL은 그것이 null인지 아닌지를 확인할 것입니다
as well in the output and we have activated this
7:10:34
그것은 출력에서도 반환될 것입니다
path so sql is returning the value to which is
7:10:37
그래서 SQL은 값을 반환하고 있습니다
the value from the billing address so now let's move to the
7:10:40
청구 주소에서의 값이므로 이제 세 번째 주문으로 넘어갑니다
third order sql first gonna go and check the shipping
7:10:44
SQL이 먼저 배송 주소를 확인할 것입니다
address is it null well yes it is null so that's why sql gonna go and start
7:10:49
그것이 null인지 확인할 것입니다
checking the second value so this time sql will
7:10:53
그래서 SQL이 두 번째 값을 확인할 것입니다
not return the billing address value since it's null
7:10:56
이번에는 SQL이 청구 주소 값을 반환하지 않을 것입니다
it's gonna go and return the third value
7:10:59
그것이 null이기 때문입니다
and what is the third value it is our static value
7:11:02
세 번째 값을 반환할 것입니다
the na so in the outputs we're gonna get
7:11:05
세 번째 값은 우리의 정적 값입니다
the na our default value so
7:11:09
출력에서 우리는 na를 얻게 될 것입니다
with that as you can see in the output we will not get any nulls we are
7:11:12
na는 우리의 기본 값입니다
using the default value and as well multiple columns
7:11:15
그래서 출력에서 null을 얻지 않을 것입니다
so if you check the output it's always the first priority
7:11:18
우리는 기본 값을 사용하고 있으며 여러 열도 사용하고 있습니다
to check the values from the first column the shipping
7:11:21
그래서 출력에서 항상 첫 번째 우선 순위입니다
address if it's null then the second priority gonna
7:11:24
첫 번째 열의 값을 확인하는 것입니다
be the billing address if it's null then the last
7:11:27
우선순위는 기본값이 될 것이므로 보시다시피
priority it's gonna be the default value so as you can see
7:11:31
SQL은 왼쪽에서 오른쪽으로 값을 확인하고 첫 번째 널이 아닌 값을 만나면 즉시 멈추고 결과에 반환합니다. 이것이 Cowlis가 작동하는 방식입니다.
sql is checking the values from left to right and it stops immediately once it encounters the first not null value and return it in the results so this is how the cowlis works
7:11:46
자, 이제 Cowlis 간의 차이에 대한 간단한 요약을 해보겠습니다.
all right so now let's have a quick summary about the differences between the cowlis
7:11:49
그리고 IS NULL은 우리가 배운 대로 제한적입니다.
and is null so as we learned the is null is limited
7:11:53
두 값으로만 제한됩니다. Cowlis는 놀랍습니다.
only to two values where the cowlis is amazing
7:11:56
여기서 여러 값의 목록을 가질 수 있습니다.
where you can have a list of multiple values which
7:11:59
IS NULL에 비해 큰 장점입니다. 성능에 대해 이야기한다면 IS NULL이 Cowlis보다 빠릅니다.
is a great advantage compared to the is null now if you are talking about the performance the is null is faster than the cowlis so if you want to optimize
7:12:07
쿼리의 성능을 최적화하려면 IS NULL을 사용하세요.
the performance of your query then go with the is null now there
7:12:11
IS NULL에 또 다른 문제가 있습니다. 서로 다른 데이터베이스에 대해
is another problem with the is null is that we have different
7:12:14
Microsoft의 경우 서로 다른 키워드가 있습니다.
keywords for different databases so for microsoft
7:12:17
SQL Server에서는 우리가 배운 대로 IS NULL을 사용하지만
sql server we use the is null as we learned but
7:12:20
Oracle에서는 다른 구현이 있으며 NVL을 사용합니다.
in oracle they have different implementations they use the nvl
7:12:24
MySQL과 같은 다른 데이터베이스에서는
and other database like mysql you have
7:12:27
NULL 및 이 세 가지 함수는 동일한 작업을 수행하지만
if null and all those three functions are doing the same but
7:12:31
서로 다른 데이터베이스에 대해 다른 구현이 있습니다.
we have different implementations for different databases but in the other hand
7:12:34
Cowlis는 모든 데이터베이스에서 사용할 수 있습니다.
the cowlis it is available in all different databases
7:12:37
따라서 여기서는 데이터베이스 간의 합의 또는 표준이 있습니다.
so here we have like an agreement or standards between the databases
7:12:40
Cowlis를 사용하는 것에 대한 것입니다. 다시 말해, 이는 큰 장점입니다.
of using the cowlis so here again this is a great
7:12:43
Cowlis를 사용하면 스크립트를 작성할 때
advantage for the cowlis because if you are writing like
7:12:46
언젠가 한 데이터베이스에서 다른 데이터베이스로 마이그레이션하고 싶을 때
scripts and someday you want to migrate from one database to another
7:12:50
Cowlis를 사용하면 아무것도 변경할 필요가 없습니다.
if you are using the cowlis you don't have to change anything but
7:12:53
IS NULL을 사용하면 쿼리와 스크립트를 올바른 함수로 조정해야 합니다.
if you are using the is null then you have to go and adjust your queries and scripts with the correct functions that's why i tend always to use the Cowlice and avoid using the isNull.
7:13:04
정말 필요한 경우에만 IS NULL을 시도하지만 보통 Cowlis를 사용합니다.
Only if it's really necessary that I have really bad performance, I go and try the isNull but I usually stick with the Cowlice.
7:13:11
그래서 그게 제 조언입니다. Cowlis를 사용하고 표준을 준수하세요.
So that is my advice for you, go with the Cowlice and stick with the standards.
7:13:19
이제 Cowlis와 IS NULL의 사용 사례는 매우 유사하며 주로 SQL 작업을 수행하기 전에 NULL을 처리하는 데 사용됩니다.
Now the use cases of the Cowlice and the isNull are very similar and we mainly use them in order to handle the null before doing any SQL task.
7:13:29
예를 들어, 우리는 데이터 집계 작업을 수행하기 전에 null을 처리하기 위해 이를 사용할 수 있습니다. 이게 무슨 뜻인지 이해해 봅시다.
For example, we can use them in order to handle the null before doing data aggregations. So let's understand what this means.
7:13:36
세 개의 셀이 있다고 가정해 봅시다. 15, 25, 그리고 null이 있습니다.
Imagine that we have three cells, we have 15, 25 and a null.
7:13:41
이제 평균과 같은 집계 함수를 사용하면 15 더하기 25를 2로 나누는 방식으로 계산하게 되어 평균은 20이 됩니다.
Now if you go and use an aggregate functions like the average, what can happen is going to calculate it like this 15 plus 25 divided by two and the average is going to be 20.
7:13:51
여기서 보시다시피, SQL은 두 값 15와 25만 포함하고 null 값은 완전히 무시합니다.
So as you can see here, SQL is including only the two values 15 and 25 and ignores totally the null value.
7:13:59
계산에서 null은 포함되지 않습니다. SQL이 그렇게 하면 출력도 null이 될 수 있기 때문입니다.
So in the calculations, the null will not be included because if SQL does that, the output can be as well null.
7:14:05
null은 완전히 무시됩니다. 이제 sum, count, sales를 세는 경우, min과 max와 같은 다른 집계 함수에서도 같은 일이 발생할 수 있습니다.
So the nulls are totally ignored. Now the same thing can happen with the other aggregate functions like the sum, count if you are counting the sales, min and max.
7:14:14
집계 함수 count에 대한 유일한 예외가 있습니다. 별표와 함께 사용할 때 SQL은 값을 고려하지 않습니다.
There is only one exception about the aggregate function count if you are using it with the star sql here is considering not the values
7:14:21
SQL은 행을 고려할 수 있습니다. 그래서 SQL은
sql can consider the rows that's why sql gonna
7:14:24
모든 행을 포함하고 출력을 찾게 됩니다.
go and include all those rows and find the output gonna
7:14:27
세 개가 될 것입니다. 이제 몇 가지 시나리오에서 비즈니스가
be three now in some scenarios if your business understand
7:14:31
null을 0으로 이해하면 분석 결과에 문제가 생길 수 있습니다.
the null as zero then you can have a problem with
7:14:34
null을 처리하지 않으면 분석 결과에 문제가 생길 수 있습니다. 그래서 우리는 집계 작업을 수행하기 전에 null을 처리해야 합니다.
the result of your analyzes if you don't handle the nulls so what we have to do we have to handle the null before doing the aggregations so we have to go and replace a null
7:14:42
null을 0으로 바꿔야 합니다. isner 또는 cowlis를 사용할 수 있습니다.
with zero using either the isner or the cowlis
7:14:45
그렇게 하면 계산이 변경됩니다.
so once you do that the calculation is going to be changed for the
7:14:48
평균이 됩니다. 15 더하기 25 더하기 0을 3으로 나누면 출력은 13.3이 됩니다. 이렇게 하면 비즈니스에 더 정확한 결과를 얻을 수 있습니다.
average so it's going to be 15 plus 25 plus zero divided by three and the output this time going to be 13.3 so with that you're going to get more accurate results for the business
7:14:59
그들이 null을 0으로 이해한다면, 이제 다음과 같은 예제가 있습니다.
if they understand nulls as zero all right so now we have the following
7:15:02
예제는 고객의 평균 점수를 찾으라고 합니다.
example it says find the average scores for the customers so
7:15:06
해결해 봅시다. 고객 ID와 점수를 선택할 것입니다.
let's go and solve it we're gonna go and select the
7:15:09
고객 ID와 점수를 선택합니다.
customer id the score from
7:15:12
테이블 고객이므로 가봅시다
table customers so let's go
7:15:15
그리고 실행해 보겠습니다. 보시다시피 우리는 점수가 있는 네 명의 고객이 있고 마지막 고객은 점수가 없으므로 null로 표시됩니다. 가봅시다
and execute it so as you can see we have four customers with score and the last one doesn't have any score so we have it as a null let's go
7:15:22
점수의 평균을 계산하고
calculate the average for the score and
7:15:26
창 함수가 필요합니다. 그래야 볼 수 있습니다
i would like to have the window function in order to see the
7:15:29
세부 사항도 마찬가지입니다. 이것은 평균 점수입니다
details as well so this is average scores
7:15:33
그러니 이제 가서 실행해 보겠습니다. 물론 무엇이든
so let's go and excuse it now of course what is
7:15:36
여기서 일어나는 일은 네 개의 값이 서로 더해지고 네로 나누어지며 널은 완전히 무시됩니다. 이제 질문은 비즈니스가 널을 0으로 이해하는 것입니다.
going on here the four values going to be added to each other's and divided by four and the null is totally ignored now of course the question is what the business understand with the null if it is zero
7:15:47
그렇지 않으면 부정확한 결과가 나옵니다.
then we have inaccurate results so let's
7:15:50
이제 수정하러 가겠습니다. 이번에는 평균을 구한다고 말할 것입니다.
go and fix it now this time we're gonna say okay we're gonna have the average
7:15:53
하지만 점수 대신 널을 먼저 처리할 것입니다. 널을 0으로 바꿔야 합니다.
but instead of score we're gonna handle the nulls first so we have to replace any nulls with zero we can go and use the cowlis or the is null so i will go with the cowlis
7:16:04
이렇게 하고 점수에서 널을 발견하면 0으로 만드세요.
like this and score if you find any null make it zero so that's it and as well i will go
7:16:12
이제 윈도우 함수를 사용하여 평균 점수를 구할 것입니다.
with a window function so average scores
7:16:16
이제 두라고 부르겠습니다. 이제 실행하러 가겠습니다.
let's call it two now let's go and execute it
7:16:19
출력에서 500을 얻은 것을 볼 수 있습니다.
now as you can see in the output we got 500 and
7:16:22
이것은 이전 평균과 다릅니다. 그 이유는 우리가
this is different than the previous average and that's because we
7:16:25
널을 0으로 바꿨기 때문입니다.
have replaced the null with zero let's just go
7:16:28
이해하기 위해 표시하겠습니다. 복사해서 여기 두겠습니다.
and display it in order to understand it so i will copy
7:16:31
이제 점수 두라고 부르고 실행하겠습니다. 이제 ISQL이 모든 값을 요약하고 5로 나눌 것입니다.
it and put it here so let's call it score two and execute it so now isql is going to summarize all those values and divide it by five and that's why we are getting the 500.
7:16:42
비즈니스가 널을 0으로 이해한다면 이 평균은 널을 처리한 후 더 정확해질 것입니다.
So if our business understand the null as a zero this average gonna be more accurate after we handle the null.
7:16:50
일부 시나리오에서는 데이터 집계를 수행하기 전에 널을 처리해야 합니다.
As you can see in some scenarios we have to handle the nulls before doing any data aggregations.
7:16:59
다음 사용 사례로 넘어가겠습니다.
All right moving on to the next use case for the kawales and is null we
7:17:02
널을 처리하기 위해 사용할 수 있습니다.
can use them in order to handle the nulls before doing
7:17:06
수학적 연산을 수행하기 전에 널을 처리하는 것입니다.
any mathematical operations so let's understand what
7:17:09
더하기 연산자를 사용하여
this means using the plus operator so if you do plus operator
7:17:12
두 숫자 간에 더하기 연산을 수행하면
between two numbers like one plus five you are summarizing
7:17:15
값을 요약하게 되고 6을 얻습니다.
the values and you will get six and if you do the plus operator
7:17:18
문자열 값 간에 더하기 연산을 수행하면
between string values like a plus b
7:17:21
데이터 연결을 수행하고 있습니다.
so now what we are doing we are doing data concatenations and
7:17:25
출력은 a b가 될 것입니다.
the output going to be a b so now if you go and replace the one with a value like zero so zero plus five we will get
7:17:32
하나를 0으로 바꾸면 0 더하기 5를 얻습니다.
five nothing fancy about that and for the strings
7:17:35
빈 문자열로 값을 바꾸면
if you go and replace a value with an empty string so
7:17:38
따옴표 사이에 문자가 없고
there is zero characters between the two quotes plus
7:17:41
출력에서 b만 얻을 수 있습니다
the b so in the output you will get only b so
7:17:45
null을 사용하면
it's fine and nothing is critical but now we come to the problem if
7:17:48
null을 사용하면
you use a null if you replace the one with a null in
7:17:52
null을 얻을 것입니다
the output you will get a null because you are saying okay five
7:17:55
모르는 것이 있으므로
plus something that i don't know so skl says okay you are summarizing now a value with a no value it is
7:18:02
왜 isql이 null이라고 말하는지
unknown so i don't as well know what's gonna be the answer that's
7:18:05
정답이 무엇인지
why isql gonna say it's gonna be null isql just don't know what
7:18:08
문자열이므로
is the answer and the same thing can happen with anything else like the
7:18:11
문자열이므로 null과 b를 더하면
string so if you are saying null plus b and
7:18:14
여기에서 null은 알 수 없는 값이라고 말할 것입니다.
here isql gonna say the same thing the null is unknown
7:18:17
그리고 답변도 알 수 없는 값이 될 것입니다. 그러니 친구들
and the answer gonna be as well unknown so my friends
7:18:20
이는 데이터 분석 및 작업에서 매우 중요합니다. 즉, 우리는 어떤 작업을 수행하기 전에 null을 처리해야 합니다.
this is very critical in the analyzes and working with data so this means we have to handle the nulls before doing any
7:18:27
수학적 연산에 대해서만 해당되는 것이 아닙니다.
mathematical operations and this is not only for the plus operator
7:18:30
빼기와 같은 다른 연산자에도 해당됩니다.
it's as well for the other operators like minus and
7:18:33
계속해서 진행하겠습니다. 이제 다음 작업을 수행해 보겠습니다. 표시하라고 합니다.
so on all right so now let's have the following task and it says display
7:18:37
고객의 전체 이름을 하나의 필드에
the full name of the customers in a single field
7:18:40
이름과 성을 합쳐서 추가합니다.
by merging their first and last names and add
7:18:43
각 고객의 점수에 10점의 보너스를 추가합니다. 그러니 해결해 보겠습니다. 먼저 기본 정보를 선택하겠습니다. 고객 ID가 필요합니다. 이름과 성이 필요합니다.
10 bonus points for each customer's score so let's go and solve it we're gonna select first the basic informations let's get the customer id what do we need the first name the last name
7:18:54
그리고 점수도 필요합니다. 그게 전부입니다.
and we need the scores so that's it from
7:18:58
판매 고객으로부터 가져옵니다. 이제 실행해 보겠습니다.
sales customers let's go and execute it
7:19:01
첫 번째 작업은 새로운 필드를 생성해야 한다는 것입니다.
now the first task is that we have to generate a new field called
7:19:04
전체 이름을 만들고, 이름과 성을 합치거나 연결해야 합니다.
full name where we have to go and merge or concatenate
7:19:08
그들의 이름과 성을 합쳐야 하므로 그렇게 해보겠습니다.
their first and last names so let's go and do that
7:19:11
먼저 이름을 더하고, 이름과 성 사이에 공백을 추가한 다음, 성을 더합니다.
we need the first name plus then let's have a space between the first and last name and then plus let's have the last name
7:19:22
전체 이름으로
as full name so
7:19:25
이제 실행해 보겠습니다. 첫 번째 고객의 결과를 가져오면
let's go and execute it now if you take the results for
7:19:28
두 번째 고객에 대해서도 같은 작업을 하지만 세 번째 고객에 대해서는
the first customer it is working so we have joseph goldenberg
7:19:32
여기 문제 고객이 있습니다. 성이 없습니다.
the same thing for the second customer but for the third customer
7:19:36
여기 문제 고객이 성이 없습니다.
we have here a problem customer doesn't have any last
7:19:39
이름은 있지만 성이 없어서 여기 마리라는 이름이 있습니다. 그래서 전체 이름은 완전히 null이며, 이 예제에 대해 올바르지 않습니다. 최소한 이름인 마리를 보여줘야 합니다. 성이 없더라도요.
name but she has a first name so we have here a mary so the full name here is completely null which is not correct for this example we I have at least to show the first name Mari, even though that the last name is missing.
7:19:51
그래서 결과가 정확하지 않습니다. 그 이유는 null과 마리 사이에 더하기 연산자를 사용하고 있기 때문입니다.
So the result is not really accurate, and that's because we are doing the plus operator between a null and Mari.
7:19:58
즉, 우리는 가야 합니다.
So that means we have to go
7:20:00
더하기를 하기 전에 null을 처리해야 합니다.
handle the nulls before doing any plus
7:20:03
연산자이므로 다시 여기서 null인 cowlis를 사용할 수 있습니다. 그래서 cowlis를 사용하여 새 필드를 만들어 보겠습니다. 그래서 성이 될 것입니다.
operator so again here we can go with the cowlis or that is null so let's go and create a new field using the cowlis so it's going to be the last name
7:20:13
이제 null일 경우 새 값을 정의해야 합니다.
and now we have to define a new value if it's null so we
7:20:17
알 수 없는 것처럼 하거나 빈 문자열을 가질 수 있습니다. 두 개의 따옴표를 사용하고 그 사이에 아무것도 없도록 할 수 있습니다. 그래서 우리는 빈 문자열을 사용하고 있습니다.
could have like something unknown or we could have like an empty string and we can do that using two quotes and between them there is nothing so we We are using an empty string.
7:20:27
결과를 확인해 보겠습니다. 성 두 개. 그래서 실행해 보겠습니다.
So let's go and check the results. Last name two. So let's go and execute it.
7:20:34
이제 마리의 성이 빈 문자열로 되어 있으며 더 이상 null이 아닙니다.
Now we can see that the last name over here for Mari, it has an empty string and it is not anymore a null.
7:20:41
이제 SQL은 알게 되었습니다. 이건 문자열이고 그 안에 문자가 없습니다.
So now SQL knows, okay, this is a string and there is no characters inside it.
7:20:46
그래서 SQL은 더 많은 정보를 알고 있으며, 이제 그 정보를 계속 사용할 수 있습니다. 그래서 가서 그렇게 해봅시다.
So with that SQL knows more information and we can go and now can continue those information. So let's go and do that.
7:20:53
전체 내용을 가져와서 성을 Cowellis로 교체할 것입니다.
We're going to take the whole thing and replace the last name with the Cowellis.
7:20:59
그래서 여기 성을 제거하고 실행하겠습니다. 이제 보시다시피 상황이 더 나아졌습니다.
So let me just remove this last name over here and execute it. So now as you can see, things look better.
7:21:05
이제 마리의 전체 이름에는 이름만 있습니다. 물론 이렇게 마음에 들지 않으면 다른 기본 값을 원할 것입니다.
Now we have in the full name for Mari, only the first name. And of course, if you don't like it like this, you would like to have another default value.
7:21:11
여기에서 사용할 수 없는 것처럼 말할 수 있습니다. 그래서 실행해 보겠습니다.
You can go over here and say something like in A not available. So let's go and execute it.
7:21:17
그렇게 하면 여기 성이 누락된 것을 즉시 볼 수 있지만, 보기 좋지 않습니다.
And with that, you can see immediately there is here a missing last name, but it doesn't really look good.
7:21:22
그래서 그냥 제거하고 빈 문자열로 가겠습니다. 실행하겠습니다.
So I will just remove it and go with the empty string. We're going to go and execute it.
7:21:26
그래서 그렇게 해서 우리는 전체 이름을 가지고 첫 번째 이름과 성에서 누락된 정보가 없는 작업의 첫 번째 부분을 해결했습니다.
So with that, we have solved the first part of the task where we have the full names and we are not missing any information from the first name and the last name.
7:21:35
이제 고객 점수마다 10점을 추가해야 하는 작업의 두 번째 부분으로 가겠습니다.
Now, let's go to the second part of the task where we have to add 10 points points for each customer score.
7:21:41
그래서 각 점수에 10을 추가해야 합니다. 그래서 가서 해봅시다. 마지막에 추가할 것입니다. 점수에 10을 더합니다.
So we have to go and add a 10 for each score. So let's go and do it. I'm going to put it at the end. So score plus 10.
7:21:48
보너스가 있는 점수라는 이름을 주자.
And let's give it the name score with bonus.
7:21:53
자, 이제 실행해 보자. 출력에서 볼 수 있다.
so that's it let's go and execute it so now in the output you can
7:21:56
매우 간단하다. 각 점수에 10을 추가했다.
see it's very easy we have added a 10 for each score so
7:22:00
각 고객의 점수 포인트를 증가시켰다. 하지만
we have increased the score points for each customer but
7:22:03
마지막 고객인 안나의 점수에는 값이 없다. 그래서
now for the last customer anna you can see over here she doesn't have a value in the scores and that's why
7:22:09
isquare가 10을 추가하지 않았기 때문에 우리는
isquare didn't go and add a 10 so we will get as well in
7:22:12
null이 발생했다. 물론 마지막 고객이 점수를 받지 않는 것은 공정하지 않을 수 있다.
null and of course this might not be a fair that the last customer is not getting any point even though that we have increased for all
7:22:18
따라서 null을 처리해야 한다. null을 0으로 바꾸고
others so that means we have to go and handle the null by replacing
7:22:22
그 후에 더할 수 있다. 자, 이제 해보자.
the null to a zero and only after that we can
7:22:25
더할 것이다. 만약
add a plus to it so let's go and do that i'm
7:22:28
null이라면 0으로 만들고
gonna add a cowlis if
7:22:31
그 후에 10점을 추가하자. 자, 이제 실행해 보자.
it is null then go and make it a zero and
7:22:34
결과를 보면 모든 것이 공정해졌다. 이제 10점이 있다.
afterward go and add a 10 points so let's go and execute it so now as you can see the result everything now is fair where we have a 10 points
7:22:43
각 고객에게 점수가 있다. 고객이 점수가 없더라도
points for each customers even if the customer doesn't
7:22:46
안나처럼 null이지만 여전히 10점을 받고 있다.
have any values in the scores like here anna she has
7:22:50
다시 말하지만, null을 제대로 처리하지 않으면
like null but still she is getting a 10 points so
7:22:53
수학적 연산을 하기 전에 예상치 못한 결과를 얻을 수 있다.
here again as you can see if you don't handle the nulls correctly
7:22:56
null을 올바르게 처리하기 전에 주의해야 한다.
before doing the mathematical operations you might get unexpected results so be careful with the nulls and handle them correctly before adding anything
7:23:10
다음 사용 사례로 넘어가자. cowalis와 null을
okay moving on to the next use case for the cowalis and is null we
7:23:13
조인하기 전에 null을 처리하는 데 사용할 수 있다.
can use them in order to handle the null before doing joins
7:23:16
조금 고급 사용 사례지만 매우 중요하다.
this is a little bit advanced use case but it's very
7:23:19
이해하는 것이 중요하다. 예를 들어 테이블 A와 테이블 B가 있다.
important to understand it so let's understand why this is important let's
7:23:23
일부 시나리오에서는 이 두 테이블을 결합해야 한다.
have for example two tables table a and table b and
7:23:26
조인을 사용하여 두 테이블을 결합해야 한다.
in some scenarios we have to go and combine those two tables using
7:23:29
조인을 위해 테이블 A와 B 사이의 키를 지정해야 한다.
the joins and now in order to join two tables we have to go and specify the keys between the table a and
7:23:35
테이블 b를 조인하기 위해서 이 예제에서는
table b in order to join on it so in this example we
7:23:38
두 개의 키가 필요합니다. 이제 특별한 경우가 있습니다.
have two keys in order to join the tables now here comes the
7:23:41
그 키에 null이 없을 경우입니다.
special case if those keys don't have any nulls
7:23:45
모든 데이터가 채워져 있다면 조인이
inside it and all the data are filled then your join
7:23:48
완벽하게 작동할 수 있으며 예상 결과를 얻을 수 있습니다.
can work perfectly and you will get the expected results and
7:23:51
이제 null이 있는 특별한 경우가 있을 수 있습니다.
now you might have a special case where there are nulls
7:23:54
키 안에 누락된 값이 있기 때문에 이는 큰 문제입니다.
inside the keys so there are missing values and this is a big problem because in the output you will get unexpected results and some records will be
7:24:02
출력에서 예상치 못한 결과를 얻을 수 있습니다.
totally missing so in this scenario we have to handle the
7:24:05
이 시나리오에서는 null을 처리해야 합니다.
nulls inside the keys before doing the joins let's
7:24:09
조인하기 전에 키 안의 null을 처리합시다.
have a very simple example in order to understand this behavior all
7:24:12
이 동작을 이해하기 위해 아주 간단한 예제를 보겠습니다.
right so now let's have this very simple example where we have two tables and we want
7:24:15
이제 두 개의 테이블이 있고 이를 결합하고자 합니다.
to combine them so in the first table we have a year type
7:24:18
첫 번째 테이블에는 연도 유형의 주문이 있습니다.
orders and in the second table we have as well year type and we have sales so now we would like to go and combine those two tables in order to have all informations in one
7:24:27
두 번째 테이블에도 연도 유형과 판매가 있습니다.
results now we can go of course and use the inner join between
7:24:30
이 두 테이블을 결합하여 모든 정보를 하나로 모으고자 합니다.
the table one and table two and the keys for the joints
7:24:34
결과적으로 내부 조인을 사용할 수 있습니다.
here as you can see we have the year in both of the tables and
7:24:38
테이블 1과 테이블 2, 그리고 조인을 위한 키입니다.
as well the type so we're gonna go and use both of those
7:24:41
여기서 두 테이블 모두에 연도가 있습니다.
columns as a key for the join so let's do it
7:24:44
유형도 있으므로 두 가지를 모두 사용할 것입니다.
step by step how is going to execute this so we need the year
7:24:47
조인을 위한 키로서 두 열을 사용합시다.
type and the results so it's going to go and take those two columns to the results and we need the orders and sales so it's going to take as well the orders and the sales from the second table.
7:24:58
단계별로 실행되는 방법을 살펴보겠습니다.
So now let's start doing it row by row so the
7:25:01
연도와 결과가 필요합니다.
first key gonna be those two columns so we
7:25:04
따라서 이 두 열을 결과로 가져올 것입니다.
have 2024 and the type a so now
7:25:07
주문과 판매도 필요하므로 두 번째 테이블에서 가져올 것입니다.
it's gonna start searching for those two informations in
7:25:10
이제 행별로 시작해 보겠습니다.
the second table and as you can see we have here a match right so
7:25:14
첫 번째 행도 일치합니다. 내부이기 때문입니다.
the first row is as well matching since it's inner
7:25:17
조인은 출력에서 일치하는 것만 표시합니다.
join it's gonna present in the output only the matching
7:25:20
왼쪽과 오른쪽의 행을 출력에서 가져옵니다.
rows from left and right so in the outputs
7:25:23
테이블에서 전체 행을 가져올 것입니다.
we're gonna get the whole row from the table
7:25:26
하나 그리고 테이블 두에서 판매를 가져올 것입니다.
one and we will get the sales from the table two all
7:25:30
오른쪽으로 이동하여 두 번째 행으로 가겠습니다.
right so that's all for the first row now let's move to the
7:25:33
여기에서 키의 값은 2024와 null입니다.
second row over here so what are the values of the keys
7:25:36
이제 오른쪽에서 일치를 확인하면
we have 2024 and null
7:25:39
여기에서 일치하는 것을 볼 수 있습니다. 논리적입니다.
so now if you check the matches on the right side you
7:25:43
2024와 null도 마찬가지입니다. 모든 것이
can see we have a match here right it is logical so
7:25:46
일치하고 결과로 얻어야 합니다. SQL입니다.
it's as well 2024 and null so everything
7:25:49
모든 것이 일치하고 결과로 얻어야 합니다. SQL입니다.
is matching and we should get it as a result right sql
7:25:52
테이블을 조인하기 위해 등호 연산자를 사용할 수 없습니다.
cannot go and use the equal operator in order
7:25:56
테이블을 조인하기 위해 등호 연산자를 사용할 수 없습니다.
to join tables so even though that is logically it
7:25:59
출력에 포함하는 것이 논리적이지만 SQL은
makes sense to have it at the output but still sql cannot
7:26:02
null을 비교할 수 없습니다. 이것이 문제입니다.
go and compare the nulls that's why this is a problem
7:26:05
이 조합에 대해 SQL은 아무것도 찾지 못할 것입니다.
for this combination sql will not find any
7:26:09
일치하지 않으므로 정보를 얻지 못할 것입니다.
matching so we will not get any informations for the
7:26:12
2024와 null의 조합에 대해
combination of 2024 and null so for us of
7:26:15
비즈니스에서 이것은 누락된 정보입니다.
course in the business this is missing informations and
7:26:18
부정확한 결과도 포함되어 있습니다.
as well inaccurate results so we're gonna miss this
7:26:21
행이 누락되어 세 번째 행으로 넘어갑니다.
row and it's gonna go and jump to the third row so here
7:26:24
키의 값은 2025와 a b입니다. 이제 두 번째 테이블에서 검색합니다.
what are the values of the key we have 2025 and a b now it's gonna go and search it in the second table and it's gonna find a match over here
7:26:33
출력에서 이러한 값을 얻을 것입니다.
so in the outputs we're gonna get those values the
7:26:37
주문은 50, 판매는 300이 될 것입니다.
set the order is gonna be 50 the sales 300 now
7:26:41
마지막 행으로 가게 될 것이고 여기 다시 있습니다
is going to go to the last row and we have here again
7:26:44
여기 2025와 null이라는 같은 문제가 있습니다
the same problem we have here 2025 and null
7:26:47
데이터를 확인하면 예, 우리가 있다고 말할 것입니다
and of course if you check the data you will say yes we have
7:26:50
여기 일치하는 것이 있지만 SQL은 이를 무시할 것이므로 우리는 결과에서 찾을 수 없습니다
a matching over here but sql would ignore it so we have exactly the same situation and we will not find it at the results
7:26:58
출력에서 우리는 두 개의 행만 얻을 것이고 두 테이블은 키를 비교하면 동일합니다
So at the output we will get only two rows even though that those two tables are like identicals if you compare the keys.
7:27:05
그로 인해 결과에서 데이터를 잃고 부정확한 결과를 제공하고 있습니다
So with that we are losing data at the results and we are providing inaccurate results.
7:27:10
친구들, 키 안에 null이 있으면 출력에서 레코드를 잃게 됩니다
So my friends if you have nulls inside your keys what can happen you will lose records at the output.
7:27:17
여기서 키 안의 null을 처리하는 것이 매우 중요합니다
So here it's very important to handle the nulls inside the keys before doing the joins.
7:27:23
그렇다면 이제 이를 수정하기 위해 cowlis 또는 is null을 사용할 것입니다
Alright so now in order to fix it we're going to go and use either the cowlis or the is null in the join.
7:27:28
보시다시피 우리는 타입을 직접 사용하지 않고 null을 빈 문자열로 대체하여 처리하고 있습니다
So as you can see we are not using the type directly we are handling it by replacing the null with an empty string.
7:27:35
어떤 값을 사용하든 중요한 것은
It doesn't matter which value you are using the main thing is
7:27:38
값이 있어야 SQL이 매핑할 수 있다는 것입니다
that you have a value and SQL can go and map
7:27:41
빈 문자열이나 공백 또는 기본값으로 가질 수 있지만 보통 빈 문자열을 사용합니다
it so you could have it as empty string or a blank or any default value but I usually go with the empty string since it's a little bit faster than having
7:27:49
다른 문자가 아닌 모든 곳에 가게 될 것입니다
any other characters so now what can happen is going to go everywhere
7:27:52
그 null을 빈 문자열로 대체합니다
and replace those nulls with
7:27:56
이제 내부에 null이 없습니다
an empty string so now we don't have any nulls inside
7:27:59
우리의 키와 이제 무슨 일이 일어날지 보겠습니다
our keys and let's go and see what can happen so
7:28:02
첫 번째 행부터 다시 시작할 것입니다
we're going to start with the first row again here we have a
7:28:05
오른쪽 테이블에서 일치하는 것이 있습니다
matching from the right table and we're going to see
7:28:08
출력에서 모든 레코드를 보게 될 것입니다
the whole records in the output so
7:28:11
우리는 매출이 백이 될 것이고 이제 두 번째 행으로 넘어갑니다
we will get as well the sales as a hundred and now it's going to go to the second row over here so this time we don't have a null
7:28:18
여기 2024와 빈 문자열이 있습니다
we have 2024 and an empty string so
7:28:21
이제 일치를 찾으러 가게 될 것입니다
now it's gonna go and search for a match and it's gonna find it over
7:28:25
여기 2024와 빈 문자열이 있습니다
here we have as well 2024 and an empty string
7:28:28
출력에서 우리가 얻을 수 있는 것은 2024입니다
so now what can happen in the outputs we're gonna get
7:28:31
2024년이지만 여기서는 null을 얻을 것입니다.
a 2024 but here we will get a null
7:28:34
그래서 우리는 빈 문자열을 얻지 않고 여기서 null을 얻을 것입니다.
so we'll not get an empty string we will get a null over here and that's because we are handling the null only on the join so as you can see we
7:28:42
여기서 조인에 null 타입이 있습니다.
have here that is null type on the join but
7:28:46
선택에서는 그것이 없습니다.
we don't have it on the select so on the select the tag
7:28:49
선택에서는 원래 데이터와 같을 수 있습니다.
can be like the original data and the original data was a
7:28:52
null을 조인에서 처리하고 있습니다.
null we are just handling the null in the joins just in order
7:28:55
sql이 데이터를 매핑하고 일치시키는 방법을 이해하도록 합니다.
to let sql understands how to map and match the
7:28:59
이 예제에서는 값을 변경하지 않습니다.
data so in this example i'm not changing the values in
7:29:02
선택에서 원래 값을 얻을 것입니다.
the select so that's why we will get the original value but the orders we
7:29:05
40을 얻고 판매는 20이 될 것입니다.
will get it 40 and the sales gonna be 20 now moving on to the third row i think you already
7:29:12
판매는 300이 될 것입니다.
get it so it's gonna find a match and
7:29:15
마지막으로 이동할 것입니다.
the sales gonna be 300 all right now we're
7:29:18
2025와 빈 문자열이 있습니다.
gonna move to the last one and here we have the same scenario so
7:29:22
더 이상 null이 아니며 정보를 검색합니다.
we have 2025 and an empty string so it's
7:29:25
선택에서 처리하지 않았습니다.
not null anymore and it's gonna go and search for all those informations and it's gonna find it over here so it's gonna take this field over here in the type in null not an empty string because
7:29:37
결과가 완전하다는 것을 알 수 있습니다.
in the select we didn't handle it. So the order can be 60 and the sales can be 200.
7:29:43
결과가 완전하다는 것을 알 수 있습니다.
So as you can see now the result is complete.
7:29:46
조인과 is null 함수를 사용하여 결과를 결합했습니다.
We successfully combined both of those tables in one big results using joins but as well using the help of the is null function in order to have a complete result and not miss any value.
7:29:57
항상 키를 확인하세요.
So my friends be very careful check always
7:30:01
다음 사용 사례로 이동하겠습니다.
the keys whether they have nulls or not and if you find nulls go immediately and handle it so you don't lose any records in the results and you get accurate analysis
7:30:15
데이터를 정렬하기 전에.
all right moving on to the next use case for the is null we can use it in order to handle the nulls
7:30:21
판매 15, 25 및 null이 있습니다.
before sorting the data so imagine we have the
7:30:24
판매를 기준으로 정렬하면.
following sales 15 25 and null now
7:30:27
최저에서 최고로 정렬할 수 있습니다.
if you go and sort the data by the sales ascending from the
7:30:30
null이 시작 부분에 표시됩니다.
lowest to the highest what can happen is going to
7:30:33
시작 부분에 널을 표시하는 것은 아닙니다
show the nulls at the start and that is not
7:30:36
널은 가장 낮은 값이기 때문에 값이 없지만 SQL은 이렇게 표시할 수 있습니다
because the null is the lowest value because null has no value but sql show it like this it can place it at the start and then below it we can
7:30:46
가장 낮은 값이므로 15가 됩니다
have the lowest value so it is a 15 and
7:30:49
마지막에 25가 될 수 있습니다
at the end we can have the 25 now if you are doing the exact
7:30:52
가장 높은 값에서 가장 낮은 값으로 정렬하는 반대입니다
opposite where you are sorting the data from the highest
7:30:55
내림차순으로 정렬할 수 있습니다
to the lowest using descending so what
7:30:58
이렇게 정렬하면 25가 될 수 있습니다
can happen is going to sort it like this we can have 25 then
7:31:01
15와 마지막으로 나타날 수 있는 것은
15 and the last thing that can appear in
7:31:04
널이 될 수 있습니다. 여기서 널을 표시합니다
the list can be the null so here is quail is showing the nulls
7:31:08
마지막에 다시 말하지만 널은 가장 낮은 값입니다
at the end and that is again not because nulls are the lowest value it has no value but is quail do it like this show it
7:31:15
마지막에 SQL이 널을 처리하는 방법입니다
at the end so this is how sql deals with the nulls
7:31:18
데이터를 정렬하는 경우
if you are sorting the data so in order to understand this use
7:31:21
다음 작업을 해보겠습니다
case let's have the following task so the task says sort
7:31:25
고객을 가장 낮은 점수에서 가장 높은 점수로 정렬합니다
the customers from the lowest to the highest scores
7:31:28
널이 마지막에 나타나도록 하겠습니다
with nulls appearing last all right so let's
7:31:31
고객 정보를 선택해야 합니다
solve it this is going to be very interesting one so we need the customer information so let's go and select and we need
7:31:38
고객 ID와 점수를 가져옵니다
the customer id and the scores from
7:31:41
판매 고객과
sales customers and
7:31:44
모든 고객의 간단한 목록을 실행해 보겠습니다
let's go and execute it so we have a simple list of all customers
7:31:47
점수를 보아야 합니다
and their scores but now we have to go and saw the data
7:31:50
가장 낮은 점수에서 가장 높은 점수로
from the lowest to the highest so we're gonna go and use the
7:31:54
정렬 기준이 필요합니다
order by clause and we need the failed score and
7:31:57
가장 낮은 점수에서 가장 높은 점수로 시작합니다
since it's lowest to the highest that means we need to have the ascending and in sql it is a default so we don't have to go and mention it so let's go and execute it so now as you can see in the results
7:32:07
작업의 첫 번째 부분이 해결되었습니다
it starts from the lowest to the highest and the first part
7:32:10
문제가 발생했습니다. 널이 있기 때문입니다
of our task is solved but now of course we have an
7:32:13
문제가 있습니다. 왜냐하면 null이 있고, SQL은
issue right because we have a null and as we learned sql gonna put
7:32:16
리스트의 첫 번째 위치에 두고, 작업에서는
it at the first place on the list but the task says
7:32:19
null이 마지막에 나타나야 한다고 말하고 있으므로
with nulls appearing last so we really don't
7:32:23
우리는 null이 시작에 나타나는 것을 원하지 않습니다. 걱정하지 마세요.
want to see the nulls at the start we don't worry about it
7:32:26
그래서 우리는 리스트의 끝에 두고 싶습니다. 즉,
so we would like to have it at the end of the list so that means we
7:32:29
정렬하기 전에 null을 처리해야 합니다.
have to go and handle the nulls before sorting
7:32:32
데이터를 처리하는 방법이 두 가지가 있습니다. 하나는
the data and here we have two ways to do it one way
7:32:35
게으른 방법이고, 다른 하나는 더 전문적인 방법입니다.
that is lazy and the other one is more professional so
7:32:39
먼저 게으른 방법을 보여드리겠습니다. 우리는
let me show you first the lazy way we're going to go and replace
7:32:42
null을 매우 큰 숫자로 대체할 것입니다. 예를 들어,
the null with a very big number so for example what
7:32:45
당신이 할 일은 cowalis를 사용하고
you're going to do we're going to go and use the cowalis and we're going to say
7:32:49
좋은 점수를 얻는 것입니다. 그러면
okay score and then let's have a
7:32:52
정말 큰 점수를 얻을 수 있습니다. 결과를 보기 위해
lot of number so that we have a really big score i just
7:32:55
선택하고, 여기서 매우 큰 숫자가 나타납니다. 이것을 사용하여
want to select it in order to see the results so as you can see it's a very big number here so if you take this and replace the order by
7:33:03
새로운 점수로 교체합니다. 그게 전부입니다.
with a new score so that's it let's go
7:33:06
이제 실행해 보겠습니다. 결과를 확인하면 이미 작업을 해결했습니다.
and execute it so now if you check the results we have already solved the task
7:33:10
모든 고객을 최고에서 최저로 나열했습니다.
we have listed all the customers from the highest to the lowest
7:33:13
null은 끝에 있습니다. 이제 질문은 왜 우리는
and the nulls are at the end so now the question why do we call
7:33:16
이것을 게으르거나 비전문적이라고 부르는가입니다. 그 이유는
this lazy or not professional and that's because we are defining
7:33:19
정적 값을 정의하고 있기 때문입니다. 물론 이 예제에서는 작동하지만
static value and of course for this example it is working but we don't know later what's gonna happen maybe things change where in the scores we're gonna get a higher value than this
7:33:29
나중에 무슨 일이 일어날지 모르기 때문에, 점수가 이보다 더 높은 값이 나올 수 있습니다.
and then sorting the data will make no sense since the
7:33:32
그럼 데이터 정렬은 의미가 없게 됩니다. null은
null gonna be like in between values so who knows your
7:33:35
값들 사이에 있을 것이기 때문에, 당신의
value might be a real value inside the data now let
7:33:38
값은 데이터 안에 실제 값일 수 있습니다. 이제
me show you the other way which is more professional in order to
7:33:41
더 전문적인 방법을 보여드리겠습니다. 이 작업을 해결하기 위해
solve this task where we don't play with luck at all so
7:33:45
이 작업을 해결합시다. 우리는 전혀 운에 의존하지 않으므로
let's go and do that i'm just move this little bit here i'm
7:33:48
새로운 논리를 만들 것입니다. 점수가 null일 때 어떤 일이 발생할 수 있는지 말할 것입니다.
gonna go and create a new logic where we're gonna say case when if the score is null then what can happen we want the value one otherwise
7:33:58
값이 0이 될 것입니다. 그래서 우리는
the value gonna be zero so end so we
7:34:01
0과 1로 플래그를 생성하고 있습니다. 점수가 null이면
are just creating a flag with zero and one if
7:34:04
우리는 1의 플래그를 얻을 것입니다. 점수에 대한 값이 있으면
the score is null then we're gonna get the flag of one if
7:34:07
0을 얻을 것입니다. 그러니 이렇게 해봅시다.
we have a value for the score we will get zero so let's
7:34:11
이렇게 하고 이걸 제거하겠습니다.
have it like this and i will just go and get rid of this
7:34:14
이렇게 하고 지금 실행해봅시다.
cowlis so let's go and execute it now
7:34:17
새로운 플래그를 확인하면 0이 있습니다.
if you check our new nice flag you can see we have zeros
7:34:20
점수에 값이 있는 곳마다 있지만
everywhere where we have a value in the score but
7:34:23
한 번만 null이 있을 때 1의 플래그를 얻을 것입니다.
only once we have a null we will get the flag of
7:34:26
그래서 이제 이것을 얻었으니, 우리가 할 일은 정렬하는 것입니다.
one so now once we got this what we're gonna do we're gonna go and sort
7:34:30
이 플래그와 점수를 기반으로 데이터를 정렬할 것입니다.
our data based on this flag and the score even
7:34:33
작업에서 플래그에 대해 언급하지 않지만 우리는
though the task is not mentioning anything about the flag but we are
7:34:36
null이 결과의 끝에 오도록 강제하기 위해 사용하고 있습니다.
using it in order to force the nulls to be at the
7:34:39
그래서 우리는 플래그를 가지고, 그 후에 점수로 데이터를 정렬할 것입니다.
end of the result let me show you how we're gonna do that so let me just remove all this so first we want to sort the data by our new flag in order to make sure that the nulls at the end
7:34:50
그래서 다시 말하자면, 먼저 데이터를 정렬하는 것입니다.
So we're going to have our flag and then afterward we sort the data by the score. So let's go and have the score.
7:34:57
플래그를 기준으로 null을 끝으로 밀어내기 위해
So again, what you are doing first sort the data
7:35:00
모든 값이 서로 같아지면
by the flag in order to push the nulls at the end
7:35:03
데이터를 점수로 정렬할 것입니다.
and now once all those values are equal to each other's
7:35:06
점수를 사용하여 데이터를 정렬할 것입니다.
what can happen is going to go and sort the data by the score
7:35:10
두 가지 모두 오름차순으로 정렬할 것입니다. 실행해봅시다.
so is going to use the scores in order to sort the data
7:35:13
지금 실행해보면, 정확히 같은 결과를 얻을 것입니다.
and both of them are ascending let's go and execute
7:35:16
값이 가장 낮은 것부터 가장 높은 것까지
it now as you can see we're going to get exactly same results
7:35:19
null은 끝에 있으며, 정렬된 결과를 확인할 수 있습니다.
the values from the lowest to the highest and
7:35:22
null은 끝에 위치하며 정렬에 따라 볼 수 있습니다.
the nulls are at the end and as you can see with the order by
7:35:25
우리는 정적 값이나 큰 숫자를 사용하지 않았습니다.
we didn't use any static values or any big numbers
7:35:28
그리고 물론 선택에서 플래그가 필요하지 않으므로 진행할 수 있습니다.
and of course we don't need the flag at the select so we can go
7:35:32
그것을 제거하고 실행해 보겠습니다. 그렇게 하면 작업을 해결했습니다.
and remove it so let's execute it and with that we have solved the task so as you can see we can use those nice functions like the cowlis or the is null in order to handle the nulls before sorting your data
7:35:47
null if 함수는 두 개의 값을 비교할 수 있습니다.
so what is the function null if null if can go and compare two
7:35:51
값이 같으면 null을 반환합니다.
values and it gonna returns a null
7:35:54
그렇지 않으면 첫 번째 값을 반환합니다.
if they are equal otherwise if they are not equal it
7:35:57
null if의 구문은 두 개의 값만 허용합니다.
gonna returns the first value okay so now
7:36:00
값 하나와 값 둘을 비교할 수 있습니다.
the syntax of the null if it accepts only two values
7:36:04
열과 정적 값 또는 두 열을 비교할 수 있습니다.
value one and value two so here again of course you can go and use a column with a static value like the unknown so we are comparing
7:36:11
배송 주소와 청구 주소를 비교할 수 있습니다.
the values between a column and a static value or
7:36:14
여기서도 두 개의 값만 허용됩니다.
you can go and compare two columns the shipping address and
7:36:18
여기서는 cowlis처럼 여러 값을 가질 수 없습니다.
the billing address so again here it accepts only two values
7:36:21
여러 값의 목록을 가질 수 없습니다.
we cannot have it like the cowlis where we have a
7:36:24
null if의 의미를 이해해 보겠습니다.
list of multiple values all right so now let's understand exactly what
7:36:27
두 개의 값을 확인하고 같으면 null을 반환합니다.
do we mean with the null if so the workflow can be like this is
7:36:30
두 값이 같지 않으면 첫 번째 값을 반환합니다.
going to go and check two values the value one and the value two and if they are equal then it's going to go and return a null but if the two
7:36:39
왼쪽에 있는 값이 반환됩니다.
values are not equal it's going to go and return the
7:36:42
결과를 확인하면 두 번째 값을 얻는 경우는 없습니다.
first value so it is the one on the left side so
7:36:45
두 번째 값을 얻는 경우는 없습니다.
by checking the outcomes here we will never have a scenario where
7:36:48
항상 이 값을 기준으로 확인합니다.
we're going to get the second value that means the second value
7:36:51
값 하나 또는 null을 얻을 수 있습니다.
always used as a check so we are checking against this value
7:36:55
매우 간단한 예를 들어 보겠습니다.
so either we're going to get the value one or a null let's have
7:36:58
가격이 -1과 같은지 확인하고 있습니다.
this very simple example we are saying null if price and we are checking whether it's equal to minus one so we are saying
7:37:05
-1이면 null로 교체합니다.
if the price is equal to minus one then go and replace
7:37:08
데이터 품질 문제이기 때문에 null로 교체합니다.
it with a null because it is data quality issue that we have
7:37:11
음수인 가격은 우리 비즈니스에 의미가 없습니다.
a price that is negative it makes no sense for our business
7:37:14
음수인 가격은 우리 비즈니스에 의미가 없습니다.
and if it is minus one then it means for us and now we
7:37:17
이 제품의 가격을 모르기 때문에
don't know the price of this product so we will
7:37:20
이 제품의 가격을 모르기 때문에 null로 수정합니다.
correct it using the null if let's check this very simple example we have two orders so let's go we're gonna start with the first order and check the first value so what is the first value is the price so here we have a 90.
7:37:32
90이 음수인지 확인할 것입니다.
it's going to go and check is 90 equal to minus one well no that means
7:37:36
이제 두 번째 주문으로 이동합시다.
it's going to go and execute this path so that means in the output we will get the first value which is 90 so in the outputs we will get a 90.
7:37:46
여기서 음수인 경우 확인할 것입니다.
now let's move to the second order here we have a minus one so it's going to check is minus one here equal to the minus one that we have in the null if
7:37:54
그렇습니다, 그래서 실행할 것입니다.
well yes so that means it's going to go and execute
7:37:58
null 값을 얻을 경로입니다.
this path where we were going to get the null value
7:38:01
이제 null과 가격을 비교하면
in the output and we're going to get it like this so now if you compare
7:38:04
음수보다 더 이상 없습니다.
the result from null if and the price you can see we
7:38:07
kawalis와 반대로 null로 교체하고 있습니다.
don't have any more than minus one and as you can see now we are doing
7:38:10
실제 값을 null로 교체합니다.
exactly the opposite as kawalis and is null we are replacing
7:38:13
null 내부에서 두 개의 열을 사용할 수 있습니다.
a real value with a null now moving on to the second example and this is very interesting one in the analytics where we
7:38:20
이 예제에서는 원래 가격이 null입니다.
can go and use two columns inside the null if so
7:38:23
할인 가격과 비교해야 합니다.
in this example we are saying null if original price and
7:38:27
두 열을 비교하고 같으면
discount price so skl have to go and compare the prices
7:38:30
null을 반환해야 합니다.
between those two columns and if they are equal it should return
7:38:33
이 예제에서 왜 이렇게 하는지 알 수 있습니다.
a null and now we might say okay in this example why we are doing this
7:38:36
특별한 경우를 강조하기 위해 사용할 수 있습니다.
well we can use it in order to highlight or
7:38:39
원래 가격이 할인 가격과 같을 때입니다.
flag special cases inside our data and the special
7:38:43
두 가격이 같으면 프로그램에 문제가 있습니다.
case here is if the original price is equal to the discount price and if those two prices are
7:38:49
문제가 발생했음을 의미합니다.
equals that means we have an issue in our program or
7:38:52
데이터를 삽입하는 중에 문제가 발생했습니다.
something like went wrong as we are inserting data so let's
7:38:55
첫 번째 행에서 어떤 일이 발생할 수 있는지 보겠습니다.
see what can happen for the first row we're gonna go and compare
7:38:58
원래 가격 150과 할인된 가격을 비교할 것입니다.
the 150 from the original price with the discount
7:39:02
가격이 같지 않으므로 이는
price so they are not equal right so that means
7:39:05
이스라엘이 원래 가격을 반환할 것입니다.
israel gonna go and return the original price
7:39:08
출력에서 150을 확인하고 두 번째 주문으로 넘어갑니다.
the 150 in the output so let's move to the
7:39:11
여기에서 원래 가격 250과 할인 가격 250이 동일하므로
second order here we have the original price 250 and as well the discount price is 250 so they are equal and if they are equal
7:39:19
출력에서 null을 받게 됩니다.
then we will get a null in the output so as
7:39:22
다시 한 번 보시면 할인에서 값을 얻지 못하고 있습니다.
you can see again here we are not getting any values from the discount we
7:39:25
체크용으로만 사용하고 있으므로 빠른 플래그가 있습니다.
are using it only for a check so with that we have a quick flag
7:39:28
null을 플래그로 사용하여
like using the nulls as flag in order to identify
7:39:32
동일한 값을 확인하는 방법입니다.
where we have equal values so this is how the null if works
7:39:35
여기에서 null if의 좋은 사용 사례가 있습니다.
all right friends here we have a very nice use case for the null if and that is preventing the error of dividing by zero.
7:39:46
이것이 의미하는 바를 살펴보겠습니다.
Let's see what this means. Okay, let's have the following task and it says find the sales price for each order by dividing the sales by quantity.
7:39:55
각 주문의 판매 가격을 찾는 작업을 수행하겠습니다.
So let's go and solve it. This should be very easy. So we need.
7:40:00
주문 ID와 판매량이 필요합니다.
the order id we need the sales
7:40:03
판매 주문에서
and the quantity from
7:40:06
실행해 보겠습니다.
sales orders let's
7:40:09
이제 10개의 주문이 있으며 이는 판매입니다.
go and execute it so now we have 10 orders those are the sales
7:40:13
가격은 판매량으로 나누면 됩니다.
and the quantity so now it's very easy to calculate
7:40:16
가격을 계산할 수 있습니다.
the price it's gonna be the sales divided
7:40:19
판매량이 0인 경우가 있습니다.
by quantity and we're gonna call it price so let's go and execute it now as you can see we got an error says divide by zero error encountered so that means
7:40:30
문제가 발생하니 데이터를 다시 확인해 보겠습니다.
somewhere we have a zero for the quantity and this
7:40:33
전체를 주석 처리하고
is a problem let's go and check the data again so i'm just
7:40:36
실행해 보겠습니다.
gonna comment the whole thing and let's
7:40:39
주문 ID 10에서 수량이 0입니다.
go and execute it so now by checking the result yes we
7:40:42
주문 ID 10에 대한 수량이 0입니다.
got for the order id 10 here we have quantity zero
7:40:45
물론 0으로 나누면 작동하지 않습니다.
so it will not work if you divide by zero of course so
7:40:48
우리가 해결할 수 있는 방법은 널의 마법을 사용하는 것입니다.
how we can solve it we can use the magic of the null f
7:40:51
여기서 0을 대체할 것입니다.
where we're gonna go and replace the zero with a
7:40:54
널을 얻는 것이 오류를 얻는 것보다 훨씬 낫습니다.
null so getting a null is way better than getting an
7:40:58
오류입니다. 이제 주석을 제거하겠습니다.
error right so let's go and do that i'm just gonna remove
7:41:01
주석을 제거하고 여기서 널이라고 말할 것입니다.
the comments and here we're gonna say null if
7:41:04
수량이 0 값과 같다면.
if the quantity equal to the zero value so
7:41:08
그게 전부입니다. 이제 실행해 보겠습니다.
that's it let's go and execute it now as you
7:41:11
작동하는 것을 볼 수 있으며, 우리는 0으로 나누지 않고 있습니다.
can see it is working and with that we are making sure that we
7:41:14
널로 대체했기 때문입니다.
are not dividing by zero and that's because we replace it
7:41:18
널을 나누면 널이 됩니다.
with a null and if you divide anything by null you will
7:41:21
주문 10의 결과를 확인하면 가격이 널입니다.
get a null so if you check the result over here the order 10 we got the price of null which is correct and for the all other values
7:41:28
모든 것이 작동하고 있습니다. 우리는 값을 가지고 있습니다.
everything is working because we have values and we didn't replace
7:41:32
널로 대체하지 않았기 때문에 가격에 대한 값이 있습니다.
it with a null that's why we have values for the price
7:41:35
널의 일반적인 사용 사례입니다.
and this is very common use case for the null if we can
7:41:38
0으로 나누는 것을 방지하기 위해 사용할 수 있습니다.
use it in order to prevent dividing by zero
7:41:41
모두
all
7:41:45
좋아, null이란 무엇인가? 그것은 true를 반환할 것이다.
right so what is is null it's gonna return true
7:41:48
값이 null이면 그렇다.
if the value is null so it is
7:41:51
값을 확인하는데, 만약 null이면 true를 반환할 것이고 그렇지 않으면
checking the value if it's null it's gonna return true otherwise
7:41:55
false를 반환할 것이다. 이제 정확히 반대의 경우는
it's gonna returns a false now the exact opposite if
7:41:58
is not null을 사용하면, 그래서 이러한 키워드를 사용하면
you go use the is not null so if you use these
7:42:01
값이 null이 아닐 경우 true를 반환할 것이고
keywords it's gonna returns a true if
7:42:04
값이 null이면 false를 반환할 것이다. 알겠지? 그러니까 그 문법은 매우 간단하다. 값이나 표현식으로 시작한다.
the value is not null otherwise if it is null it's gonna go and return a false okay so the syntax for that is very simple it starts with a value or expression
7:42:13
그런 다음 우리는 키워드가 null인지 확인할 것입니다.
and then after that we're gonna have the keyword is space null and the is not is exactly the same So we have a value then afterwards we have that is not null.
7:42:23
그렇다면 우리는 not 연산자를 사용할 것입니다.
So we have the not operator after that and that is not is exactly the same.
7:42:27
우리는 배송 주소의 값이 null인지 확인하고 있습니다.
So we have a value then we have that is not the not operator than the null. So it's very simple. Let's have an example.
7:42:34
배송 주소가 null인지 확인할 수 있습니다.
We are checking whether the values of the shipping address is null.
7:42:37
배송 주소는 null이 아닙니다.
So we can have it like this shipping address is null or we can check the opposite whether it's not null.
7:42:43
우리는 값을 확인하고 있습니다.
So the shipping address is not null. It's very easy. Okay, so now let's understand how this works.
7:42:49
값이 null인지 확인하고 있습니다.
we are checking the value so if the value is null
7:42:52
null이 아닐 경우 true를 반환합니다.
then return a true if it is not null
7:42:55
그렇지 않으면 false를 반환합니다.
then we return a false so as you can see it never returns
7:42:58
값 자체 또는 null을 얻고 있습니다.
the value itself or any nulls so we are getting a boolean
7:43:01
true와 false의 불리언을 생성하고 있습니다.
of true and false so we are creating
7:43:05
불리언 플래그를 생성하여 확인을 도와줍니다.
like a boolean flag in order to assist us with the checks
7:43:08
가격이 null인지 확인하는 간단한 예입니다.
so we have this very simple example price is null and we
7:43:11
첫 번째 주문의 가격은 null이 아닙니다.
have those two rows so we are checking whether the price is null in the first order it is not null right that's why we will get
7:43:18
출력에서 false를 얻을 것입니다.
a false in the output and the second order the value
7:43:21
두 번째 주문의 값은 null입니다.
is null so it is correct that's why we'll get
7:43:25
그렇기 때문에 true를 얻을 것입니다.
true now of course if we go and use the is not null
7:43:28
가격이 null이 아닙니다.
it's going to be exact opposite so is the price
7:43:31
여기서 true를 얻을 것입니다.
and not null well yes it's not null that's why you
7:43:35
그것은 null입니다.
will get a true over here so now for the second check
7:43:38
출력은 false가 될 것입니다.
it is null right so the output is going to be false we will get the exact opposite so that's it it's very simple how the is null and is not null works
7:43:51
is null 및 is not null의 명백한 사용 사례입니다.
all right one very obvious use case for is null and is not
7:43:54
누락된 정보를 검색하는 것입니다.
null is by searching for missing informations or
7:43:58
null을 검색하고 있습니다.
searching for nulls and maybe after that we can go and clean up
7:44:01
데이터 세트에서 null을 제거하여 데이터를 정리합니다.
our data by removing the nulls from our data sets
7:44:04
다음 작업을 수행해 보겠습니다. 점수가 없는 고객을 식별하라고 합니다. 자, 시작해 봅시다.
let's have the following task and it says identify the customers who has no scores all right let's go and solve it this is very simple so let's start
7:44:13
판매 고객에서 별을 선택하여
by selecting star from sales customers
7:44:17
모든 것을 필요로 하니 이제 실행해 봅시다.
so we need everything let's go and execute it now
7:44:20
우리가 다섯 명의 고객을 가지고 있지만, 작업에서는
as you can see we have our five customers but the task says we have to have
7:44:23
점수가 없는 모든 고객을 가져와야 합니다.
all the customers who have no score so
7:44:26
결과는 마지막 고객만 반환해야 합니다.
that means the result should return only the last
7:44:29
안나의 점수가 null이므로 where 절을 추가합시다. 우리는 점수가 필요합니다.
record since the score of anna is null so let's go and have a where clause so where and now what do we need we need the score then we don't
7:44:39
같은 방식으로 null을 사용합니다. 이제 실행해 봅시다.
use the equal we use is null like this. So that's it. Let's go and execute it.
7:44:45
이렇게 하면 데이터가 필터링되고 점수가 null인 모든 고객을 볼 수 있습니다.
And with that, as you can see, it's very simple. We have filtered our data and now we can see all the customers where the score is null.
7:44:52
이것은 데이터에 null이 포함되어 있는지 확인하는 아주 기본적인 검사입니다.
This is a very basic check to understand whether our data contains nulls.
7:44:56
다음 작업으로 넘어가겠습니다. 점수가 있는 모든 고객의 목록을 보여달라고 합니다.
All right, moving on to the next task and it says show a list of all customers who have scores.
7:45:01
이제 예제로 돌아가서, 이번에는 정반대의 작업을 하겠습니다.
So back to our example, this time we're going to do exactly the opposite.
7:45:05
점수가 있는 모든 고객의 목록을 원합니다.
We want a list of all customers where we have a value in the scores.
7:45:09
점수가 null이 아닌 고객을 가져오도록 하겠습니다.
So what we're going to do, we're going to say where score is not null.
7:45:14
이렇게 하면 점수 필드 내의 모든 null을 제거할 수 있습니다.
So if you go and execute it, you can see we're going to get a clean list where all the customers have a score.
7:45:19
이제 매우 흥미로운 사용 사례로 넘어갑니다.
And with that, we get rid of all nulls inside the score field. and maybe this is helpful in order to do further analyzes.
7:45:30
null에 대한 흥미로운 사용 사례로, 테이블 간의 새로운 조인 유형을 도입하겠습니다.
All right, friends, now we come to very interesting use case for the is
7:45:33
두 테이블 간의 일치하지 않는 행을 찾는 데 도움이 될 것입니다.
null, and that is by introducing a new type of joints between tables that's going to help us to find the unmatching rows between two tables.
7:45:43
SQL의 조인에 대해 간단히 복습해 보겠습니다.
Let's have a quick recap about the joints in SQL in order to understand the new types.
7:45:48
기본적으로 두 개의 집합, 즉 두 개의 테이블이 있습니다.
So basically, we have two sets or let's say two tables, the
7:45:51
왼쪽과 오른쪽 테이블이 있으며, 내부 조인을 사용하면
left and the right and if you go and use an inner join
7:45:54
왼쪽 테이블과 오른쪽 테이블 간의 일치하는 행만 찾습니다.
what we are doing here we are finding only the matching rows
7:45:58
결과적으로 일치하는 행만 얻게 됩니다.
between the left table and the right table so at
7:46:01
이제 왼쪽 외부 조인이라는 또 다른 조인 유형이 있습니다.
the result we will get only the matching rows now we
7:46:04
이 유형을 사용하면 모든 결과를 얻을 수 있습니다.
have another type of joints called left outer join
7:46:07
이 유형을 사용하면 모든
and if you use this type at the result you will get all
7:46:10
왼쪽 테이블의 행과 일치하는
the rows from the left table and as well only
7:46:14
행을 가져옵니다. 이제 우리는
the matching rows from the right table now we
7:46:17
정확히 반대인 오른쪽 조인을 배웁니다. 여기서는 오른쪽 테이블의 모든 행과 왼쪽 테이블의 일치하는 정보만 가져옵니다.
have another type which is exactly the opposite the right join and here we're gonna get all the rows from the right table and only the matching informations from the left table.
7:46:27
우리가 배운 마지막으로, 전체 조인을 통해 왼쪽의 모든 행과 오른쪽의 모든 행을 가져옵니다.
And now to the last time that we learned, we have the full join where we will get all the rows from the left and as well all the rows from the right.
7:46:34
우리는 아무것도 놓치지 않을 것입니다. 그래서 이것들은
So we will not be missing anything. So those are
7:46:37
SQL에서 우리가 배운 네 가지 기본 조인입니다. 그러나 SQL에는 더 고급 유형도 있습니다.
the four basic joints that we have learned in SQL, but in SQL we have as well other types that are more advanced, but we don't have in SQL any keywords for that.
7:46:47
첫 번째는 리프트 안티 조인이라고 합니다.
So the first one called lift anti join.
7:46:51
여기서 우리가 말하는 것은 왼쪽 테이블의 모든 행이 필요하지만, 이번에는 일치하는 행 없이 필요합니다.
So what we are saying here, we need all the rows from the left table, but this time without the matching rows.
7:46:58
오른쪽 테이블과 일치하는 모든 정보는 결과로 보고 싶지 않습니다.
So all the information that are matching with the right table, we don't want to see it as a result.
7:47:03
이 유형의 조인에 대한 추가 키워드는 없습니다.
And as I said, we don't have here an extra keyword for this type of join.
7:47:07
이 효과를 얻기 위해 왼쪽 조인과 is null을 결합할 것입니다.
But in order to get this effect, we're going to go and combine the left join together with the is null.
7:47:13
이것을 왼쪽 안티 조인이라고 부르며, 또 다른 고급 유형이 있습니다.
And with that, we're going to get all the data from the left side, but without anything that is matching the right side.
7:47:19
조인을 위한 유형으로 오른쪽 안티 조인이라고 합니다.
this we call it left anti-join and we have another advanced
7:47:23
이것은 정확히 반대입니다. 그래서 우리는 모든
type for the joints called the right anti-join
7:47:26
오른쪽 테이블의 행을 가져오고 왼쪽 테이블의
this is exactly the opposite so we are saying all
7:47:29
일치하는 행 없이 가져옵니다. 그래서 모든
the rows from the right table without having any
7:47:32
정보는 오른쪽에 있으며 왼쪽과 일치하지 않습니다.
matching rows from the left table so all the
7:47:35
여기서도 키워드가 없으므로
information is on the right side that is not matching the left side
7:47:38
오른쪽 조인과 is null을 함께 사용합니다.
so again here we don't have a keyword for that we're gonna go and
7:47:41
그것으로 두 가지 새로운 조인 유형이 추가되었습니다.
work with the right join plus and is null so
7:47:45
우리의 네 가지 기본 조인에 추가되었습니다. 이제 이것은 혼란스러울 수 있습니다.
with that as you can see we have two new types of joins added
7:47:48
이해하기 위해 다음 작업을 수행합시다. 모든
to our four basic joins now this might be confusing let's
7:47:51
주문을 하지 않은 고객에 대한
have the following task in order to understand it show a list of all
7:47:54
세부 정보를 보여줍니다. 자, 효과를 만드는 방법을 봅시다.
details for customers who have not placed
7:47:58
주문을 하지 않은 고객에 대한 세부정보
any orders all right so let's see how we can create the effect
7:48:01
왼쪽 안티 조인을 만드는 방법을 살펴보겠습니다
of the left anti-join so let's do it step by step
7:48:04
여기에는 두 개의 테이블이 필요합니다. 고객과
we need here two tables we need the customers and
7:48:07
주문을 포함하여 고객에 집중하고 있으므로 왼쪽 테이블은 고객이 됩니다.
as well the orders so since we are focusing on the customers the left table gonna be the customers so let's go and do that we're gonna go and say select
7:48:17
이것이 우리의 첫 번째 테이블입니다.
star from sales customers
7:48:20
우리는 c라는 별칭을 사용하고 있습니다.
this is our first table so we
7:48:23
이제 모든 고객 목록을 얻었습니다.
are using the alias of c so let's go and execute it
7:48:27
모든 고객에 대한 세부정보를 얻었지만 이제 조인을 해야 합니다.
now as you can see we got the list of all customers so that we have
7:48:30
주문과 조인하기 위해
all the details for our customers but now we have to go and join
7:48:33
새로운 줄에서 왼쪽 조인을 하겠습니다.
it with the orders so in order to do that let's
7:48:37
주문과 함께 별칭 o를 사용하겠습니다.
have a new line left join sales sales
7:48:41
조인을 위한 키를 정의해야 합니다.
orders and let's have the alias o
7:48:44
고객 ID가 같아야 합니다.
and now we have to go and define the key for the join so
7:48:47
주문 테이블의 고객 ID와 같아야 합니다.
on it's gonna be the customer id equal
7:48:52
이제 실행해 보겠습니다.
the customer id in the order table so now if
7:48:55
주문 테이블에서 주문 ID를 표시하겠습니다.
you go and execute it now what we can do we're gonna go and show
7:48:58
주문 ID를 확인하여 일치하는지 확인하겠습니다.
the order id from the table orders so
7:49:02
이 네 개의 열은 고객 테이블에서 가져온 것입니다.
order id just to see whether we have a match or not so let's have it like this and execute it now let's go and check the results as you can see those four columns
7:49:11
마지막 열은 주문에서 가져온 것입니다.
comes from the table customers and only the last
7:49:14
주문 ID에 null이 있는지 확인해야 합니다.
column come from the orders so now what is interesting is
7:49:17
고객 1의 경우 모든 것이 있습니다.
to check the order id whether we have nulls or
7:49:20
고객 2도 주문이 있습니다.
not so as you can see for the customer one we have everything
7:49:23
고객 ID 5의 경우 null이 있습니다.
matching for the customer two as well we have orders the
7:49:27
다시 말해, 고객 Anna는 주문이 없고 다른 고객들은 주문이 있었습니다.
three as well for only the last one customer id five we have here a null so that means sql was not able to find any order for this customer.
7:49:38
우리가 오른쪽 테이블에서 값을 가지고 있기 때문입니다.
So again, what this means, we have only one customer, Anna, where she doesn't have any order, but all other customers, they did have an order.
7:49:48
그것은 우리가 오른쪽 테이블에서 값을 가지고 있기 때문입니다. 그래서 값을 가지면 일치하는 것이 있다는 의미입니다.
And that's because we have values from the right table. So once we have values, that means we have matching.
7:49:55
하지만 null이 있기 때문에 일치하는 것이 없다는 의미입니다.
But since we have a null, that means we don't have any matching.
7:49:59
이제 왼쪽 안티 조인이 우리가
So now since the left anti-joint says we
7:50:02
왼쪽 테이블의 모든 데이터를 원한다는 의미입니다.
would like to have all the data from the left table without
7:50:05
오른쪽 테이블에서 일치하는 것이 없다는 의미입니다.
having any matching from the right table so
7:50:08
이 예제에서는 고객 안나만 가져오고, 이는 우리의 작업을 충족합니다. 작업은 고객의 모든 세부 정보를 나열하라고 합니다.
that means for this example we would like to get only this customer anna and this is exactly as well fulfilling our task the task says list all details for customers
7:50:18
주문을 하지 않은 고객의 모든 데이터입니다.
who have not placed any order all data from customers
7:50:22
주문에서 일치하는 것이 없다는 의미입니다.
where we don't have matching from the orders
7:50:25
이 효과를 얻는 방법을 이미 이해했을 것이라고 생각합니다.
now i think you already got it how to get this effect we're
7:50:28
다음과 같이 데이터를 필터링할 것입니다.
gonna go and filter the data like the following so we're gonna have
7:50:32
where 절이 필요하고 이제 오른쪽 테이블의 열이 필요합니다.
the where clause and now we need the column from the right table
7:50:35
주문에서 고객 ID를 사용하겠습니다.
from the orders so we're gonna go with the customer id comes from the orders so we're gonna
7:50:41
고객 ID 또는 주문 ID는
say or customer id is
7:50:45
null이며 물론 주문 ID로 진행할 수 있습니다.
null and of course you can go with the order id
7:50:48
같은 효과를 얻을 수 있지만 항상 사용하고 싶습니다.
as well you're gonna get the same effect but i would like always to use
7:50:51
조인에 사용하고 있는 키를
the key that we are using with the join so let's
7:50:54
실행해 보겠습니다. 이제 보시다시피 우리는
go and execute it and now as you can see we got the effect of
7:50:58
리프트 안티 조인의 효과를 얻었습니다. 그리고 그로 인해 우리는
the lift anti-join and with that as you can see we got the
7:51:01
우리가 목표로 하는 고객을 얻었습니다. 여기에서 우리는
customer that we are aiming for so here we have the data from
7:51:04
오른쪽과 일치하지 않는 왼쪽의 데이터를 가지고 있습니다. 즉, 주문을 하지 않은 고객입니다. 이를 통해 우리는
the left side that is not matching the right side so the customers who have not placed an order and with that we have solved
7:51:10
작업을 해결했습니다. 보시다시피 우리는 왼쪽 안티 조인을 구현했습니다.
the task so as you can see we have implemented the left anti-join
7:51:14
왼쪽 조인을 결합하여
by combining the left join together
7:51:17
is null과 함께 사용했습니다. 이것이 바로
with the is null so this is the power
7:51:20
SQL에서 null을 다루는 힘입니다.
of playing with the nulls in sql now
7:51:27
친구들, 정말 많은 사람들을 혼란스럽게 하는 것이 있습니다.
my friends there is something that is really confuses a lot of
7:51:30
데이터와 관련된 개발자나 누구에게나 정말 혼란스러운 부분이 있습니다.
developers or anyone that is working with data in
7:51:33
데이터베이스와 SQL에서 널, 빈 문자열 및
databases and sql and that is the differences between nulls empty string and
7:51:39
빈 공간의 차이점입니다. 널은 우리가 배운 대로
blank spaces so the nulls as we learned we are
7:51:42
값이 무엇인지 모르겠다고 말하는 것입니다. 그것은 알 수 없는 것입니다.
saying i don't know what the value is it is unknown but
7:51:46
다른 한편으로, 빈 문자열은 내가
now in the other hand the empty string you are saying i
7:51:49
값을 알고 있다는 것입니다. 그것은 아무것도 아닙니다.
know the value it is nothing so the empty string
7:51:52
빈 문자열은 문자 수가 0인 문자열 값입니다.
is a string value which has a
7:51:56
이것은 널과는 완전히 다릅니다. 널에 대해서는 아무것도 알지 못합니다.
zero characters this is totally different than the nulls the nulls we don't know anything about it so now sometimes maybe happens to you as you are
7:52:03
때때로 여러분이 포럼을 작성할 때 발생할 수 있습니다.
filling a forum and you come to one field you go
7:52:06
한 필드에 도달했을 때 실수로 스페이스 바를 눌렀습니다.
and by mistake hit a space bar and with that you are
7:52:09
그로 인해 필드에 공백이 입력되고, 다른 값을 입력하지 않고
entering space into the field and you just jump to
7:52:13
다음 필드로 넘어갑니다.
the next field without entering any other values so we
7:52:16
이제 필드 안에 공백 문자가 있습니다.
have now like a space character inside the field
7:52:19
데이터베이스에서는 이것이 정말 악성입니다. 사용자가
this is really evil in databases because once the user enter
7:52:22
빈 공간을 입력하면 데이터베이스에 값으로 저장됩니다.
a blank space it's gonna go and store it as a value inside the database and it's gonna take a storage so it could be one space or many spaces depends on how long
7:52:31
공백은 문자열이지만 크기는 0이 아닙니다.
you press the space bar so the blank space is
7:52:35
빈 문자열과는 달리, 입력한 공백의 크기를 가집니다.
a string but the size is not zero like
7:52:38
여기서는 널과 같지 않습니다.
the empty string we're gonna have a size of how
7:52:41
값이 문자열이며 그 문자는 공백이 됩니다.
many spaces you have entered so here it's not like the null we
7:52:44
이제 세 가지 시나리오를 살펴보겠습니다.
know the value it is string and the character of that gonna be space
7:52:47
더미 데이터를 사용하여 도시 문을 사용하고 있습니다.
okay so let's see those three scenarios inside the scale now i have like a dummy data using the city statements don't worry about it i'm gonna teach all those stuff in the next tutorials so now we have here like four rows
7:52:59
첫 번째는 값 A입니다. 다음은 널입니다. 세 번째는 빈 문자열입니다.
The first one with a value A. The next one is null. The third one with empty string.
7:53:05
따라서 두 인용부호 사이에 아무것도 없습니다.
So as you can see, there is nothing between those two quotes. And the last one, we have a space between those two quotes.
7:53:11
마지막으로 두 인용부호 사이에 공백이 있습니다.
Now let's go and query this temporal table. So select star from orders and execute.
7:53:19
이제 이 임시 테이블을 쿼리해 보겠습니다.
So now by looking to the values of the categories, you can find all the scenarios now.
7:53:24
그래서 이제 첫 번째 시나리오는 우리가 정상 값을 가진 가장 쉬운 경우입니다.
So now the first scenario is the easiest one where we have a normal value.
7:53:28
여기 A가 있지만 나머지 세 개의 행은 정상 값이 없습니다. 우리는 빈 값이 있습니다.
We have here an A, but the other three rows, we don't have normal values. We have like empty stuff.
7:53:34
그래서 첫 번째는 null이 될 것입니다. 그래서 우리는 값이 없습니다. 이것은 SQL의 특별한 표시입니다. null이라고 합니다.
So the first one is going to be the null. So we don't have a value. This is the special marker from SQL. It says null.
7:53:41
그래서 값이 없습니다. 그리고 나머지 두 개는 정말 혼란스럽습니다.
So there is no value. And the other two, they are really confusing.
7:53:44
보시다시피, 데이터나 결과를 보고 판단하기가 정말 어렵습니다,
As you can see, it's really hard by just looking to the data or to the results,
7:53:48
빈 문자열인지 공백인지. 그리고 이것은 많은 개발자나 데이터를 다루는 사람들을 혼란스럽게 합니다.
whether it is an empty string or a blank space. And this confuses a lot of developers or anyone working with data seeing those results.
7:53:56
결과를 보고 데이터 품질 문제를 감지하기가 정말 어렵습니다.
It's really hard to detect the data quality issues by just looking at the results.
7:54:01
그래서 이제 이 시나리오에서 제가 하는 것은 제 열 안의 각 값의 길이를 계산하는 것입니다.
So now in this scenario, what I do, I go and calculate the length of each value inside my column.
7:54:06
그래서 가서 그렇게 해봅시다. 이제 SQL 서버로 가겠습니다.
So let's go and do that. Now we're going to go in the SQL server.
7:54:10
우리는 데이터 길이 함수를 사용하고 우리의 필드는 카테고리가 될 것입니다.
We're going to go and use the function data length and our field going to be the category.
7:54:16
그래서 카테고리 길이라고 부르겠습니다. 그래서 실행해봅시다. 이제 결과를 확인해봅시다.
So let's call it category length. So let's go execute it. And now let's check the results.
7:54:23
첫 번째는 우리가 단 하나의 문자를 가지고 있다고 말합니다.
the first one says we have only one character the length of that's
7:54:26
그 길이는 하나가 될 것이며, 맞습니다. 이제 다음 행으로 가면
going to be one which is correct and now to the next row we have the
7:54:29
카테고리 null이므로 우리는 값을 알 수 없고,
category null we don't know the value and as
7:54:32
값의 길이를 알 수 없으므로, 그래서 우리는 null을 얻게 됩니다.
well we don't know the length of the value right so that's why
7:54:35
이제 다음으로 이동하면서 보시다시피,
we will get a null so now by moving to the next one as you can see those
7:54:39
두 개가 정말 똑같이 보이지만 이제
two looking really exactly the same but now
7:54:42
길이 또는 데이터 길이 함수의 도움으로 우리는 세 번째 행 또는 세 번째 카테고리 값의 길이를 볼 수 있습니다.
with the help of the length or the data length function we can see that the third row or the third category value has the length of
7:54:51
그것은 빈 문자열이라는 것을 의미하며, 여기 숨겨진 문자가 없습니다.
That means it is an empty string and we don't have any characters over here that is hidden.
7:54:56
그래서 우리는 이것이 빈 문자열이라는 것을 확신합니다.
So with that we are sure this is an empty string.
7:54:58
하지만 이제 마지막으로 이동해봅시다. 여기 있습니다.
But now let's move to the last one here it is
7:55:01
매우 교활하고 악의적인 숨겨진 공백이 있습니다.
very tricky and evil we have a hidden space
7:55:05
이 값 안에 있으며, 우리는 그것을 이해할 수 있습니다.
inside this value and we can understand that by
7:55:08
이 필드의 길이로, 보시다시피 여기 하나가 있습니다.
the length of this field so as you can see we have here a one that
7:55:11
여기 숨겨진 공백이 있다는 것을 의미합니다.
means we have here one hidden space inside
7:55:14
이 값은 비어 있지 않으므로
this value and it is not empty string so
7:55:18
여기에는 공백이 하나만 있습니다. 또 하나의 공백을 추가하고 길이를 계산해 봅시다.
that means i have here only one space let's go and give it another space and calculate the length so as you can see we have two spaces and that's why the links is two.
7:55:27
그래서 이제 세 가지 시나리오를 나란히 비교해 보겠습니다.
So don't count on your eyes in order to understand the spaces. Go and calculate the length in order to be very precise.
7:55:34
그럼 이제 테이블 안에서 null로 보일 수 있습니다.
So now let's go and compare the three scenarios side by side. So let's start with the first one about the representations in the table.
7:55:41
빈 문자열은 두 개의 따옴표처럼 보이며 그 사이에 아무것도 없습니다.
Then now we can see it as a null inside the table. The empty string going to be like two quotes and nothing between them.
7:55:48
빈 공간은 두 개의 따옴표와 그 사이에 하나 이상의 공백이 있습니다.
And the blank space is as well two quotes and between them one or many spaces.
7:55:53
이제 의미에 대해 이야기하자면, null은 알 수 없는 값을 의미합니다.
And now if you are talking about the meaning, the null means unknown. We don't know the value.
7:55:58
빈 문자열은 알려져 있지만 아무것도 없습니다.
The empty string, it is known, but it is nothing. It is empty value.
7:56:04
세 번째는 빈 공간이며, 이것도 알려져 있습니다.
And the third one, blank spaces, it is as well known. And the spaces are the value.
7:56:08
이제 데이터 유형에 대해 이야기하자면, null은 값이 없기 때문에 데이터 유형이 없습니다.
And now if you are talking about the data types, since the null is no value, so we don't have a data type for this.
7:56:15
SQL에서 특별한 마커와 같습니다.
And it is like a special marker in the SQL. And now the empty string has a data type.
7:56:20
빈 문자열은 데이터 유형이 있습니다.
It is a string and the size of this string going to be zero since we have zero characters inside the empty string.
7:56:27
빈 문자열의 크기는 0이 될 것입니다.
Moving on to the blank spaces. It is a string since a space is a character and it's going to be the size of one or many.
7:56:34
빈 공간은 문자열이며, 크기는 하나 또는 여러 개입니다.
And now if you are talking about the storage, the null is the best. They don't consume or occupy a lot of storage.
7:56:40
null은 가장 좋습니다. 저장 공간을 많이 차지하지 않습니다.
While the empty string and the blank spaces, they occupy here storage and memory and they waste the space.
7:56:47
빈 문자열과 빈 공간은 저장 공간을 차지합니다.
So if you are worried about the storage, the best option here is a null.
7:56:50
저장 공간이 걱정된다면, null이 최선의 선택입니다.
Now talking about the performance, you will get the best performance if you are using nulls.
7:56:56
null을 사용하면 최고의 성능을 얻을 수 있습니다.
Now the empty string is as well fast, but it is not that fast like the nulls. Now the worst option here is the blank spaces.
7:57:03
빈 문자열도 빠르지만 null만큼 빠르지는 않습니다.
It is slow. So again, if the speed is important for you, you have to have those scenarios as a null.
7:57:08
속도가 중요하다면, null을 사용해야 합니다.
So now if you are talking about the comparison and you are searching for those values,
7:57:13
비교에 대해 이야기하자면, null을 검색하려면 is null을 사용해야 합니다.
if you want to search for the null, you have to go and use is null.
7:57:16
빈 문자열과 빈 공간을 검색하려면 등호 연산자를 사용해야 합니다.
But in the other hand, if you want to search for the empty string and the blank spaces, you have to go and use the operator equal.
7:57:22
그게 전부입니다. null, 빈 문자열, 빈 공간의 주요 차이점입니다.
So that's all. Those are the main differences between the null empty string and blank spaces.
7:57:32
이제 여러분은 이렇게 물어볼 수 있습니다.
Now you might ask, you know what? Why do I have to understand the differences between all those stuff and nulls, empty strings and the blanks?
7:57:38
모든 것이 비어 있으니, 왜 신경 써야 할까요?
Everything like empty. So why do I care? Well, in New Year Projects, I'm going to promise you that you will be working with sources and data that has bad data quality,
7:57:48
데이터에서 이러한 세 가지 시나리오를 만날 수 있습니다.
and you might encounter all those three scenarios in your data.
7:57:51
이제 데이터를 정리하는 것과 같은 데이터 준비를 하지 않으면,
And now if you don't do any data preparations like cleaning up the data,
7:57:55
이러한 세 가지 시나리오를 처리하고 데이터에 기준을 적용하지 않으면,
handling those three scenarios and bringing standards to your data and you jump immediately to the analysis without doing all those stuff,
7:58:03
보고서와 분석에서 부정확한 결과를 제공하게 되어 잘못된 결정으로 이어집니다.
you will end up providing inaccurate results in your reports and analysis which leads to wrong decisions.
7:58:10
데이터를 정리하고 이러한 세 가지 시나리오를 처리하며 기준을 적용하는 것은
So preparing your data before doing any analysis by cleaning up the data, handling those three scenarios and as well bringing standards
7:58:18
분석을 수행하기 전에 데이터를 준비하는 것이 매우 중요한 단계입니다.
is very important step before doing any analyzers
7:58:21
이제 이해관계자와 함께 이를 수행하는 방법입니다.
so this is how we're gonna do it together with the stack holders
7:58:25
보고서와 분석의 사용자들은
and the users of your reports and analyzers you
7:58:28
명확한 데이터 정책을 정의해야 합니다.
have to define a clear data policies it's
7:58:31
규칙과 같으며 구현 중에 스스로에게 약속해야 합니다.
like rules and you have to commit yourself during the implementations
7:58:35
이러한 규칙을 따르며 세 가지 다른 옵션이 있습니다.
by following those rules and here we have three different options the first one you can go and define the data
7:58:41
첫 번째는 데이터를 정의하는 것입니다.
policies like this only use nulls and empty string
7:58:44
정책은 null과 빈 문자열만 사용합니다.
but avoid using blank spaces in
7:58:47
하지만 공백 사용은 피해야 합니다.
my projects i cannot imagine that there is a scenario
7:58:51
내 프로젝트에서는 공백이 필요한 상황을 상상할 수 없습니다.
where we need blank spaces they are just evil
7:58:54
그들은 그저 악입니다.
just go and get rid of them all right with this policy we have to
7:58:57
모두 제거하세요. 이 정책으로 우리는
go and get rid of all blank spaces inside our data and
7:59:00
우리 데이터 내의 모든 공백을 제거해야 합니다.
in order to do that we have a wonderful function in sql called trim
7:59:04
그렇게 하기 위해 SQL에서 trim이라는 멋진 기능이 있습니다.
the trim function in sql gonna go and remove the spaces from a string from the left side and as well from the right
7:59:11
trim 함수는 문자열의 왼쪽과 오른쪽에서 공백을 제거합니다.
side so all the leading spaces and the trailing
7:59:14
모든 선행 공백과 후행 공백이 제거됩니다.
space is going to be removed so now if you go and apply that trim function on
7:59:17
이제 trim 함수를 적용하면
that category what's going to happen all the blank space is
7:59:20
모든 공백이 제거되고 빈 문자열로 변환됩니다.
going to be removed and it's going to be turned into empty
7:59:24
이제 trim 함수를 사용하여
string so let's go and do that it's very simple so we're
7:59:27
정책 1이라고 부르겠습니다.
going to use the trim function and we're going to apply it on that
7:59:30
카테고리, 정책 1이라고 부르겠습니다. 그래서 실행해 보겠습니다. 이제 정책 1과 카테고리를 비교해 보면, 동일하지만 그렇지 않습니다.
category let's go and call it policy one so let's go and execute it so now by just comparing the policy one with the category, you see like it's identical, but it's not.
7:59:42
이제 이 내용을 더 잘 이해하기 위해 데이터 길이를 사용해 테스트해 보겠습니다.
Now, in order to have a better feeling about this, we can go and test it using the data length.
7:59:47
이제 다시 데이터 길이 함수를 사용하여 전체 결과에 사용할 수 있습니다.
Now let's go again and use the data length function so we can use it for the whole results.
7:59:53
그리고 카테고리에도 사용하여 비교해 보겠습니다. 그래서
And as well, I'm going to go and use it for the category in order to just compare it. So without the
8:00:00
이렇게 해서 실행해 보겠습니다.
So like this, let's go and excuse it.
8:00:06
이제 결과를 확인해 보면, 여기서 두 개의 공백이 있기 때문에 길이가 2입니다. 그러나 정책 1은 0입니다.
Now, if you go and check the result, as you can see here again, we have the length of two because here we have two spaces, but with the policy one, we have zero.
8:00:14
그래서 이 두 값은 용어 함수를 적용한 후 길이가 0입니다.
So those two values after applying the term function, they have the length of zero.
8:00:20
그리고 그로 인해 공백이 없습니다. 즉, 이제 트림을 적용한 후 null 또는 빈 문자열이 확실합니다.
And with that, we don't have blank spaces. So that means now we are sure after applying the trim, we have either null or empty string.
8:00:29
그래서 모든 정보를 제거하겠습니다. 이제 두 개 모두 빈 문자열이라는 것이 확실합니다. 보시다시피 매우 간단합니다.
So let me just get rid of all those informations. Now I am sure both of them are empty string. So as you can see, it's very simple.
8:00:36
하나의 SQL 함수만 사용하여 데이터를 정리하고 표준을 가져옵니다.
Using only one SQL function, you are cleaning up the data and bringing standards.
8:00:41
좋습니다, 옵션 2로 넘어가겠습니다. 데이터 정책을 이렇게 정의할 수 있습니다.
All right, moving on to the option two, you can define your data policies like this.
8:00:45
null만 사용하고 빈 문자열과 공백을 모두 피하십시오.
Only use nulls and avoid both empty strings and as well blank spaces.
8:00:51
즉, 우리 비즈니스에서는 빈 문자열과 공백에 대해 의미 있는 것이 없습니다.
So that means in our business, we don't have anything meaningful for the empty string and the blank spaces.
8:00:57
우리는 null만 사용할 수 있습니다. 이제 가서
we can go and use only the nulls okay so now let's go and
8:01:00
이 규칙을 구현하려면 값을 변환해야 합니다.
implement this rule we have to go and convert a value
8:01:03
null로, 빈 문자열로 변환될 값입니다.
to a null so the value going to be empty string to
8:01:06
null로, 우리가 배운 대로 null if 함수를 사용할 수 있습니다.
a null and as we learned we can go and use the null if function
8:01:09
값 대신 null을 얻기 위해서입니다.
in order to get nulls instead of values so
8:01:12
이 정책을 적용해 보겠습니다. 그러나 이제 두 개의 값이 있습니다.
let's go and apply this policy but now here we have two values
8:01:16
빈 문자열과 공백입니다. 이제 두 개의 규칙 대신 먼저 공백을 빈 문자열로 변환하겠습니다.
the empty string and spaces now instead of having two rules for that i'm going to convert first the blank spaces to an empty string like we have done here
8:01:26
이 함수의 결과를 먼저 가져오겠습니다.
so i'm going to take the result of this function first
8:01:29
첫 번째 단계로, 이후에 가서
as a first step and afterwards we're going to go
8:01:32
null if를 사용할 것입니다. 그래서 우리는 말할 것입니다.
and use the null if so we're going to say
8:01:35
결과에 대해 null if
null if for the result of
8:01:38
트림에서 빈 문자열을 찾으면
the trim if you find any empty strings
8:01:42
null로 변환되었으니 그게 정책입니다
converted to null so that's it policy
8:01:45
결과에서 볼 수 있듯이 두 개를 변환했습니다
two so as you can see in the result we have converted those
8:01:48
빈 공간과 판자를 null로 변환했습니다
empty spaces and planks to a null so
8:01:51
우리와 함께 세 개의 null을 얻고 있으며, 물론 값 a를 얻을 것입니다
with us we are getting three nulls and of course we're gonna get the value a
8:01:54
이제 세 개의 열을 나란히 비교하면
and now if you compare those three columns side by side you're gonna
8:01:57
정책 2가 정말 이해하기 쉽다는 것을 알 수 있습니다
see the policy two is really easier to understand
8:02:00
이전 것들과 비교했을 때, 이제 정책 2를 정책 1과 비교하면
compared to the previous ones right so now if you compare
8:02:03
정책 2를 정책 1과 비교하면 이해하기 더 쉽고
the policy two now to the policy one you can see it's easier to
8:02:07
데이터 정리를 두 개의 함수로 하는 것이 매우 쉽습니다
understand and it's easier as well to handle so again
8:02:10
이제 우리의 데이터 안에 표준이 생겼습니다
it's very easy to do data cleanup with only two functions
8:02:13
이제 마지막 옵션으로 넘어가서 데이터 정책을 정의할 수 있습니다
we have now like standards inside our data and
8:02:16
이처럼 기본값 unknown만 사용하세요
now moving on to the last option we can define our data policy
8:02:19
그리고 null과 같은 다른 것은 사용하지 마세요
like this use only a default value unknown
8:02:23
빈 문자열과 빈 공간은 즉,
and avoid using anything else like nulls
8:02:26
분석기와 보고서에서 값 unknown을 보고 싶습니다
empty strings and blank spaces so that means in
8:02:29
우리는 이 세 가지 정보를 처리하고 변환해야 합니다
the analyzers and reports we want to see the value unknown and
8:02:33
그들을 unknown으로 변환해야 하므로 정책을 구현하기 위해
we have to handle all those three informations and convert
8:02:36
null을 변환해야 하므로
them to unknown so now in order to implement the policy
8:02:39
값 기본값을 사용해야 하며, 여기 두 가지 옵션이 있습니다
three we have to go and convert a null with a
8:02:42
is null을 사용하거나 cowlis를 사용할 수 있습니다
value a default value and here we have two options either use
8:02:45
저는 coalesce를 사용할 것입니다
the is null or we can go and use the cowlis and
8:02:48
coalesce를 사용하고 직접 카테고리를 사용할 것입니다
i will go with the coalesce so coalesce and
8:02:52
null을 발견하면 기본값 unknown으로 교체하세요
i'm gonna use directly the category so if you find
8:02:56
정책 3이라고 부르겠습니다
any null replace it with the default value unknown
8:02:59
가서 실행해 보겠습니다
and let's call it policy three so let's
8:03:02
가서 실행해 보겠습니다. 이제 여기 결과를 확인하면
go and execute it so now if you check the result over here you
8:03:05
한 번만 정확하게 얻었다는 것을 알 수 있습니다. 그래서 null을 unknown으로 대체했지만 여전히 빈 공간과 공백이 있습니다. 그건 우리가 서두른 때문입니다.
see that we got it only once correct so we replace the null with the unknown but we still have like empty spaces and blanks and that's because we rushed
8:03:14
qualis를 사용하고 다른 단계를 건너뛰었기 때문에 데이터를 준비하는 것은 천천히 단계별로 해야 합니다. 먼저 모든 것을 null로 변환해야 합니다.
using the qualis and we skipped the other steps so as you can see preparing the data you have to do it slowly step by step so first we have to go and convert everything to a null like the policy two
8:03:25
그 후 마지막 단계로 기본값을 사용할 것입니다.
and after that the last step we're gonna go and use the default
8:03:28
즉, 카테고리를 사용하는 대신
value so that means instead of using the category we have
8:03:31
정책 두의 결과를 얻어야 합니다. 그러니
to go and get the result of the policy two so let's
8:03:34
가서 복사하고 카테고리를 대체합시다.
go and copy it and replace the category with
8:03:37
그 두 단계를 거쳐 실행해 보겠습니다.
those two steps and let's go and execute it
8:03:40
이제 보시다시피 모든 것에 대한 기본값이 있습니다.
so now as you can see we have the default value for all those
8:03:44
세 가지 시나리오에서 먼저 데이터를 다듬어야 합니다.
three scenarios first we have to trim the data in
8:03:47
빈 공간을 모두 제거하기 위해서입니다. 두 번째 단계는
order to remove all the blank spaces the second step we're
8:03:50
모든 빈 문자열을 null로 대체하는 것입니다.
gonna go and replace all the empty strings with
8:03:53
그렇게 하면 세 가지 모두에 대해 null을 얻을 수 있습니다.
a null and with that we're gonna get a null for all those three
8:03:57
마지막으로 null을 기본값인 unknown으로 대체할 것입니다.
scenarios and finally we're gonna go and replace the
8:04:00
이것이 세 가지 정책에 대한 내용이며, 데이터 정리를 위한 다양한 방법입니다.
nulls with a default value the unknown so
8:04:03
데이터를 정리하고 표준을 가져오기 위해서입니다.
that's it for the three policies and this is the different ways in
8:04:06
이제 세 가지 정책에 대한 내용이 끝났습니다.
order to clean up the data and bring standards before doing
8:04:10
어떤 것을 사용해야 할지 물어보실 수 있습니다.
analyzes and now you might ask me okay which one should
8:04:13
내 프로젝트에서 무언가를 제안하고 싶다면
i use in my project like if i want to suggest something for the
8:04:16
사용자에게 어떤 것을 사용해야 할까요? 정말 비즈니스에 따라 다릅니다.
users which one should i use well it really depends on
8:04:19
항상 이 정책을 피하려고 합니다.
the business but i try always to avoid this one the
8:04:22
항상 혼란스럽고 사용자에게 설명해 주었습니다.
policy one because it's always confusing and i have always explained
8:04:26
이제 두 번째와 세 번째가 남았습니다.
for the users so now we are left with the two and three will
8:04:29
다양한 시나리오에서 두 가지를 모두 사용합니다.
i use both of them in different scenarios i normally go with the policy too because it takes less storage and as well the the performance of your queries afterward can be really good.
8:04:38
테이블에 삽입하기 전에 ETL에서 데이터 준비를 할 때 정책 두를 사용합니다.
So if I'm doing data preparations in my ETL before inserting it inside a table, I go with the policy two.
8:04:46
하지만 다른 한편으로, Tableau나 Power BI와 같은 보고서에 표시하기 전에 준비 단계를 수행하는 경우.
But in other hand, if I'm doing a preparation step before showing it in a report like in Tableau or Power BI.
8:04:52
그래서 그것이 표시하기 직전의 마지막 단계 중 하나라면
So if it is like one of the last steps before showing
8:04:56
사용자에게 데이터를 제공하기 위해 정책 3을 따릅니다.
the data to the users, I go with the policy three,
8:04:59
보고서에 null을 표시하면 정말 어렵기 때문에
because if you present a null inside a report it's gonna be really hard
8:05:03
읽기 쉬운 것이므로 '알 수 없음'과 같은 단어를 사용하는 것이 좋습니다.
to read so having like a word like unknown
8:05:06
여기 누락된 데이터가 있다는 것을 이해하기가 더 쉽습니다.
it's easier to understand okay we have here missing data so
8:05:09
다시 말해, 데이터를 제공하기 직전의 데이터 준비가 정확하다면
again if the data preparations is exactly before i present
8:05:13
사용자에게 데이터를 제공하기 위해 정책 3을 따릅니다.
the data to the users i go with the policy three where i
8:05:16
기본값을 사용하지만 데이터베이스에 삽입하기 전에 데이터 준비를 하는 경우 정책 2를 따릅니다.
use default values but if i'm using data preparations before inserting it in the database i go with the policy two because it can
8:05:24
저장 최적화가 가능하며, 정책 3을 따르는 것은 정말 나쁩니다.
optimize the storage and it's going to be really bad if
8:05:27
알 수 없는 값이 없을 때마다 전체 세계를 저장하는 것은 정말 나쁩니다.
you go with the policy three because it's really bad to store the
8:05:30
값이 없을 때마다 전체 세계를 저장하는 것은 많은 공간을 차지할 것입니다.
whole world each time there is no value like the unknown it's
8:05:34
쿼리를 작성할 때 성능이 나빠질 것입니다.
going to take a lot of space and as well you're going to get bad performance as
8:05:37
쿼리를 작성할 때 성능이 나빠질 것입니다.
you are building the queries that's why i tend to store the data
8:05:40
사용자에게 표시할 때 null을 사용하고
using nulls if you present it to the users go and
8:05:43
기본값으로 표시하는 것이 매우 중요합니다.
show it as a default value so as you can see it's very important to understand
8:05:47
null, 빈 문자열 및 공백의 차이를 이해하는 것이 중요합니다.
the differences between the nulls empty strings and blanks and how to prepare the data by cleaning up the data and bringing standards and policies before doing any analysis.
8:05:56
이로써 이러한 시나리오 간의 혼란을 해소했습니다.
So with this, we have clear up the confusion between those scenarios and if you encounter it in your projects, you know how to deal with it.
8:06:07
자, 이제 null에 대한 간단한 요약을 해보겠습니다.
All right, so now let's have a quick summary about the nulls. Nulls are special markers in SQL in order to say there is no value, it is missing, it is unknown.
8:06:16
null은 값이 없음을 나타내는 특별한 표시입니다.
So nulls are not equal to zero or empty string or any blank spaces.
8:06:22
null은 0이나 빈 문자열 또는 공백과 같지 않습니다.
And using nulls inside our databases is going to save some storage and as well provide a strong performance in your queries.
8:06:29
우리 데이터베이스에서 null을 사용하면 저장 공간을 절약할 수 있습니다.
And in SQL, we have different functions in order to handle the nulls.
8:06:32
이제 null을 값으로 대체하려면
So now if you want to replace a null with the value, we can go either with the function Cowelless or is null.
8:06:38
값을 null로 대체하려면
Or if you want to do the opposite where you want to replace a value with null, you can go use the function null if.
8:06:43
null이 있는지 여부만 확인하고 싶습니다.
Or in other cases, we want only to check whether there is nulls or not.
8:06:48
우리는 is null 또는 is not null을 사용할 수 있습니다.
We can use the is null or is not null.
8:06:51
우리는 null을 처리해야 한다는 것도 배웠습니다. 특히 작업을 수행하기 전에 말이죠.
And we have learned as well that we have to treat the nulls especially before doing any tasks.
8:06:56
즉, 평균, 합계, 최대값, 최소값과 같은 데이터 집계를 수행하기 전에 null을 처리해야 합니다.
So that means we have to handle the nulls before doing, for example, data aggregations like average, sum, max, min, and so on.
8:07:04
그리고 우리는 두 문자열을 연결하기 위해 더하기 연산자를 사용하는 것과 같은 수학적 작업을 수행하기 전에 null을 처리해야 합니다.
And we have to handle the nulls as well before doing any mathematical operations like using the plus operator to concatenate two strings.
8:07:12
그리고 다른 경우에는 데이터를 정렬하기 전에 null을 처리해야 합니다.
And in some scenarios, as we learned, we have to handle the nulls as well before doing joins.
8:07:16
그리고 우리는 조인과 isNull을 결합하여 새로운 유형의 조인을 도입하는 것도 배웠습니다.
And in other cases, we have as well to handle the nulls before sorting the data.
8:07:21
예를 들어, 왼쪽 반조인과 오른쪽 반조인을 배웠습니다. 여기서 우리는 isNull을 사용하여 일치하는 행을 제외합니다.
And we have learned as well, by combining the joins and the isNull, we introduce new types of joins.
8:07:27
그리고 우리는 데이터에서 기준과 데이터 정책을 제공하기 위해 null 함수를 사용할 수 있습니다.
Like as we learned, the left anti-join and the right anti-join. Where we exclude the matching rows using the isNull.
8:07:34
예를 들어, null을 사용하거나 알 수 없는 것과 같은 기본값을 사용할 수 있습니다.
And we can use the null functions in order to provide standards and data policies in our data.
8:07:40
널 값이나 알 수 없는 기본값을 사용하는 것과 같습니다.
Like using the nulls or using default values like the unknown.
8:07:44
좋아요, 친구들. 이제 여러분은 데이터 내에서 널 값을 처리하는 방법을 배웠습니다. 이제 우리는 케이스 문이라는 매우 특별한 주제로 넘어가겠습니다.
Alright my friends, so with that you have learned how to handle the nulls inside your data. And now we're going to move to a very special topic called the case statements.
8:07:51
데이터 변환을 수행하기 위한 매우 중요한 도구입니다. 자, 시작해봅시다.
This is very important tool in order to do data transformations. So let's go.
8:08:00
케이스 문은 SQL 쿼리에서 조건부 논리를 구축할 수 있게 해주며, 조건 목록을 하나씩 평가하고 첫 번째 조건이 충족되면 값을 반환합니다.
Case statements, it can allow you to build a conditional logic in your SQL query by evaluating a list of conditions one by one and return a value when the first condition is met.
8:08:11
이제 케이스 문의 구문과 그 의미를 이해해 봅시다.
So now let's understand the syntax of the case statements and what this means.
8:08:19
좋아요, 이제 구문을 단계별로 살펴보겠습니다. 'case'라는 키워드로 시작합니다.
Okay, so now let's see the syntax step by step. It starts with the keyword case.
8:08:23
이 케이스는 이제 SQL에서 논리, 조건부 논리를 시작하고 있음을 나타냅니다.
This case indicates now we are starting a logic, a conditional logic in SQL.
8:08:28
프로그래밍 언어와 같아서 'if'와 'else'로 시작합니다.
It's like programming languages as you start with the F else.
8:08:30
여기서 'if'는 논리의 키워드이며 전체 논리는 'end'라는 또 다른 키워드로 끝납니다.
So the F is the keyword of a logic and the whole logic as well ends with another keyword called end.
8:08:37
SQL이 'end'를 만나면 이것이 조건부 논리의 끝입니다.
So once SQL sees the end, so this is the end of the conditional logic.
8:08:41
케이스는 시작이고, 끝은 끝입니다. 그러므로 이제 그 사이에 조건부 논리가 있을 것입니다, 맞죠?
So the case is a start and the end is the end. So now what we're going to have in between is the conditional logics, right?
8:08:48
조건부 논리는 'when'이라는 키워드로 시작합니다. 이제 SQL에 평가할 조건이 있음을 알리고 있습니다.
So the conditional logic starts with the keyword when. Now we are telling SQL we have a condition to be evaluated.
8:08:54
그런 다음 우리는 그 조건부 논리를 구체화할 것입니다. 이제 이 조건이 충족되면 SQL에 무엇이 발생할지를 알려야 합니다.
And then we're going to go and specify that conditional logic. So now we have to tell SQL what can happen if this condition is fulfilled.
8:09:02
이제 'then'이라는 또 다른 키워드를 사용해야 합니다.
So now we have to use another keyword called then.
8:09:05
이제 우리는 SQL에 조건이 참일 경우 이러한 결과를 보여주라고 말하고 있습니다. 보시다시피, 매우 간단합니다.
So now we are telling SQL show these results if the condition is true. So as you can see, it's very simple.
8:09:11
자연어와 같습니다, 맞죠? 영어로 'when'과 같습니다.
It's like the natural language, right? It's like in English. when
8:09:14
조건이 충족되면 결과를 보여줍니다.
the condition one is met then show the results it's very
8:09:17
논리적으로 맞고 이제 두 번째 조건을 추가할 수 있습니다.
logic right and now of course we can go and add a second condition inside
8:09:21
조건이 충족되면 두 번째 조건을 설정합니다.
our case statements so we're going to have the same setup when
8:09:24
결과 번호 두를 지정하고 키워드를 설정합니다.
condition two if this is true then show the
8:09:27
두 번째 조건을 설정하고 이 조건이 충족되면
result number two we specify the keyword when then we have
8:09:30
SQL에 다른 결과를 보여주도록 지시합니다.
a second condition and if this condition is true then
8:09:34
그 SQL의 구문이 어떻게 진행될지를 이해하는 것이 중요합니다.
we tell sql to show another results and of course it's
8:09:37
조건을 위에서 아래로 처리합니다.
very important to understand that the syntax of that sql is going to go
8:09:40
가장 중요한 조건은 맨 위에 있어야 합니다.
and process the conditions from the top to the bottom
8:09:43
SQL은 이 조건을 가장 먼저 확인합니다.
so the first most important condition should be at
8:09:46
조건이 실패하면 다음으로 넘어갑니다.
the start so sql gonna first check this condition
8:09:49
두 번째 조건으로 점프합니다.
if it fails and it's not true then it's gonna go
8:09:52
조건의 순서는 논리에서 매우 중요합니다.
and jump to the second condition so the order of the
8:09:55
여러 조건을 추가할 수 있습니다.
conditions is very important in your logic and now of course we
8:09:58
키워드를 사용하여 조건을 정의합니다.
can go and add multiple conditions depend on the logic using
8:10:02
ELSE 키워드를 지정할 수 있습니다.
the keyword when and now once we are done defining all the conditions
8:10:05
ELSE는 기본값을 도입할 수 있습니다.
we can go and specify an else keyword
8:10:08
선택 사항이며 생략할 수 있습니다.
the else can introduce the default value and it is
8:10:11
모든 조건이 실패할 때만 기본값이 사용됩니다.
optional you can go and skip it so the value of the else
8:10:14
모든 조건이 실패하면
or the default gonna be used only if all
8:10:18
조건이 충족되지 않으면 넘어갑니다.
the conditions fails so that means all our conditions are
8:10:21
ELSE에서 값을 사용합니다.
not true and nothing is fulfilled then it's going to go
8:10:24
모든 조건이 거짓일 때 사용될 기본값입니다.
and use the value from the else so it is the
8:10:27
이러한 키워드는 각 조건문 내에서 사용해야 합니다.
default value that's going to be used if all conditions are
8:10:30
모든 조건이 거짓일 때 사용될 키워드입니다.
false so those are the keywords that you must use inside each
8:10:33
각 케이스 문에서 사용해야 하는 키워드입니다.
case statement so we have case when then and end only the else is an optional so you can go and use it or skip it so this is the main structure and the syntax of each case statement
8:10:49
이제 SQL을 이해하기 위한 간단한 예제를 살펴보겠습니다.
now let's have a very simple example in order to understand how sql
8:10:53
백그라운드에서 케이스 문을 실행합니다.
execute the case statements behind the scenes all
8:10:56
하나의 조건만 있는 매우 간단한 예제를 살펴보겠습니다.
right let's have this very simple example where we have only one condition so
8:10:59
구문에서 케이스로 시작하고 끝나는 것을 볼 수 있으며, 여기서 판매를 평가하고 있습니다.
as you can see in the syntax it starts with case and end and then we have only one condition and we are evaluating here the sales so the condition says if the sales is higher than 50
8:11:11
매우 간단한 하나의 조건입니다.
then show as a result the value of high so it's very
8:11:14
논리가 어떻게 실행되는지 이해하기 위한 차트입니다.
simple only one condition and on the right side we have here a flow
8:11:17
이제 네 개의 판매를 평가해 보겠습니다.
chart in order to understand how the logic is executed and
8:11:20
이 논리를 통해 결과가 어떻게 나오는지 확인해 보겠습니다.
now what we're gonna do we're gonna go and evaluate those four sales through
8:11:24
하나씩 진행해 보겠습니다. 첫 번째 판매는 60입니다.
this logic and see what the auto gonna be with the case
8:11:27
60이 50보다 높은지 확인해 보겠습니다.
statement so let's do it one by one let's start with
8:11:30
이 조건을 충족하므로 true가 됩니다.
the first sales it is 60 so here we're gonna go and check is 60 higher than 50 well yes that means this sales is
8:11:38
출력에서 high 값을 얻을 것입니다.
meeting this condition and we will get true and
8:11:41
출력에서 high 값을 얻습니다.
we're going to get in the output the value of high so
8:11:44
첫 번째 판매가 요구 사항을 충족합니다.
here we're going to get the value high in the output so
8:11:48
이 조건이 충족되므로 값을 제공합니다.
that means the first sales is fulfilling the requirement the
8:11:51
이제 다음 값으로 넘어갑니다.
condition and it's going to give us the value from this
8:11:54
30을 평가해 보겠습니다. 30이 50보다 높은가요?
condition all right so now it's going to go to the next value and we're going to start
8:11:57
이 조건에 대한 출력은 false가 됩니다.
evaluating the 30 now we're going to ask the same question the same condition is 30 higher than 50 well no so that means in the
8:12:05
false 경로를 선택하겠습니다.
output for this condition we will get false so we
8:12:09
값을 얻지 못합니다.
will take the path of the false now if you took the path of the false
8:12:12
출력은 null이 됩니다.
we will not get any value right so that means the
8:12:15
출력은 null이 되며,
output is gonna be a null so the
8:12:18
30에 대한 출력은 null입니다.
output for the 30 is null and that's because we didn't
8:12:21
기본 옵션에 대한 논리를 정의하지 않았기 때문입니다.
define in our logic anything about the default option
8:12:25
그래서 여기 else가 없고, else를 사용하지 않으면 case 문에서 null을 얻게 됩니다. 이제 다음으로 넘어가겠습니다. 같은 내용이 될 것입니다.
so we don't have here an else and this is what's gonna happen if you don't use else you will get a null in the output for the case statement so now let's move to the next one it's going to be the same thing.
8:12:35
15는 50보다 작습니다. 그래서 조건을 충족하지 않습니다. 또한 null을 얻게 됩니다.
So 15 is smaller than 50. So it's not fulfilling the condition. And as well, we're going to get a null.
8:12:41
마지막 경우에 대해서는 null이기 때문에 조건을 충족하지 않아 null을 얻게 됩니다.
And for the last one, since it's null, we will get as well a null since it will not fulfill the condition.
8:12:47
이제 모든 판매를 평가한 결과, 첫 번째 판매만이 그 조건을 충족합니다.
So now after evaluating all those sales, only the first sales is fulfilling that condition.
8:12:52
그래서 우리는 단 하나의 값, 즉 최고값만을 갖게 됩니다. 자, 이제 계속 진행하고 case 문에 내용을 추가해 보겠습니다.
And that's why we have only one value, the high. All right. So now let's keep moving and adding stuff to our case statements.
8:12:58
이제 두 번째 조건을 추가하고 있습니다. 판매가 50보다 높은지 확인한 후, 20보다 높은지 다시 확인합니다.
Now we are adding a second condition. So it says after checking the sales, whether it's higher than 50 and it fails check again the sales whether it's higher than 20.
8:13:08
예라면 중간값을 보여줍니다. 이제
if yes then show the value of medium so now
8:13:11
우리의 작업 흐름에서 첫 번째 조건이 false일 경우 확인할 두 번째 조건을 추가하고 있습니다. 이제 다시 판매를 평가하고 첫 번째 출력인 60을 확인해 보겠습니다.
in our workflow we are adding a second condition to be checked if the first one is false so now let's go and evaluate our sales again and check the output the first one the 60.
8:13:21
보시다시피 60은 50보다 높습니다.
so as you can see the 60 is higher than 50
8:13:24
그래서 우리는 첫 번째 요구 사항을 충족하고 있습니다. 그래서
so we are fulfilling the first requirement that's why
8:13:27
우리는 높은 값을 얻게 될 것이고, 이전과 같습니다.
we will get the value of high so it's same like before
8:13:31
우리는 높은 값을 얻게 될 것이고, 여기서 출력에서 높은 값을 얻게 됩니다.
so here we're gonna get high in the output and
8:13:34
여기서 중요한 점은 SQL이
now here very important to understand one thing is that sql
8:13:37
이 시나리오에서 두 번째 조건을 평가하지 않았습니다.
didn't evaluate here in this scenario the second
8:13:40
그래서 SQL은 다른 조건을 확인하는 데 시간을 낭비하지 않았습니다.
condition so sql didn't waste any time by checking the other condition
8:13:43
한 조건에서 true를 얻으면 모든 것을 건너뜁니다.
it skipped everything once it gets a true from
8:13:46
이것이 SQL이 case를 처리하는 방식입니다.
one condition so this is exactly how sql process the case
8:13:50
각 조건을 위에서 아래로 확인할 때
when it's gonna check each conditions from top to
8:13:53
true를 찾으면 즉시 모든 것을 멈추고 이 조건의 값을 보여줍니다.
down and once it finds it true it's
8:13:56
다른 조건은 평가하지 않을 것입니다.
gonna stop everything immediately and show the value from this condition
8:13:59
이제 다음 값으로 넘어가고, 우리는
and it will not evaluate any other conditions so
8:14:02
30에 있습니다. 조건을 평가해 보겠습니다. 30은
now it's gonna go and jump to the next value we are at the value of
8:14:05
50보다 높은지, 아니면 그렇지 않은지 확인해 보겠습니다.
30 so let's evaluate the conditions is 30
8:14:09
30은 50보다 높지 않으므로 false입니다.
higher than 50 well it's not so it's false so
8:14:12
이제 발생할 수 있는 일은 다음 조건으로 넘어가서
now what can happen is gonna go and jump to the next condition and
8:14:15
두 번째 조건이 참인지 거짓인지 평가하기 시작합니다.
start evaluating the second one whether it's true or false so
8:14:18
이제 30이 20보다 큰지 확인해 보겠습니다.
now we're gonna check here is 30 higher than 20 well
8:14:21
네, 그러므로 충족될 것이고 우리는
yes so it's gonna be fulfilled and we will get the
8:14:24
중간값을 얻을 것입니다. 그래서 모든 것을 멈추게 됩니다.
value of medium so it's going to stop everything and
8:14:28
이 값에 대한 출력에서 중간값을 표시합니다.
show in the output for this value the medium
8:14:31
여기서 중간값을 얻을 것입니다. 그래서 이 시나리오에서는
so we're going to get medium here so in this scenario
8:14:34
우리가 가진 두 조건을 평가했습니다.
we have evaluated both of the conditions that we have
8:14:37
이제 케이스 문에서 세 번째로 넘어갑니다.
in the case statement now it's going to go to the third one we
8:14:40
15가 50보다 큰지 확인해 보겠습니다. 아니요.
have 15 is 15 higher than 50 well no
8:14:43
그러므로 첫 번째 조건에 대해 거짓이 될 것입니다.
so we will get to false for the first condition then gonna
8:14:47
두 번째 조건으로 넘어가서 15가
go and jump to the second condition and check it is 15
8:14:50
20보다 큰지 확인해 보겠습니다. 아니요. 이제 무슨 일이 일어날지 보겠습니다. 여기서 오류가 발생할 것이고 반환값이 없습니다.
higher than 20 well as well no so now what can going to happen the fault is going to be activated over here and we will not get any value as a return so we will get the value of null in the output.
8:15:02
그래서 출력에서 null 값을 얻게 될 것입니다.
And now for the last one, we have null. We will get as well null because it will not fulfill any of those conditions.
8:15:08
마지막으로 null이 있습니다. 어떤 조건도 충족되지 않기 때문에 null을 얻게 될 것입니다.
And that's because we didn't define an else in the case statement.
8:15:12
그리고 이는 케이스 문에서 else를 정의하지 않았기 때문입니다.
So if we define these conditions like this, we will get the category medium for the 30.
8:15:17
이러한 조건을 정의하면 30에 대한 중간 카테고리를 얻게 됩니다.
And this is how SQL evaluate multiple conditions in the case statements. All right, now we're going to go to the final form of our case statements.
8:15:25
SQL이 케이스 문에서 여러 조건을 평가하는 방법입니다.
And we're going to go and add an else so we can have a default value.
8:15:28
이제 최종 형태로 넘어가겠습니다.
So we are seeing here if the sales is not higher than 50 or higher than 20, then show a default value as low.
8:15:34
우리는 else를 추가하여 기본값을 가질 수 있습니다.
So that means any sales that is equal or smaller than 20 can get the value of low.
8:15:40
판매가 50보다 크지 않거나 20보다 크지 않으면 기본값으로 낮음을 표시합니다.
And now very interesting, if you check the workflow over here, you can see that we have now a value for each path.
8:15:47
따라서 20 이하의 판매는 낮음 값을 가질 수 있습니다.
So for the first condition, we're going to get high for the second one medium. And if nothing is fulfilled, we're going to get always the value of low.
8:15:54
여기서 워크플로를 확인하면 각 경로에 대한 값이 있습니다.
So there is no way in this chart to get any nulls, right? So let's go and evaluate again our values. I think you already get it.
8:16:01
첫 번째 조건에 대해 높음, 두 번째 조건에 대해 중간값을 얻습니다.
The 60 is fulfilling the first requirement and SQL gonna stop everything immediately and just show the value of high.
8:16:08
아무것도 충족되지 않으면 항상 낮음 값을 얻습니다.
So on the right side over here, nothing gonna be evaluated because the first condition is true.
8:16:13
이 차트에서 null을 얻을 방법이 없습니다.
So here in the outwards, we're gonna get the value of high. So nothing changed like the two previous examples.
8:16:19
이제 SQL은 다음 값을 가져올 것입니다. 우리는 30이 있으므로
Now SQL gonna go to the next value. we have the 30 so
8:16:22
첫 번째를 평가할 수 있습니다. 그것은 거짓이 될 것이고 다음
we can evaluate the first one it's going to be false the next
8:16:26
하나는 20보다 큽니다. 그것은 참이고
one it's higher than 20 it is true and
8:16:29
그래서 중간 값을 표시할 것입니다. 그리고
that's why it's going to show the value of medium and
8:16:32
이것은 이전 예제에서도 있었던 것입니다. 그래서
this is as well we had it in the previous example so
8:16:35
중간 값입니다. 이제 스케일은 다음으로 이동할 것입니다. 여기서
medium so now scale going to move to the next one and here things can
8:16:39
흥미로워질 수 있습니다. 그래서 15의 값을 평가할 수 있습니다.
get interesting so the value of 15 we can evaluate
8:16:42
첫 번째 조건은 50보다 큽니다. 글쎄요, 아니요. 20보다 큽니다. 글쎄요, 아니요. 그래서 이제 우리는
the first condition is it higher than 50 well no is it higher than 20 well no so now we are in scenario where none of those conditions
8:16:50
어떤 조건도 참이 아닙니다. 그래서 SQL은 가서 실행할 것입니다.
are true so that's why sql gonna go and execute
8:16:53
else입니다. 그래서 차트를 확인하면
the else so if you check our chart it's
8:16:56
거짓이 될 것이고 우리는 낮은 값을 얻게 될 것입니다.
gonna be false and we will get the value of low so
8:17:00
출력에서 이번에는 null을 얻지 않을 것입니다.
in the output we will not get this time a
8:17:03
우리는 else가 있으므로 낮은 값을 얻게 될 것입니다.
null because we have else we will get the value of low the
8:17:06
null에 대해서도 같은 일이 발생합니다. null은 첫 번째 조건을 충족하지 않을 것입니다.
same thing now for the null null will not fulfill the first condition as well the second condition and that's why we will get as well the value from
8:17:15
else입니다. 그래서 출력에서 우리는
the else so here in the output we will get as
8:17:19
낮은 값을 얻게 될 것입니다. 이제 보시다시피 else를 사용하면
well the value of low so now as you can see if you use an else
8:17:22
case 문 안에 있습니다. 출력에서 null이 없도록 할 것입니다.
inside the case statements you will make sure that there
8:17:25
좋습니다, 친구들. 이제 case 문에서 가장 유용한 사용 사례를 보여드릴 차례입니다.
will be no nulls in the output so that you have learned the different options that we have inside the case statements and how is quail execute the case behind the scenes
8:17:38
좋습니다, 친구들. 이제 case 문에서 가장 유용한 사용 사례를 보여드릴 차례입니다.
all right friends so now we come to the part where i'm going to show you the most useful use cases of the case statements that I usually use in my projects.
8:17:46
시작합시다. case 문의 주요 목적은 데이터 변환을 수행하는 것입니다.
So let's start. The main purpose of the case statement is to do data transformations.
8:17:51
데이터 변환은 각 데이터 프로젝트에서 매우 중요한 과정입니다.
And data transformations is a very important process in each data project.
8:17:56
데이터 변환에서 매우 중요한 작업 중 하나는 새로운 정보를 생성할 수 있다는 것입니다.
And one very important task in data transformations is that we can generate new information.
8:18:00
기존 데이터에 기반하여 새로운 열을 생성할 수 있습니다.
We can go and create in new columns based on the existing data that we have in the database using the case statements.
8:18:06
이것은 물론 분석을 위한 새로운 정보를 도출하는 데 도움이 될 수 있습니다.
And this, of course, can help us deriving new information for our analysis
8:18:11
소스 데이터베이스를 수정하지 않고 오직 분석을 위해서입니다.
without modifying the source database only for analytics.
8:18:15
그래서 친구들, 케이스 문장의 주요 목적은 새로운 열을 생성하고 생성하여 데이터 변환을 수행하는 것입니다.
So my friends, the main purpose of the case statement is to do data transformations by creating and generating new columns.
8:18:22
이제 첫 번째 사용 사례를 시작해 보겠습니다. 가장 중요하고 유명한 것은 데이터를 분류하기 위해 케이스 문장을 사용하는 것입니다.
So now let's start with the first use case and the most important and famous one is we use case statement in order to categorize the data.
8:18:30
이는 특정 조건에 따라 데이터를 서로 다른 범주로 그룹화할 것임을 의미합니다.
This means we are going to group up the data into different categories based on certain conditions.
8:18:35
이 사용 사례가 중요한 이유를 물어볼 수 있습니다. 데이터 분류와 그룹화는 데이터 분석에서 기본적입니다.
And now you might ask why this use case is important well classifying
8:18:39
데이터 분석과 보고에서 데이터가 더 쉽게 이해될 수 있도록 하기 때문입니다.
and grouping data is fundamental in data analysis
8:18:42
이해하기 쉽고 추적하기도 쉬워지지만, 더 중요한 것은
and reporting because it makes the data easier
8:18:45
데이터를 그들의 범주에 따라 집계하는 데 도움이 될 것입니다.
to understand and as well to track but what's more important it
8:18:49
좋습니다. 이제 다음 작업을 해보겠습니다. 생성기라고 합니다.
gonna help us aggregating the data based on their
8:18:52
다음 범주에 대한 총 판매량을 보여주는 보고서입니다. 판매가 50을 초과하면 높은 범주, 판매가 20과 50 사이면 중간 범주입니다.
categories all right so now let's have the following task and it says generator
8:18:56
판매가 20 이하이면 낮은 범주로 분류하고 정렬합니다.
reports showing total sales for each of the following categories category high if the sales is over 50 category medium if the sales is between 20 and 50
8:19:06
가장 높은 판매에서 가장 낮은 판매로 범주를 정렬합니다. 알겠죠?
and low if the sales is 20 or less and sort
8:19:09
단계별로 진행해 보겠습니다. 이제 데이터 집계를 수행하기 전에
the categories from the highest sales to the lowest okay so
8:19:13
범주라는 새 열을 만들어야 합니다. 왜냐하면
let's do it step by step and now before we do any data aggregations
8:19:16
데이터베이스에 없기 때문입니다. 이제 매우 간단한
we have to go and create a new column called categories because
8:19:19
선택 문으로 시작해 보겠습니다. 무엇이 필요할까요? 주문 ID와 판매를 가져오겠습니다.
we don't have it in the database so now let's start with very simple
8:19:22
그게 전부입니다.
select statements so select what do we need let's take the
8:19:25
주문 ID 판매 및 그게 전부입니다.
order id the sales and that's it for
8:19:28
이제 판매 주문에서 실행해 보겠습니다. 이제 10개의 주문이 있으며, 새로운 열인 카테고리를 만들어야 합니다. 이를 케이스 문을 사용하여 수행할 것입니다.
now so from sales orders let's go and execute it and now we have our 10 orders and we have to go and now create a new column called categories and we're going to do that using the case statements.
8:19:41
새로운 줄을 시작하고 케이스로 시작한 다음, 첫 번째 조건을 정의하기 위해 다시 새로운 줄을 추가합니다.
So let's take a new line and we start with case and then again a new line in order to define the first condition using the when.
8:19:49
첫 번째 조건은 판매가 50을 초과하는 경우입니다. 매우 간단합니다.
So the first condition is the high where sales is over 50. So it's very simple.
8:19:53
판매가 50보다 높을 때, 이것이 참이라면 무엇이 발생할 수 있습니까?
So when the sales is higher than 50, what can happen if this is true?
8:20:00
우리는 값을 높게 표시하고 싶습니다. 그래서 이것은
we want to show the value high so this is
8:20:03
첫 번째 조건이고, 두 번째 조건으로 넘어갑니다.
the first condition and then let's move to the second one if
8:20:07
판매가 20보다 높으면
the sales is higher than 20 that
8:20:10
이는 50보다 적고 20보다 높은 것을 의미합니다.
means it's less than 50 and higher than 20 then
8:20:14
우리는 값이 중간인 것을 보고 싶고 이제
we want to see the value medium and now for
8:20:17
마지막 카테고리인 낮은 값에 대해 조건을 만들 필요가 없습니다. 왜냐하면 두 조건이 실패하면 판매가 20 이하이기 때문입니다.
the last category the low we don't have to go and create a condition for that because if those two fails then that means the sales either equal to 20 or less so
8:20:26
우리는 간단한 else를 사용하여
we're gonna do we're gonna just do a simple else and show
8:20:29
낮은 값을 이렇게 표시할 것입니다. 이걸 조금 더
the value low like this let me make this a
8:20:32
작게 만들어야 합니다. 이제 우리 경우에 빠진 것은
little bit smaller now what is missing in our case is of
8:20:35
끝입니다. 그것이 없으면 오류가 발생합니다.
course the end without it you're gonna get an error so end
8:20:39
그리고 이름을 카테고리라고 지어줍시다.
and let's give it the name category so we
8:20:42
준비가 되었습니다. 이제 실행해 보겠습니다.
are ready let's go and execute it so now let's check randomly
8:20:45
여기에서 판매량이 50인 것을 볼 수 있습니다.
stuff so as you can see here we have the sales of 50 it
8:20:48
낮은 값이 맞고, 여기 60이 있습니다.
is low which is correct and then we have here 60 it's
8:20:51
50 이상이며 카테고리는 높습니다. 이제 주문 번호 6을 확인하면 주문 50은 중간입니다.
above 50 and we have the category high and now if you check the order number six we have the order 50 it's medium because it is not higher than 50 it is between 50 and 20.
8:21:02
이제 우리는 주문을 분류했습니다.
so now as you can see we have now classified our orders using
8:21:05
다음 단계는 데이터를 집계하는 것입니다.
the category now the next step is that we're going to go and aggregate the
8:21:08
그것을 어떻게 할 것인지 서브 쿼리를 사용할 것입니다.
data so how we're going to do that we will use a
8:21:11
이렇게 하여 선택할 것입니다.
sub query so let's do it like this we're going to go and select
8:21:14
그리고 물론 카테고리별로 데이터를 그룹화할 것입니다.
and of course we're going to group up the data by the category so we're going to go
8:21:17
그 카테고리를 선택하고 총합이 필요합니다.
and select that category and we need the total
8:21:21
판매량을 의미하며 sum 함수를 사용할 것입니다.
sales that means we're gonna go and use the function sum for
8:21:24
이제 쿼리를 함께 중첩해야 합니다.
the sales and we're gonna call it total sales
8:21:27
이것이 우리의 쿼리입니다.
so now we have to nest the queries together so from
8:21:31
그리고 닫아야 합니다.
this is our query like this
8:21:34
그룹화하므로 우리는
and then we have to close it and
8:21:37
카테고리별로 판매를 집계하고 있습니다.
group by so we are grouping by the
8:21:40
이제 결과에는 세 개의 카테고리만 있습니다.
category okay so with that we are now aggregating the sales by that category it's very simple let's go and execute it
8:21:48
이제 데이터 집계를 하고 있습니다.
so now in the result we have only three categories we don't have the 10 orders
8:21:51
이제 결과에는 10개의 주문이 없고 3개의 카테고리만 있습니다.
because now we are doing data aggregations so now the
8:21:54
현재 우리는 데이터 집계를 하고 있으므로
granularity now on the level of category so now
8:21:57
카테고리 수준에서의 세분화가 이루어집니다.
we can see the total sales for the high is 2010 the
8:22:01
높은 판매량은 2010이고
low we have 65 and the medium we have 105 and
8:22:04
물론 우리는 아직 끝나지 않았습니다. 작업에서 정렬하라고 하였으므로
of course we are not done yet because in the task it says sort
8:22:07
카테고리를 가장 높은 판매량에서 가장 낮은 판매량으로 정렬해야 합니다. 이는 최종적으로 정렬문을 사용해야 함을 의미합니다.
the categories from the highest sales to the lowest that means we have to go and use an order by statement at the end and we're going to sort So the data by the sales from the highest to the lowest, that means descending.
8:22:18
그래서 이제 실행해 보겠습니다. 이제 우리는 보고서를 가지고 있습니다.
So that's it. Let's go and execute it. And now with that, we have our reports.
8:22:23
이제 카테고리별 총 판매량을 보여주고 있으며, 데이터는 가장 높은 것부터 가장 낮은 것까지 정렬되어 있습니다.
Now we are showing the total sales by the categories and the data is sorted from the highest to the lowest.
8:22:28
가장 높은 카테고리는 높음, 그 다음은 중간, 마지막은 낮음입니다.
So the highest category is high, then medium, and then the last one is low.
8:22:32
친구들, 보시다시피, 사례의 도움으로 데이터에서 새로운 정보를 생성했습니다.
So my friends, as you can see, with the help of the case, when we have created new informations from our data, we have the category, and then we have created insights or report
8:22:41
이 새로운 정보를 기반으로 데이터를 집계했습니다.
based on this new information where we have aggregated our data using this new information.
8:22:47
데이터를 분류하는 사용 사례는 각 데이터 프로젝트에서 기본적이고 매우 중요합니다.
So the use case of categorizing data using case statements is fundamental and very important in each data project.
8:22:53
좋아요,
Okay,
8:22:57
다음 사용 사례로 넘어가기 전에 따라야 할 규칙이 하나 있습니다. 그것은 케이스 문을 사용할 때 결과의 데이터 유형이 일치해야 한다는 것입니다.
so now one more thing before we jump to the next use case is that there is one rule to follow if you are using case statements and that is the data types of the results must be matching.
8:23:07
이것이 의미하는 바는, 여기 우리의 예제를 다시 확인해 보면 각 조건의 결과가 문자열이라는 것을 알 수 있습니다.
So what this means, if we check again our example over here, we can see that the result of each condition is a string.
8:23:13
보시다시피, 여기에는 높음, 중간 및 낮음이 있습니다. 그리고 이 모든 정보는 동일한 데이터 유형을 따릅니다. 그래서 이것은 올바릅니다.
So as you can see, we have here high, medium and low. And all of those informations are following the same data type. So it is correct.
8:23:20
이제 이 규칙을 깨뜨리면, 예를 들어, 그 이후에 값 2를 가지면.
So now if I go and break this rule, for example, after this, then let's have the value two.
8:23:26
이제 우리는 숫자와 문자가 있습니다. 그래서 실행해 보겠습니다.
So now we have a number and we have characters. So let's go and execute it.
8:23:30
물론 이제 오류가 발생할 것입니다. 왜냐하면 SQL이 값을 정수로 변환하려고 시도하고 있기 때문입니다. 이는 올바르지 않습니다.
And now of course, we're going to get an error because now SQL is trying to convert the value law to an integer, which is incorrect.
8:23:37
그래서 결과의 출력 데이터 유형은
So the data types of the output of the result must
8:23:40
일치해야 하며, 이는 값만 포함하는 것이 아닙니다.
be matching and that's not only include the value
8:23:43
then 이후의 값뿐만 아니라 else 이후의 값도 포함됩니다.
after the then but also the value after the else
8:23:46
이 값도 출력의 일부이기 때문입니다.
because this value is as well part of the output so
8:23:49
다시 중간을 가져오고 이제 가서
let's have here again medium and now let's go and
8:23:52
이 값을 1로 바꿔보겠습니다. 그러니 가서
change this to let's say one so let's go and
8:23:56
다시 말하지만 SQL은 오류를 발생시킬 것입니다. 왜냐하면 이것은 정수이고 나머지는 문자열이기 때문입니다. 그래서 이것이 CASE 문을 사용하는 규칙입니다.
excuse it again sql gonna throw an error because this is an integer a number and the others are string characters so this is the rule of using the case statement the data types after then and after else
8:24:07
그래서 제한이 없고 우리는 이 하나의 규칙만 가지고 있습니다.
must be matching. And if you ask me whether there is restriction about where you can use the case statement in which clauses, you can use it everywhere in select, in joins, from, where, group by, order by, everywhere.
8:24:19
좋아요 친구들, CASE 문에 대한 또 다른 사용 사례는 값을 매핑하는 것입니다.
So there are no restrictions and we have only this one rule.
8:24:27
따라서 우리는 CASE 문을 사용하여 데이터를 한 형태에서 다른 형태로 변환하여 더 읽기 쉽고 분석에 더 유용하게 만들 수 있습니다.
Okay friends, another use case for the case statements, we can use it in order to map values.
8:24:32
값을 매핑하는 한 가지 시나리오는 데이터베이스 개발자가 데이터를 코드와 플래그로 저장하는 경우입니다.
So we can use the case statement in order to transform the data from one form to another in in order to make it more readable and more usable for analytics.
8:24:40
예를 들어, 주문의 상태는 비활성 및 활성 대신 1과 0으로 저장될 수 있습니다.
One scenario of mapping values is that sometimes the database developers stores the data and values inside the database as codes and as flags.
8:24:48
그리고 이것은 애플리케이션의 데이터베이스 성능을 최적화하기 위한 한 가지 기술입니다.
So for example, the status of the order could be stored as one and zero instead of having inactive and active.
8:24:55
왜냐하면 1과 0은 전체 문자열을 저장하는 것보다 훨씬 빠르기 때문입니다.
And this is one technique in order to optimize the
8:24:58
데이터 분석에서는 일반적으로 사람이 읽을 수 있는 보고서를 생성합니다.
performance of the database for the application because one and zero is
8:25:01
사람이 읽을 수 있도록 데이터 분석에서 보고서를 생성합니다.
way faster than storing the whole string but in
8:25:04
이제 데이터가 0과 1로 표시되는 대신
data analysis we usually generate reports to be read by
8:25:07
데이터를 활성 및 비활성으로 표시하면 더 보기 좋고 읽기 쉬워질 것입니다.
human by persons and now instead of showing the
8:25:11
따라서 이러한 시나리오에서는 CASE 문을 사용하여 암호화된 기술적 값을 읽기 쉬운 용어로 변환합니다.
data as zero and one it's gonna be more nicer and readable
8:25:14
그렇지 않으면 각 사람이 보고서를 소비할 수 있으며, 0과 1이 무엇을 의미하는지 물어볼 것입니다. 다음 작업을 해봅시다.
if you show the data as active and inactive so for these scenarios we're gonna go and use the case statement in order to translate those cryptical and technical values into readable terms.
8:25:24
그리고 직원 세부 정보를 성별로 전체 텍스트로 표시하라고 합니다. 좋아요, 이제 해결해 봅시다.
Otherwise, each one can consume your report, going to ask you, what do you mean with the zero and one? Let's have the following task.
8:25:30
먼저 몇 가지 정보를 탐색해 보겠습니다. 그러니 직원 ID를 표시해 봅시다.
And it says retrieve employee details with gender displayed as full text. Okay, so now let's go and solve it.
8:25:37
그리고 이름, 성을 가져오고 성별 정보를 필요로 합니다.
First, we're going to go and explore few informations. So let's go and show the employee ID.
8:25:44
판매 직원의 성별을 가져옵니다.
And let's take the first name, last name. And we need the gender informations.
8:25:49
그래서 그게 다입니다. 이제 넘어갑시다.
so gender from sales employees
8:25:52
그래서 이제 결과에서 다섯 명의 직원을 얻었습니다.
so that's it let's go and excuse
8:25:55
이제 성별 정보는 단지 하나로 저장됩니다.
it so now as you can see in the results we got our five employees and
8:25:59
문자 f와 m으로 저장되며, 물론 이해하기 쉽습니다.
now the gender informations are stored as only one
8:26:02
f는 여성이고 m은 남성입니다. 하지만 우리는
character f and m and of course it's easy to understand that
8:26:05
f는 여성이고 m은 남성이지만 우리는
the f is female and m is male but we
8:26:08
보고서에 전체 텍스트로 여성과 남성으로 표시하고 싶습니다. 따라서 이러한 약어 대신 그렇게 하려면 키 문장을 사용하여 매핑을 수행할 것입니다.
would like to show it in the report as a full text so female and male instead of those abbreviations so in order to do that we're going to go and use the key statement in order to do the mapping
8:26:19
구형 값과 신형 값 사이에
between the old value and the new value so let's
8:26:22
사례를 사용하여 새 열을 만들고
go and create a new column using the case so we're gonna have here
8:26:25
두 가지 조건이 있습니다. 첫 번째부터 시작합시다.
two conditions because we have two values let's start with the first
8:26:28
하나이므로 새로운 줄을 만들고
one so we're gonna have a new line and when so when
8:26:31
성별이 f일 때 여성 먼저
the gender equals to f ladies first
8:26:35
그럼 여성이고 두 번째 값은 성별이 m일 때 남성이 됩니다.
then female and now for the second value it's gonna be exactly the same when gender equal to m then we're gonna have male
8:26:46
값의 대소문자 구분에 주의하세요.
be careful for the case sensitivity of the values so of course
8:26:49
우리는 else 없이 끝내지 않을 것입니다.
we will not end this without an else or else then
8:26:53
기본값을 가질 수 있습니다.
we can have the default value we're gonna have the default value not available
8:26:56
우리가 놓친 것은 끝입니다.
it's better than having nulls so what
8:26:59
여기서 끝을 내고 성별을 완전하게 부르겠습니다.
we are missing is the end so we're gonna have
8:27:02
텍스트이므로 이제 실행해 보겠습니다.
an end over here and we're gonna call you gender full
8:27:06
물론 여기에는 null이 없습니다.
text so that's it let's go and execute it now if you check the results we have now done the mapping between the old format of the value with the new format so So instead of M, we have males and females.
8:27:18
물론 큰 데이터가 있다면 null이 있을 수 있습니다.
And of course, we don't have here any nulls. That's why we don't have a nut available in the data.
8:27:22
그래서 값 간의 매핑을 쉽게 할 수 있습니다.
But if you have huge data, of course, you can have somewhere a null. And then you will get this default value.
8:27:28
작업은 약어 국가 코드로 직원 세부정보를 검색하라는 것입니다.
So this is how you can do mapping between values very easily using the case statements. Okay, let's have another task for the mapping use case.
8:27:35
작업에서는 약어 국가 코드로 직원 세부 정보를 검색하라고 합니다.
And the task says retrieve employee details with abbreviated country code.
8:27:40
전체 이름을 사용할 공간이 충분하지 않습니다.
Sometimes as we are generating reports, maybe using Power BI or Tableau,
8:27:44
값의 약어가 필요합니다.
we don't have enough spaces in order to use the full name
8:27:47
값의 약어가 필요합니다.
of values so what do we need we need abbreviations
8:27:50
SQL에서 사례 문을 사용하여
we need short form of the values and we can go and
8:27:54
고객 ID와 이름, 그리고 국가가 필요합니다.
use in sql the case statement in order to map the full value to an abbreviated value so it's like the previous example but the way around all right so now let's go and solve it we're gonna go and select a few details
8:28:06
판매 고객의 정보를 가져옵니다.
like the customer id let's take the first name last name and what do we need we need the country
8:28:11
그게 다입니다. 실행해 보겠습니다.
information from sales customers so
8:28:15
그게 다야, 가서 실행하자.
that's it let's go and execute it and
8:28:18
보시다시피 우리는 다섯 명의 고객을 얻었고 국가 정보가 있습니다.
as you can see we get our five customers and we have the country informations as
8:28:22
이제 전체 이름이 필요하고 보고서에는 약어 값이 필요합니다.
a full name now of course for the report we need abbreviated values
8:28:25
여기서 우리는 전체 이름을 매핑할 것입니다.
from this so we're gonna go and map those full names
8:28:28
국가를 짧은 형태로 변환하지만 실제 프로젝트에서는 수천 개 또는 수백만 개의 레코드가 있는 큰 테이블을 얻을 수 있습니다.
of the countries to a short form but in real projects you might get big tables where you have thousands and millions of records so you cannot just check it like this so how i usually do it i go and retrieve
8:28:39
그래서 저는 일반적으로 이를 위해 서브쿼리를 사용합니다.
a distinct list of all values from one column so i usually go and have a subred query for that so
8:28:45
우리는 고유한 국가를 선택할 것입니다.
we're gonna have select distinct country from
8:28:49
판매 고객 테이블에서 그것을 볼 수 있습니다.
the table sales customers it's just for me to see
8:28:52
데이터베이스 내의 모든 가능한 값을 볼 수 있습니다.
all the possible values inside the database so now you see the second
8:28:55
여기서 우리는 독일과 미국의 두 가지 값만 있습니다.
result over here we have only two values germany and usa and
8:28:59
그런 다음 데이터를 올바르게 매핑할 수 있습니다.
then i can go and map the data correctly so always if you are
8:29:02
국가가 첫 번째 값인 경우 독일이 될 것입니다.
mapping data using the case win you have to understand all the possible values that you have inside the table so let's go and generate this new information let's start with case and then you line when
8:29:14
데이터베이스와 정확히 같은 방식으로 작성해야 합니다.
country equal to the first value it's going to be germany
8:29:17
첫 번째 문자는 대문자이고 나머지는 소문자입니다.
make sure you write it exactly like in the database the
8:29:20
무슨 일이 일어났는지, 우리는 독일의 약어를 갖게 될 것입니다.
first character is capital and the rest is small so
8:29:24
그것은 de가 될 것입니다.
what happened we're going to have the abbreviation of germany
8:29:27
그리고 이제 두 번째 값으로 이동합시다.
it's going to be de all right so this is for the first value and then let's move to the second one it's going to be country equal to usa it's already abbreviated but maybe we can get only two characters.
8:29:40
그래서 us처럼 이렇게 됩니다.
So us like this. And now let's go and add an else.
8:29:43
선택 사항이지만 데이터에 null이 있거나 새 값을 받을 경우 사용할 수 없습니다.
It's optional, but in case that we have nulls in the data or we get a new value, so else it's not available.
8:29:50
그래서 그게 다입니다. 끝을 잊지 마세요.
So in a so that's it. And never forget about the end. So and and the name going to be country abbreviation.
8:29:59
그래서 매핑이 올바릅니다.
So that's it. Let me just get rid of the other query
8:30:02
이제 결과를 확인하면 새로운 열이 생겼습니다.
so the mapping is correct let's go and execute it
8:30:05
국가 약어라는 새로운 열이 생겼습니다.
and now if you check the results we got a new column called country
8:30:08
우리는 독일과 de를 가지고 있고 미국은 us입니다.
abbreviation and as you can see now the mapping is working here
8:30:12
좋습니다, 친구들, 이제 값 매핑을 위한 case 문법의 특별한 경우가 있습니다.
we have germany and we have here de and for the usa we have us so with that we have have solved the task and we've done the mapping correctly between the old value and the new value.
8:30:25
그래서 이제 확인해 보겠습니다.
All right, friends, now there is a special case for the syntax of the case statements if you are using it for mapping values.
8:30:31
이제 확인해 보겠습니다. 이제 국가 안에 서로 다른 값들이 많이 있다고 가정해 보겠습니다.
So now let's go and check it. So now let's say that we have a lot of different distinct values inside the country, not only two values, we have a lot of values.
8:30:38
값을 매핑할 때 항상 같은 것을 작성하게 됩니다.
And if you are mapping the values using the case, when you're going to end up always
8:30:42
독일 국가와 같다고 작성하게 됩니다.
writing the same thing country equal germany country
8:30:45
인도 국가, 미국 국가 등으로 계속됩니다.
equal india country equal united states and so on
8:30:48
항상 국가 열을 사용하고 있으므로 조건이 있습니다.
so we are always using the column country so the conditions
8:30:51
여기서는 항상 하나의 열을 사용하고 있습니다.
over here using always one column and it's
8:30:55
항상 연산자는 같으므로 이 시나리오에 대해서만입니다.
always the operator is equal so now only for this scenario
8:30:58
케이스 문에 대한 다른 구문이 있습니다.
we have another syntax for the case statements and
8:31:01
이렇게 보입니다. 키워드 케이스로 시작합니다.
it looks like this we start with the keyword case but
8:31:04
그 다음 즉시 우리가 평가할 열을 사용합니다.
after that immediately we're going to use the column that
8:31:07
여기서는 하나의 열만 사용할 수 있습니다.
we want to evaluate and here you can use only one column
8:31:10
여기서는 하나의 열만 사용할 수 있습니다.
you cannot use multiple columns so now we are telling sql
8:31:13
이제 우리는 하나의 열, 즉 국가를 평가하고 있습니다.
we are now evaluating one column the country and
8:31:17
각 조건에 대해 다음과 같은 내용을 말합니다.
then for each condition we have the following stuff we say when
8:31:20
독일, 즉 국가가 독일과 같을 때를 의미합니다.
germany that means when country is equal to germany
8:31:24
여기서는 전체 조건이 없습니다.
then de so as you can see here we don't have here the whole condition
8:31:27
가능한 값만 있습니다.
we have only a possible value that you
8:31:30
국가 안에서 볼 수 있는 값입니다.
can see inside the country so we are saying is the value
8:31:33
그렇다면 다음을 보여줍니다.
country if it's true then show the e the next
8:31:37
하나는 인도, 다른 하나는 미국입니다.
one is it india then en united states us and
8:31:40
따라서 이 구문을 케이스의 빠른 형식이라고 부릅니다.
so on so we call this syntax a quick form of the case
8:31:43
왼쪽에서는 전체 형식이라고 부릅니다.
statement and on the left side we call it full form
8:31:46
빠른 형식을 사용할 때의 제한 사항입니다.
of the case statements and of course the restriction and limitation
8:31:49
하나의 열만 사용할 수 있습니다.
using the quick format is that you can use only
8:31:52
그리고 이는 오직 같음 연산자에 대해서만입니다.
one column and it's only for the equal operator
8:31:56
따라서 이는 이러한 시나리오에 대해서만 사용할 수 있다는 의미입니다.
so that means only for these scenarios you can go and use the
8:31:59
조금 복잡해지면 빠른 형식을 사용할 수 있습니다.
quick format if things get a little bit complicated where
8:32:02
복잡한 논리를 혼합해야 할 때는 빠른 형식을 사용할 수 없습니다.
you have to mix and make complex logic you cannot use the
8:32:05
복잡해지지 않을 것이라고 확신한다면 빠른 형식을 사용할 수 있습니다.
quick format so i would say if you are sure that the logic will not
8:32:08
복잡해지지 않을 것이라고 확신한다면 같은 열로 계속 유지할 수 있습니다.
get complicated and you can stay always with the same column you
8:32:11
빠른 형식을 사용할 수 있지만 항상 전체 형식을 사용하는 것이 좋습니다.
can go with a quick format but i would recommend always to go with
8:32:14
전체 형식을 사용하는 이유는 간단합니다. 작은 논리를 추가하면
the full format because for one simple reason if you add
8:32:17
전체 형식으로 다시 작성해야 합니다.
one small logic you have to go and rewrite the whole
8:32:21
작은 논리를 추가하려면 전체 형식으로 다시 작성해야 합니다.
case statements back to the full format in order to
8:32:24
작은 논리를 추가하는 데 있어 빠른 형식을 사용하는 것은 문제가 없습니다.
add any small logic but of course there is nothing wrong using the
8:32:27
빠른 형식을 사용하여 사례 문을 작성할 수 있습니다.
quick form in order to do the case statements if
8:32:30
논리가 정적일 수 있고 우리는 단지 하나의 열만 사용하고 있습니다.
the logic can stay static and you are sure we are using only
8:32:33
우리는 단지 매핑을 하고 있으며 추가 논리는 없습니다.
one column and we are just doing mapping there is no any extra
8:32:36
이전 예제를 위해 이 빠른 형식을 시도해 보겠습니다.
logic okay so now let's try this quick format for the case statements
8:32:39
모든 것을 새 열로 복사하겠습니다.
for the previous example so i will just go and copy everything
8:32:42
새 열로 이름을 바꾸겠습니다.
to a new column so i'm just going to rename it
8:32:45
두 개로 이름을 바꾸고 이제 어떻게 할지 보겠습니다.
to two and now how we're going to do it so it's
8:32:49
사례가 될 것이며 이번에는 국가를 작성할 것입니다.
going to be case but this time we're going to write a country
8:32:52
그리고 그 안에 값만 있을 것입니다.
and then inside the win we will have
8:32:55
조건이 필요 없으므로 이렇게 될 것입니다.
only the values so no need for the condition so
8:32:58
이렇게 될 것이며, 스크롤을 올려보겠습니다.
it's going to be like this let me scroll up so that's
8:33:01
작고 빠르며 매번 전체 조건을 작성하는 것보다 낫습니다.
it as you can see it's smaller and quicker than writing
8:33:04
이제 실행해 보겠습니다. 결과에서 동일한 값을 얻을 것입니다.
the whole condition each time so now let's go and execute this and as you can see in the result we're gonna get identical values so now you know one more trick in the case statement
8:33:18
다음 사용 사례로 넘어가겠습니다.
all right moving on to the next use case for the case statements we can use
8:33:21
널을 처리하기 위해 사용할 수 있습니다.
it in order to handle nulls handling nulls means replace
8:33:24
널을 처리하기 위해 널을 값으로 대체하는 것을 의미하며, 윈도우 집계 함수와 함께 배운 바와 같이, 때때로 널은 잘못된 계산과 결과를 초래하여 잘못된 의사결정으로 이어집니다.
a null with a value and as we learned before with the window aggregate functions, sometimes nulls leads to incorrect calculations and results, which leads to wrong decision making.
8:33:34
SQL에서 널을 처리하는 방법에 대한 전용 장이 나중에 있을 것입니다. 그러나 지금은 케이스 문을 사용하여 널을 처리하는 방법을 배워보겠습니다.
We're going to have later a dedicated chapter on how to handle nulls in SQL. But now we're going to learn how to handle nulls using case statements.
8:33:41
이제 다음 작업을 살펴보겠습니다. 고객의 평균 점수를 찾고 널을 0으로 처리하며, 고객 ID와 성과 같은 세부정보도 제공하라고 합니다.
So now let's have the following task and it says find the average scores of customers and treat nulls as zero and additionally provide details such as customer ID and the last name.
8:33:51
이제 단계별로 해결해 보겠습니다. 여기 세부정보가 있으며, 집계를 수행해야 합니다.
Okay, so now let's solve it step by step. And again, we have here details and as well, we have to do aggregations.
8:33:57
즉, 윈도우 함수를 사용해야 하며, 널을 처리해야 한다는 것을 잊지 말아야 합니다.
means we have to go and use the window functions and we don't have
8:34:00
널을 처리해야 한다는 것을 잊지 말아야 합니다.
to forget that we have to treat the null so we have to handle it so
8:34:03
이제 매우 간단한 선택을 시작해 보겠습니다. 고객을 선택합니다.
now let's go and start with very simple uh select so select customer
8:34:07
ID와 성이 필요합니다.
id we need the last
8:34:11
그리고 점수도 필요합니다.
name and as well we need the scores so
8:34:14
판매 고객에서 선택하겠습니다.
from sales customers let's
8:34:17
이제 실행해 보겠습니다. 평소처럼 다섯 명의 고객이 있습니다.
go and execute it so as usual we have our five customers and
8:34:21
점수와 여기 널이 있습니다. 이제 널을 처리하지 않고 윈도우 함수를 작성할 것입니다.
the scores and here we have a null now we're gonna go and write the window
8:34:24
널을 처리하지 않고 작성할 것입니다. 차이를 보기 위해서입니다.
function but without handling the nulls just in order to see the
8:34:27
점수에 대한 평균 함수를 필요로 합니다.
differences so we need the average function for
8:34:30
데이터를 어떻게 분할해야 할까요? 아니요, 비워두겠습니다.
what for the scores do we have to now partition
8:34:33
모든 고객의 평균 점수가 필요합니다.
the data well no so we're gonna leave it as empty we
8:34:36
이제 이름을 지정하고 실행해 보겠습니다.
need the average score of all customers so that's
8:34:39
여기 실수가 있는 것 같습니다. 점수이지 점수가 아닙니다.
it let's go and give it a name and then execute
8:34:43
이제 평균이 625임을 알 수 있습니다.
it i think i have here mistakes so it is a score not scores
8:34:46
그래서 이제 보시다시피 우리는 625의 평균을 가지고 있습니다.
so and now as you can see we have the average of 625
8:34:49
그리고 우리가 이전에 배운 것처럼 SQL은 이 네 가지 값을 요약하고 네로 나누지만, 우리 비즈니스는 널을 누락된 정보가 아니라 0으로 이해합니다.
and as we learned before sql gonna go and summarize all those four values and divide it by four but our business understand and the nulls as zero, not as missing information.
8:34:59
그래서 우리는 널을 처리해야 합니다.
So we have to go and handle the null let's
8:35:02
점수를 위한 새로운 열을 만들어 보겠습니다.
go and create a new column for the scores but
8:35:05
이번에는 케이스 문을 사용할 것입니다.
this time we're going to go and use the case statements it can
8:35:08
매우 간단할 수 있으므로 우리는 다음과 같이 말할 것입니다.
be very simple so we're going to say when the
8:35:12
점수가 null일 때 SQL에서는 null과 같다고 쓰지 않고 is null이라고 말합니다. 그래서 null을
score is null so in sql we don't write equal null we say is null so with that we are replacing the nulls with
8:35:20
제로로 바꾸고 이제 그렇지 않으면
zero right so now otherwise what can happen
8:35:23
null이 아닐 때 점수를 그대로 가져와야 합니다.
so if it's not null so we need the score as it is
8:35:26
아무것도 조작하지 않아야 하므로 기본값은
we should not manipulate anything so the default
8:35:30
점수 자체입니다. 점수가 null이 아닐 때
value is the score itself if the score is not null so
8:35:33
이제 끝내고 점수라고 부릅시다.
now let's go and end it and let's call it score
8:35:37
깨끗하게 실행합시다.
clean so let's go and execute
8:35:40
이제 결과를 확인하면 거의 동일합니다.
it now if you check the result over here it's like almost identical
8:35:43
점수에서 새로운 값이 없으므로
at the score so we don't have a new values for the
8:35:47
현재 null만 제로로 바뀌고 모든
scores but only the nulls now are zero and all
8:35:50
다른 값은 영향을 받지 않으므로 건드리지 않았습니다.
other values they are not affected so we didn't touch it
8:35:53
우리는 그것을 전혀 변형하지 않았습니다. 그래서 이것이 우리가 처리하는 의미입니다.
we didn't transform it at all so this is what do we mean with handling
8:35:56
null을 다른 값으로 대체하는 것입니다. 이제 작업을 마치기 위해
nulls replacing nulls with another value so now in order
8:35:59
점수의 평균을 구해야 합니다.
to finish the task we have to do the average for the score
8:36:02
원래 점수가 아닌 깨끗한 점수로 어떻게 할 것인지
clean and not for the original score so how we're gonna do it let's
8:36:05
전체 case 문을 복사하러 가고 있습니다.
go and copy the whole case statements i'm just gonna do it
8:36:08
다른 열에서 평균을 구합시다.
in another column so let's have an average and
8:36:12
그 안에 case 문이 이렇게 있습니다.
inside it we have the case statements like this let
8:36:15
이렇게 정렬하고 이제 무엇이
me just sort it like this and now what
8:36:18
부족한지는 over이고 비어 있을 것입니다. 평균 고객이라고 부릅시다.
is missing is the over and it's going to be empty so average customer let's call it clean so this is the logic
8:36:27
이제 모든 것을 더 작게 만들어 보겠습니다.
let me just make everything smaller so
8:36:30
이제 보시다시피 이전과 정확히 같습니다. 하지만 원래 점수를 사용하는 대신
now as you can see it's exactly like the previous one but instead of using the original score now we are using the column that we have created but of course
8:36:38
우리는 여기서 별칭이 필요하지 않으므로 제거해야 합니다.
we don't need the alias over here so we have to remove it so
8:36:42
case로 시작하고 끝납니다. 이제 실행합시다.
it starts with case and end so let's go and execute
8:36:45
이제 출력에서 새로운 값을 얻었습니다.
it and now you can see in the output we got a new value
8:36:48
평균에 대한 것이며 더 정확합니다.
for the average and it is more accurate for the
8:36:51
비즈니스에서 이제 우리는 500을 가지고 있습니다. 이전에는 625가 있었습니다.
business so now we have 500 previously we had 625
8:36:55
보시다시피, 비즈니스에서 null이 의미하는 바를 이해하고 올바르게 처리해야 합니다. 그렇지 않으면 잘못된 결과를 얻을 것입니다. 그래서 우리는 데이터 내의 null을 처리하기 위해 case 문을 사용합니다.
so as you can see you have to understand what the nulls means in your business and handle it correctly otherwise you will get wrong results so that's it we use case statements in order to handle the nulls inside our data.
8:37:06
조건부
Conditional
8:37:11
집계는 SQL에서 평균, 개수와 같은 집계 함수를 특정 조건을 충족하는 데이터의 하위 집합에만 적용할 수 있음을 의미합니다.
aggregations means we can go and apply an aggregate function in SQL like some average count but this time only on a subset of data that meet specific conditions.
8:37:22
이 기술은 특정 데이터 하위 집합에 대한 심층 분석이나 목표 분석을 수행하는 데 놀랍습니다.
This technique is amazing in order to do deep dive analysis or target analysis on a specific subset of the data.
8:37:28
이제 이 사용 사례를 이해하기 위해 다음 SQL 작업을 수행해 보겠습니다.
So now let's have the following SQL task in order to understand this use case.
8:37:32
작업은 각 고객이 30보다 큰 판매로 주문한 횟수를 세라고 합니다.
the task says count how many times each customer has made an order with sales greater than 30.
8:37:37
좋습니다. 평소처럼 단계별로 진행할 수 있습니다.
all right so as usual we can do it step by step so
8:37:41
우리가 필요한 것은 주문이므로 주문 ID를 가져옵니다.
what do we need we need the orders so let's get the order id
8:37:44
그리고 고객 ID도 가져옵니다.
and as well let's get the customer id like
8:37:48
이렇게 하고 판매 주문에서 판매를 가져옵니다. 이제 실행해 보겠습니다. 그러면 그 데이터로 무엇을 할 것인지 정렬할 것입니다.
this and the sales from sales orders let's go and execute it so now what else i'm gonna do with that i'm gonna go and order the data
8:37:58
고객 ID로 정렬하겠습니다. 다시 실행해 보겠습니다. 이제 작업이 쉬워 보이지만 약간 까다롭습니다. 우리는 판매가 30보다 높은 각 고객의 주문 수를 세어야 합니다.
by customer id so let's execute it again okay so now the task sounds easy but it's a little bit tricky we have to count the number of orders for each customer where the sales is higher than 30.
8:38:09
예를 들어 고객 번호 1의 예를 들어 보겠습니다. 총 주문 수는 3개입니다. 하지만 우리는 판매가 30보다 높은 주문만 세어야 합니다.
let's have an example for example this customer number one so the total number of orders is three orders right but we have to count only the orders where the sales is higher than 30.
8:38:18
이 예에서는 판매가 30보다 높은 주문이 하나뿐입니다.
and in this example we have only one order where
8:38:22
그래서 판매가 30보다 높은 것은 주문 번호 4뿐입니다.
the sales is higher than 30 so it's only the order number four
8:38:25
따라서 고객 ID 번호 1의 카운트는 1이어야 합니다. 이제 다른 고객, 예를 들어 고객 번호 2를 확인해 보겠습니다. 보시다시피 우리는 3개의 주문이 있지만 그 중 어느 것도 판매가 30보다 높지 않습니다.
so the count for the customer id number one should be one now let's check another customer for example the two and as you can see we have three orders but none of them have the sales higher than 30.
8:38:36
그래서 카운트는 여기서 0이어야 합니다. 그럼 우리는 어떻게 할까요?
so the count should be zero here so how we're gonna do that
8:38:39
각 행을 플래그해야 합니다. 그것이 30보다 높은지 아닌지.
we have to go and flag each row whether
8:38:42
30보다 높으면 1의 플래그를 받습니다. 30보다 낮거나 같으면 0을 받습니다. 그런 다음 우리는 모든 플래그를 요약할 것입니다.
it's higher than 30 or not so if it's higher than
8:38:46
그래서 단계별로 진행해 보겠습니다. 먼저 플래그를 생성하겠습니다.
30 it gets the flag of one if it's less than 30 or equal to 30 it's gonna get zero and then we're gonna go and summarize
8:38:53
그래서 우리는 case를 사용하고 조건은 매우 간단합니다. 우리는 '언제'라고 말할 것입니다. 조건은 판매가 30보다 큰 경우입니다.
all those flags in order to get the count so let's do it step by step let's first create the flag
8:38:59
판매가 30보다 높으면 어떻게 될까요? 우리는 그것을 1로 플래그할 것입니다.
so we're gonna go and use case and then our condition is very easy we're gonna say when so what is the condition sales greater than 30 so sales is higher than 30.
8:39:10
나중에 우리는 1을 요약할 것입니다. 이제 30보다 높지 않거나 30과 같거나 낮으면 0을 받습니다. 알겠습니다. 이제 진행해 보겠습니다.
then what can happen we're gonna flag it with the one because
8:39:13
그리고 판매를 종료하겠습니다.
later we're gonna go and summarize the one and now else if it's not higher than 30 equal to 30 or less so it's gonna get zero all right so now let's go
8:39:22
그리고 끝내고 판매를 보자
and end it so and let's say sales
8:39:25
지금 플래그를 실행하고 결과를 확인하자
flag now let's go and execute it and check the results all right so now if you check the results we got now a very nice flag in order to see which orders has sales higher than 30.
8:39:35
예를 들어 고객 ID 번호 1을 보자
so now for example let's take that customer id number one as you can see
8:39:38
주문 번호 4만 판매가 30 이상이다
only the order number four has sales higher than
8:39:41
그리고 30이고 플래그가 1로 설정되어 있으며 나머지는 0이다
30 and it's flagged with one and all others are zero now let's take that customer id number three and as you can see we have now two orders where the sales is higher than 30.
8:39:51
그리고 우리가 하나를 두 번 보았다. 이제 이 플래그를 사용하여 집계를 할 수 있다.
And as you can see, we have the one twice. And now we can use this flag in order to do the aggregation.
8:39:56
고객 ID 번호 3에 대한 플래그를 요약하면
So now if you go and summarize the flag for the customer
8:40:00
우리는 2를 얻을 것이다. 그리고 이것은 판매가 30 이상인 주문의 수이다.
ID number three, we will get two. And this is the count of orders where the sales is higher than 30. Right.
8:40:05
고객 ID 번호 2의 또 다른 예를 보자. 우리는 모든 곳에서 0이다.
And let's take another example, the customer ID number two. We have everywhere zero.
8:40:09
이 값을 요약하면 0이 나온다.
And if we summarize those values, we will get zero, which is the count of orders where the sales is higher than 30, which is correct.
8:40:16
그래서 우리는 집계를 도와줄 추가 열을 만들었다.
So as you can see, first, we have built an extra column in order to help us doing the aggregation.
8:40:20
이제 다음 단계에서 이 열을 집계할 것이다.
And now in the next step, we're going to go and aggregate this column. So let's go and do that. We don't need all those informations.
8:40:27
주문 ID. 우리는 고객 ID가 필요하다.
The order ID. We need the customer ID because it is the granularity for the aggregation.
8:40:32
그리고 정렬을 제거하자. 이제 고객 ID로 데이터를 그룹화하자.
And let's remove the order by. And now let's go and group up the data by customer ID.
8:40:40
물론 집계 함수가 필요하다.
But of course, we need the aggregate function. So how are we going to do it? We're going to go and summarize the whole flag.
8:40:45
그래서 이제 우리는 이것을 집계된 열로 이름을 바꾸어야 한다.
So and now, of course, we're going to go and rename this since now it is an aggregated column.
8:40:51
그래서 우리는 이것을 총 주문이라고 부를 것이다.
So we're going to call it total orders. So now let's go and execute it. So now let's go and check the result.
8:40:58
고객 ID 번호 1에 대해 30 이상인 주문이 하나뿐이다.
as you can see now we have our four customers and for the customer id number one we got only one order higher than 30.
8:41:04
두 번째 고객은 30 이상인 주문이 없다.
the second one has no orders higher than 30.
8:41:07
세 번째 고객은 두 개와 하나가 있다.
the third we have two and one and with that we have solved
8:41:10
작업을 완료했다. 쿼리에 한 가지를 더 추가하고 싶다.
the task now i would like to add one more thing to our query in order to
8:41:13
정상 집계를 보자.
see the normal aggregations not the conditional aggregations so usually we go and count for
8:41:19
예를 들어 총 주문을 얻기 위해 별을 사용하자.
example the star in order to get the total orders and let's rename the previous one to high sales
8:41:27
조건 없이 집계를 실행하자.
so let's go and execute it so we are just now doing aggregations
8:41:31
각 고객이 몇 개의 주문을 했는지 볼 수 있다.
without any conditions and now we can see how many orders did each customer so we can see that the customer id number one did order three times but only one order higher than 30.
8:41:41
그래서 이것은 일반 집계이며, 이것은 조건부 집계입니다. 자, 친구들, 이제 케이스 문에 대해 요약해 보겠습니다.
so this is a normal aggregation and this is a conditional aggregations using the case statements all right friends now let's do a recap about the case statements.
8:41:53
케이스 문은 조건 목록을 하나씩 평가하고 첫 번째 조건이 충족되면 값을 반환할 수 있습니다.
Case statement can go and evaluate the list of conditions one by one and return value once the first condition is met.
8:42:00
그리고 케이스 문을 사용하는 규칙에 대해 이야기한다면, 조건 뒤의 데이터 유형이 일치해야 한다는 하나의 규칙만 있습니다.
And if we are talking about the rules of using the case statements, we have only one where the data types of each condition after the then and else must be matching.
8:42:09
이제 케이스 문의 사용 사례에 대해 이야기해 보겠습니다. 주요 사용 사례는 데이터 변환을 수행하는 것이며, 특히 새로운 열을 만들고 새로운 정보를 생성하는 것입니다.
And now if we talk about the use cases of the case statements, the main use case is to do data transformations, and especially by creating new columns and driving new information.
8:42:19
우리가 본 것처럼 케이스 문에는 놀라운 사용 사례가 있습니다.
So as we saw there are amazing use cases for the case
8:42:22
예를 들어, 데이터를 분류하는 데 사용할 수 있습니다.
statements for example we can use it in order to categorize our data
8:42:25
우리가 배운 대로, 새로운 데이터 그룹을 만들 수 있습니다.
as we learned we can go and create a new groups of data then
8:42:28
보고서를 위해 집계될 수 있으며, 또 다른 사용 사례는 값 매핑입니다.
to be aggregated for our reports and then we saw another use
8:42:31
우리는 케이스 문을 사용하여 데이터베이스에 저장된 암호화된 기술 값을 매핑하는 데 도움을 줄 수 있습니다.
case is mapping values we can use the case statement in order to help us mapping the cryptical technical values that is stored in databases
8:42:40
더 읽기 쉽고 친숙한 새로운 값으로 변환할 수 있습니다.
to new values which is more readable and more
8:42:43
다음 사용 사례는 널 값을 처리하는 것입니다.
friendly to be used and the next use case that we have learned is handling
8:42:46
널 값을 대체하여 집계를 더 정확하게 만들 수 있습니다.
the nulls we can use the case statement in order to
8:42:49
더 정확하게 만들고, 우리가 배운 마지막 사용 사례는
replace the nulls with value to make our aggregations
8:42:52
내 프로젝트에서 가장 많이 사용되는 것은 조건부 집계입니다.
more accurate and the last use kit that we have learned and i think
8:42:56
특정 조건을 충족하는 데이터의 하위 집합을 집계할 수 있습니다.
the most used one in my project is doing conditional
8:42:59
특정 조건을 충족하는 데이터의 하위 집합을 집계할 수 있는 집계
aggregations where we can aggregate a subset of data that
8:43:02
분석을 집중하고 목표로 삼기 위해 필요한 모든 주제와 기능을 다루었습니다.
meets specific conditions in order to do focus and target analyzes okay my friends so with that we have covered all the topics and all the functions in order to transform
8:43:12
SQL에서 단일 값, 원시 수준의 함수는
single value in sql the raw level functions that
8:43:15
특히 데이터 엔지니어에게 매우 중요했습니다.
was very important especially for data engineers so
8:43:18
이 장은 여기서 끝났고 이제 매우 흥미로운
we are done with this chapter now we are moving to very interesting
8:43:22
장으로 넘어갑니다. 마침내 SQL에서 데이터 분석에 대해 이야기할 것입니다.
chapter finally we're going to talk about data analytics in sql
8:43:25
이제 SQL에서 집계 및 분석 기능을 다룰 것입니다.
and we will be covering now the aggregate and the analytical functions
8:43:28
먼저 기본부터 시작하겠습니다.
that we have in sql so first we're going to start with the basics
8:43:32
데이터를 집계하는 방법에 대한 간단한 함수를 배울 것입니다. 자, 친구들, 이제 SQL의 집계 함수에 대해 이야기할 것입니다.
so we will learn simple functions on how to aggregate your data so let's go hey my friends so now we're going to talk about about the aggregate functions in SQL.
8:43:44
데이터 분석가나 데이터 과학자라면 놀라운 기능입니다. 우리는 보통 데이터를 통해 통찰력을 발견하기 위해 사용합니다.
They are amazing if you are a data analyst or data scientist where we usually use them in order to uncover insights about our data.
8:43:51
그래서 집계 함수는 여러 행을 입력으로 받아들이고 집계 함수의 출력은 보통 하나의 값입니다.
So the aggregate functions, they accept multiple rows as an input and the output of the aggregate function usually is one single value.
8:43:58
이제 우리는 SQL의 기본 집계 함수에 대해 먼저 다룰 것입니다. 시작합시다.
So now we're gonna go and cover first the basic aggregate functions in SQL. So let's go.
8:44:03
현재 데이터베이스에는 네 개의 주문이 있으며 각 주문에 대한 판매 정보가 있습니다.
So now in our database, we have four orders and we have the sales informations for each one of them.
8:44:08
이제 떠오르는 질문은 우리 비즈니스의 총 주문 수는 얼마인가요? 우리는 몇 개의 주문을 가지고 있나요?
So now one question that comes in our mind, What is the total number of orders in our business? So how many orders do we have?
8:44:15
이를 위해 우리는 count 함수를 사용합니다. 이 함수는 테이블 내의 행 수를 세는 것입니다.
Now, in order to do that, we use the function count. Because what it does, it's going to go and count the number of rows inside our table.
8:44:22
이 데이터에 count 함수를 적용하면 SQL이 몇 개의 행이 있는지 세기 시작합니다. 총 수는 네 개입니다.
So if you apply the count function on this data, SQL is going to go and start counting how many rows do we have. So the total number is four.
8:44:29
출력에서는 네 개를 얻게 됩니다. 테이블의 내용은 별로 중요하지 않습니다.
And in the output, we will get four. So as you can see, we don't really care about the content of the tables.
8:44:34
SQL은 단순히 몇 개의 행인지 세고 있습니다. 이 숫자는 판매 정보나 주문에 기반하지 않습니다.
SQL is just counting how many rows. So the number is not based on the sales of formations or the orders.
8:44:40
이것이 count 함수의 작동 방식입니다. 이제 우리는 또 다른 질문이 있습니다. 데이터에서 총 판매액을 찾고 싶습니다.
So this is how the count function works. Now we have another question and we say, I would like to find the total sales in our data, in our business.
8:44:47
즉, 주문에서 우리가 가진 모든 판매를 요약해야 합니다. 이를 위해 sum 함수가 있습니다.
So that means we have to go and summarize all those sales that we have in the order. And for that, we have the sum function.
8:44:53
sum 함수를 적용하면 모든 판매를 요약하고 최종적으로 총 판매액을 반환합니다.
So if you go and apply the sum function, it's going to go and summarize all the sales and return at the end the total sales.
8:44:59
이 예제에서 총 판매액은 80이 될 것입니다. 집계 함수는
and this example is going to be 80 so as you can see the aggregate
8:45:02
여러 행과 여러 값을 받아들이고
function accepts multiple rows multiple values and
8:45:06
출력은 하나의 값, 즉 집계된 값이 됩니다.
the output going to be one single value the aggregated
8:45:09
이제 평균이 무엇인지 이해하고 싶습니다.
value now moving on i would like to understand what is the average
8:45:12
우리 비즈니스의 평균 판매액을 이해하기 위해 평균 함수를 사용할 것입니다.
sales in our business so it sounds simple in order
8:45:15
이를 위해 평균 함수를 사용하고 판매에 적용하면 모든 값을 요약하고 값의 수로 나누어 평균 20을 얻게 됩니다.
to do that you're going to use the average function so if you apply it on the sales it's going to go and summarize all those values and divide it by the number of values so you will get average of 20.
8:45:26
이제 데이터에서 가장 높은 판매액이 무엇인지 찾고 싶습니다. 이를 위해 max 함수를 사용할 수 있습니다.
Now comes interesting question where you want to find what is the highest sales in my data. So for that, we can use the function max.
8:45:33
함수를 적용하면 테이블 내에서 가장 높은 값을 찾기 시작합니다.
So once you apply it, it's going to go and start searching for the highest value inside our table.
8:45:38
이번에는 데이터를 새로운 것으로 집계하는 것이 아닙니다. 여러 값 중에서 가장 높은 값을 찾는 것입니다.
So this time we are not really aggregating the data into something new. It's like searching for the highest value between multiple values.
8:45:46
이 예제에서는 35가 가장 높은 판매액이 될 것입니다.
So in this example, we will get the 35 as the highest sales.
8:45:49
이제 비즈니스 내에서 가장 낮은 판매액을 보고 싶다면
Now, of course, if you want to see the lowest sales inside your business
8:45:52
min 함수를 사용할 수 있으며, 이를 적용하면 판매에서 가장 낮은 값을 찾기 시작합니다. 이 예제에서는 10이 될 것입니다.
you can use the min function and if you go and apply it as well the same thing is going to go and start searching for the lowest value in the sales and in this example it's going to be the 10.
8:46:02
보시다시피 집계 함수는 매우 간단하지만 매우
so as you can see guys the aggregate functions is very simple but yet very
8:46:05
강력하여 통찰력을 얻는 데 정말 유용합니다.
powerful so it is really useful for insights in order to
8:46:08
비즈니스 성과를 이해하기 위해
understand how well your business is performing so now let's go to sql in
8:46:11
SQL로 가서 그 기능들을 시도해 보겠습니다.
order to try those functions okay so now we're going to go and analyze
8:46:15
데이터베이스 내의 주문 테이블을 분석해 보겠습니다.
the orders table inside our database by doing very simple aggregations so let's start with the first task it says find the total number of orders so this time we are targeting the table
8:46:26
주문 테이블을 선택하는 것부터 시작해 보겠습니다.
orders so let's just start with the select so now we
8:46:29
우리는 네 개의 주문이 있다는 것을 알 수 있습니다.
can see we have like four orders and now we would like to have like one
8:46:32
우리가 할 수 있는 것은 count star라고 말하는 것입니다.
number what we can do we can go and say count star
8:46:36
총 주문 수로서
as total number of orders so
8:46:39
우리가 얻은 숫자는 4입니다.
let's go and execute it and with that we got one number it
8:46:42
이것이 총 주문 수입니다.
is the four this is the total number of orders now let's move
8:46:45
두 번째 작업으로 넘어갑니다.
to the second task it says find the total sales
8:46:49
모든 주문의 총 매출을 찾는 것입니다.
of all orders so this time we have to summarize all
8:46:52
모든 매출 값을 하나의 큰 값으로 요약해야 합니다.
the sales values in one big value so how
8:46:56
이를 위해 sum 함수를 사용할 수 있습니다.
to do it we can use the function sum and this
8:46:59
이번에는 매출을 대상으로 하겠습니다.
time we are targeting the sales and we're gonna go and call it
8:47:02
총 매출을 호출하겠습니다.
total sales so let's go and execute
8:47:05
그 결과 80이 총 매출 수입니다.
it and with that we have 80 as the total number of
8:47:08
모든 매출 값이 하나의 큰 값으로 요약됩니다.
sales so all the the sales values are summarized in one big value
8:47:11
이제 비즈니스를 탐색하고 있습니다.
so as you can see now we are exploring the business right we are
8:47:14
몇 개의 판매와 몇 개의 주문이 있는지 이해하고 있습니다.
understanding how many sales how many orders so this is
8:47:17
이것이 SQL에서 분석의 기초입니다.
really the basics of analytics in sql now let's go to the second
8:47:20
모든 주문의 평균 매출을 찾아보겠습니다.
task let's find the average sales of all orders so
8:47:24
이번에는 평균 매출을 구할 것입니다.
we're gonna have average this time the sales
8:47:27
평균 판매량으로 다시
as average sales again
8:47:30
매우 간단합니다. 이제 실행해 봅시다. 총 판매량은 80이지만 평균 판매량은 20입니다. 그래서 모든 판매량의 값이 요약되고 주문 수로 나누어집니다.
very simple let's go and execute it now the total sales is 80 but the average sales is 20 so all the values of the sales is summarized and then the divided by the number of orders.
8:47:40
그래서 80을 4로 나누면 됩니다. 그리고 그로 인해 SQL이 20을 평균으로 찾습니다. 이제 흥미로운 내용을 찾아봅시다.
So 80 divided by four. And with that, SQL finding that 20 as an average. Now let's go and get interesting stuff.
8:47:46
모든 주문의 최고 매출을 찾아봅시다. 우리 비즈니스에서 발생하는 최고 매출은 무엇인가요?
Let's go and find the highest sales of all orders. So what is the highest sales that happens in our business?
8:47:53
이를 위해 max sales 함수를 사용하여 최고 매출을 구할 수 있습니다.
In order to do that, you can use the function max sales as highest sales.
8:48:00
아주 좋습니다. 실행해 봅시다. 데이터베이스에서 최고 매출은 35입니다.
Very nice. Let's go and execute. So the highest sales in the database is 35.
8:48:05
이제 다음 작업이 무엇인지 이미 알고 계실 것 같습니다.
And now I think you already know what is the next task.
8:48:08
모든 주문의 최저 매출을 찾아봅시다.
find the lowest sales of all orders so this
8:48:11
이는 정반대입니다. min sales를 사용하여 최저 매출을 구할 것입니다. 우리 비즈니스의 최저 매출은 10이었습니다.
is exactly the opposite we're going to go and use the min sales as lowest sales so let's go and execute the lowest sales in our business was 10.
8:48:22
친구들, 집계 함수가 정말 놀랍다는 것을 알 수 있습니다.
so my friends as you can see the aggregate functions are really amazing and
8:48:25
이렇게 사용하면 큰 숫자를 얻을 수 있습니다.
if you use it like this you will get like the big numbers about
8:48:28
하지만 이제 집계 함수를 잊지 마세요.
our business but now don't forget about the aggregate functions
8:48:31
그룹으로 묶으면 큰 숫자를 나누게 됩니다.
if you combine it with a group by then you will be breaking those big numbers into
8:48:38
고객 ID로 집계하는 것과 같은 방식입니다.
something like you are aggregating by the customer id
8:48:41
날짜나 국가별로도 가능합니다.
maybe by a date by a country so
8:48:44
그룹으로 묶은 내용을 지정하면 큰 숫자를 줄일 수 있습니다.
anything you specify with the group by it gonna break those
8:48:47
예를 들어 고객 ID로 가보겠습니다.
big numbers into a smaller number based on the column that
8:48:50
이제 시작 부분에 넣어 보겠습니다.
you are using for example let's go with the customer id over here
8:48:54
실행하면 출력에서 모든 것을 볼 수 있습니다.
and let's put it at the start as well now
8:48:57
이제 숫자가 더 이상 큰 숫자가 아니고, 우리가 지정한 열에 따라 더 많은 세부정보로 나눠집니다.
if you go and execute it so now as you can see in the output all
8:49:00
지정한 대로 이제 각 고객에 대한 총합이 있습니다.
those numbers are not anymore like big numbers we drill down to more details based on the column that we
8:49:07
주문 수, 총 매출, 평균 매출입니다.
specified so now we have for each customer the total
8:49:10
최고 매출 또는 최저 매출입니다. 물론 데이터는
number of orders the total number of sales the average sales
8:49:13
매우 작고, 이러한 숫자는 더 큰 데이터가 있을 경우 더 흥미로울 수 있습니다.
the highest sales or the lowest sales of course the data is
8:49:17
더 큰 데이터와 함께 집계 함수를 결합하면
very small and those numbers can be more interesting if you have
8:49:20
그룹으로 묶으면 큰 숫자를 더 많은 세부정보로 나눌 수 있습니다.
bigger data so if you combine the aggregate functions together with
8:49:23
고객에 대해 점수가 있으며, 이를 적용할 수 있습니다.
the group by you will break those big numbers into more details based on the column that you are grouping by so now what you can do you can go and apply those functions as well
8:49:32
고객에 대해 평균 점수, 최고 점수, 최저 점수를 찾을 수 있습니다.
for the customers there we have a score and you can
8:49:36
평균 점수, 최고 점수, 최저 점수를 찾아보세요.
go and find the average score the highest score the lowest
8:49:39
그런 다음 데이터를 국가별로 그룹화할 수 있습니다.
score and then you can group up the data by the country
8:49:42
예를 들어, 비디오를 일시 정지하고 집계 작업을 수행하세요.
for example so pause the video and do some aggregations
8:49:45
모든 고객의 테이블에서
on the table customers all
8:49:52
자, 친구들, 이제 집계하는 방법의 기초를 배웠습니다.
right my friends so with that you have learned the basics on how to aggregate
8:49:55
이제 SQL을 사용하여 데이터를 집계하는 방법을 더 고급으로 넘어갈 수 있습니다.
your data using sql now we can move to more advanced
8:49:59
데이터를 집계하는 방법에 대해 이야기할 것입니다.
way on how to aggregate your data we will start talking about
8:50:02
윈도우 함수와 분석 함수에 대해 이야기할 것입니다.
the window functions the analytical functions so first
8:50:05
먼저 윈도우 함수가 무엇인지에 대해 이야기할 것입니다.
we're gonna start talking about what is exactly window functions and
8:50:08
이 주제에 대한 기초를 다룰 것이니 윈도우
we're gonna cover the basics about this topic so let's go window
8:50:16
함수 또는 때때로 분석 함수라고 부릅니다.
functions or sometimes we call them analytical functions they
8:50:19
SQL에서 매우 중요한 함수입니다.
are very important functions in sql everyone must
8:50:22
특히 데이터 분석을 하는 경우 알아야 합니다.
know them especially if you are doing data analyzes each
8:50:25
데이터 분석을 위해 SQL 스크립트를 작성할 때마다
time i write sql script in order to do data analytics i
8:50:28
결국 이들을 사용하게 됩니다.
end up using them so as usual we're gonna go and now understand
8:50:32
자, 이제 그 개념을 이해해 봅시다.
the concept behind them and then we're gonna start practicing so
8:50:36
가자, 좋아
let's go okay
8:50:40
자, 이제 첫 번째 질문부터 시작해 보겠습니다. SQL이란 무엇인가요?
guys so now let's start with the first question what are sql
8:50:44
윈도우 함수는 집계와 같은 계산을 수행할 수 있게 해주는 함수입니다.
window functions they are functions that allows you to do calculations like aggregations but on top of
8:50:50
데이터의 하위 집합에서 세부 정보를 잃지 않고
subset of data without losing the level of
8:50:53
행의 세부 사항을 유지하는 것과 매우 유사합니다.
details of the rows so it is something very similar to the group
8:50:56
그룹화와 비슷하지만, 여기에는 특별한 경우가 있습니다. 세부 정보를 잃지 않습니다.
by but here we have special case you don't lose the
8:51:00
이제 정의를 이해하기 위해 간단한 예를 들어보겠습니다.
level of details so now in order to understand the definition let's
8:51:03
자, 이제 SQL이 어떻게 작동하는지 이해해 봅시다.
have a very simple example okay so now let's understand how sql
8:51:06
그룹 바이 클라우드와 함께. 우리가 있다고 가정해 봅시다.
works with the group by clouds let's say that we have the very
8:51:09
간단한 예로, 우리는 네 개의 주문이 있습니다. 모자에 대한 두 개의 주문과 장갑에 대한 두 개의 주문이 있습니다. 그리고 총 판매량을 보고 싶다고 가정해 봅시다.
simple example we have four orders two orders for the caps and two order for the gloves and let's say that i would like to see the total
8:51:17
각 제품에 대한 판매량을 보려면, 이제 그룹화를 사용하기로 결정했다면
sales for each product so now if you decided to use
8:51:20
그룹화를 사용하면 SQL이 첫 번째
the group by what is ql gonna do gonna take the first
8:51:23
모자에 대한 두 개의 주문을 가져와서 한 행에 넣습니다.
two orders for the caps and put it in one row
8:51:26
출력에서는 모자에 대한 행이 하나만 있게 됩니다.
so in the output we're gonna have only one row for the caps
8:51:29
총 판매량이 40이 되고, 같은 일이 장갑에서도 발생할 수 있습니다.
with the total sales of 40 and the same thing can happen
8:51:33
장갑에 대한 두 개의 행을 입력에서 가져와서
for the gloves so we're gonna take the two rows of the gloves from
8:51:36
출력에서는 장갑에 대한 행이 하나만 있게 됩니다. 즉, 행의 수는 제품의 수에 따라 달라집니다.
the input and in the output we're gonna have only one row for the gloves so that means the number of rows gonna be depending on the number of products
8:51:44
데이터에서 우리는 두 개의 제품이 있고 두 개의 행을 얻습니다.
we have on our data we have two products we get two rows
8:51:47
즉, SQL은 결과를 압축하거나 압착하는 것과 같습니다.
so that means sql is really like smashing or squeezing
8:51:51
출력의 결과는 바로 이것이며, 그룹화가 데이터에 대해 수행하는 작업입니다. 행을 집계합니다.
the results in the output and this is exactly what
8:51:54
데이터를 서로 다른 세부 수준으로 집계합니다.
the group by does to our data it aggregates the rows aggregate the
8:51:57
이제 왼쪽에는 네 개의 행이 있고 오른쪽에는
data into different level of details so
8:52:00
두 개의 행이 있으며, 이로 인해 결과에서 일부 세부 정보가 손실되고 있지만 여전히 작업을 해결했습니다. 이제 SQL에서
now on the left side we see four rows on the right side
8:52:03
윈도우 함수를 사용하면 어떤 일이 발생할 수 있는지 살펴보겠습니다. 이제 같은 데이터가 있습니다.
we have two rows and with that we are losing some details in the results but still we have solved the tasks so now let's see what can happen if you use a
8:52:11
그리고 같은 작업을 수행해야 합니다. 각 제품에 대한 총 판매량을 찾아야 합니다.
window function in sql okay so now we have the same data and as
8:52:14
이제 윈도우 함수를 사용하면 SQL이
well the same task we have to find the total sales for each product
8:52:18
다음과 같은 작업을 수행합니다. 각 행을 개별적으로 실행합니다.
now if you use window function sql
8:52:21
서로 독립적으로 실행되므로 어떤 일이 발생할 수 있는지
gonna do the following it's gonna go and execute each rows
8:52:24
첫 번째 행, 주문 ID 1부터 시작합니다.
individually from each other's so what can happen it
8:52:27
첫 번째 행에서 주문 ID 1로 시작합니다.
start with the first row the order id one in
8:52:30
출력은 동일한 내용으로, 주문 ID 1의 동일한 행이지만 모자의 총 판매량을 얻을 것입니다. 여기서 총 판매량은 10입니다.
the output we're gonna get as well the same stuff the order id one the same row but we will get the total sales for the caps so here the total sales is gonna be 10
8:52:39
30이 되면 40을 얻을 것이고, 그 다음 두 번째 행으로 넘어갑니다.
30 we will get 40 then it's going to jump to the second
8:52:42
행을 처리할 것이며, 출력에서
row and it's going to process it as well so in the output
8:52:45
주문 ID 2와 제품 모자를 얻게 될 것입니다.
we will get the order id 2 the product caps and as
8:52:48
우리는 같은 제품에 대해 이야기하고 있으므로
well we have the same aggregation since we are talking about the same
8:52:51
40을 얻을 것이고, 그러면 세 번째 주문으로 넘어갈 것입니다.
product so we will get 40 then it's going to go to the third order
8:52:55
여기서 우리는 장갑을 가지고 있으며, 출력에서 다시 주문 ID가 있습니다.
and here we have the gloves so in the output again we have the order id
8:52:58
3번 제품 장갑과 이번 총 판매량은 5 더하기 20이므로 25를 얻을 것입니다.
3 the product gloves and the total sales this time going to be 5 plus 20 so we'll get 25 then it goes
8:53:05
출력에서 주문 ID 번호 4로 마지막 행으로 갑니다.
to the last row to the order id number four in the output
8:53:08
우리는 4개의 장갑과 25를 얻을 것입니다.
we're gonna get four gloves and as well 25 so now
8:53:11
윈도우 함수를 사용하면 데이터의 세부 수준을 잃지 않을 것입니다.
we can notice that if you use the window function you will
8:53:14
우리는 행 수준 계산이라고 하는 작업을 하고 있습니다.
not lose the level of details of your data so
8:53:18
입력 데이터에 4개의 주문이 있다면 출력에서 우리는
we are doing something called row level calculations so
8:53:21
4개의 주문을 얻을 것이고, 집계도 정확하게 얻을 것입니다.
if in input data we have four orders in the output we're
8:53:24
두 방법을 나란히 비교하면 우리는
gonna get four orders and as well we will get our aggregations correctly so now if you compare both of the methods side by side we can see that we are
8:53:32
같은 작업을 해결하고 있으며, 각 제품의 총 판매량을 찾고 있습니다.
solving the same task so we are finding the total sales for
8:53:35
그룹 구매를 통해 우리는 결과를 압축하고 있습니다.
each product but with the group buy we are smashing
8:53:39
4개의 주문에서 두 행으로, 각 주문에 대해 한 행씩.
squeezing the results from four orders into
8:53:42
그룹 구매로 인해 세분화가 변경됩니다.
two rows one row for each order so that
8:53:45
입력에서 주문 ID가 세부 수준을 제어하지만, 그룹 구매의 출력에서는 제품이 세부 수준을 제어합니다.
means with the group buy the granularity is changing right in
8:53:48
우리는 여전히 집계를 수행할 수 있지만 세부 사항을 잃지 않고 있습니다.
the input the order id is controlling the level of details but in the output of the group buy the product is controlling the level of details so we have different granularity but in the other hand in the window functions
8:54:00
입력의 세부 수준이
we are still able to do aggregations but we are not losing the
8:54:03
출력의 결과와 같을 수 있습니다.
level of details so the granularity of the input can
8:54:06
이것이 그룹 구매와 윈도우 함수 간의 주요 차이점입니다.
be the same like the output in the results so this
8:54:09
단순 집계만 하려면
is exactly the main difference between the group by and the window function
8:54:13
그룹 구매를 사용하세요. 하지만 세부 수준이 중요하다면
if you want just to do simple aggregations then
8:54:16
결과에 더 많은 세부 사항을 추가해야 하므로 윈도우 함수를 사용할 수 있습니다.
go with the group by but if you care about the level of
8:54:19
세부 사항을 추가해야 하며, 이제 윈도우와
details and you need to add more details to your results then you can go with the window function where you can do aggregations plus having more
8:54:27
그룹 구매 간의 함수를 비교하면 두 가지 모두 정확히 동일합니다.
details and now if you go and compare the functions between the window and
8:54:30
그룹화에서 우리는 두 가지가 정확히 동일한
the group by we can find that both of them has exactly the
8:54:33
집계 함수가 있으므로 카운트 합계를
same functions for the aggregations so we have the count sum
8:54:36
평균 최대값이 있으며 여기서 또 다른 차이점이
average mean max and here comes another difference between
8:54:39
창과 그룹화 사이에 있습니다. 그룹화는 오직 집계
the window and the group by the group by has only the aggregate
8:54:42
함수만 가지고 있습니다. 그래서 그게 전부지만 창 함수에서는
functions so that's it but at the window functions we
8:54:46
분석에 사용할 수 있는 훨씬 더 많은 함수가 있습니다.
have way more functions to use for analytics so
8:54:49
예를 들어, 우리는 순위 함수를 가지고 있으며 여기서 값에 대한 또 다른 함수 그룹이 있습니다. 또는 이를 분석 함수라고 부릅니다. 즉, SQL 창에서는 많은 함수가 있습니다.
for example we have the ranking functions and we have here another group of functions for the value or we call it analytical functions so that means in the SQL window, we have a lot of functions.
8:54:58
우리는 많은 분석 사용 사례와 고급 복잡한 작업을 다룰 수 있습니다.
We can cover a lot of analytical use cases and advanced complex stuff.
8:55:03
하지만 그룹화에서는 단순한 사용 사례에 대해서만 집계 함수가 있습니다.
But with the group by, we have only the aggregate functions only for simple use cases.
8:55:08
그래서 이것은 그룹화와 창 그룹화 사이의 또 다른 차이점입니다.
So this is another difference between the group by and the window group by use it.
8:55:13
간단한 분석, 간단한 집계, 창 함수가 있다면, 우리는 더 고급 데이터 분석에 사용할 것입니다.
If you have a simple analysis, simple aggregations, window functions, we're going to use it for more advanced data analysis, where we're going to cover a lot of use cases.
8:55:21
좋아요, 여러분, 이제 하나를 이해하기 위해 몇 가지 작업을 할 것입니다.
All right, guys, so now we're going to have a few tasks in order to understand one
8:55:24
왜 스케일 창 함수가 필요한지와
thing why do we need a scale window functions and
8:55:28
어떤 시나리오에서는 그룹화가 충분하지 않기 때문에
why in some scenarios group by is not enough and we
8:55:31
스케일 창 함수를 사용해야 합니다. 자, 시작해봅시다.
have to use a scale window functions so let's go all right so
8:55:34
매우 간단한 작업을 시작할 것입니다. 총 매출을 찾으라고 할 것입니다.
let's start with very simple task it's gonna say find the
8:55:37
모든 주문의 총 매출을 찾으라고 할 것입니다.
total sales across all orders so we
8:55:40
하나의 값, 총 매출이 필요합니다. 어떻게 할 수 있는지 봅시다.
need one value the total sales let's see how we can do that
8:55:43
먼저 데이터베이스를 사용하고 있는지 확인하세요.
first make sure that you are using the database so
8:55:46
클라이언트를 닫은 경우 매출 데이터베이스를 사용하세요.
use sales database in case you have closed the clients so that we don't get any errors so now we're gonna start with the
8:55:53
첫 번째로 우리는 매출을 선택할 것입니다. 테이블에서 찾을 것입니다.
first thing we're going to go and select the sales you're going to find
8:55:56
판매 주문 테이블에서 찾을 것입니다.
it in the table sales orders so
8:55:59
이제 데이터를 쿼리해 봅시다. 보시다시피 10개의 주문이 있습니다.
now let's just query the data and as you can see we have 10 orders with
8:56:03
10개의 판매가 있으며 아직 집계한 것이 없습니다.
10 sales we didn't aggregate anything yet so we
8:56:06
이제 원시 데이터가 있습니다. 이제 작업을 해결하기 위해 사용할 것입니다.
have the raw data now so now in order to solve the task we're going to use
8:56:09
이제 원시 데이터를 가지고 있으니, 이 작업을 해결하기 위해
the function sum so sum of sales and
8:56:12
합계 함수인 sum을 사용할 것입니다.
we're going to give it new name total sales we don't have to use any group by because we don't have to group up anything so that's it let's go and
8:56:21
우리는 이를 총 판매라는 새로운 이름으로 부를 것입니다. 그룹화할 필요가 없으니
execute that and as you can see sql can return one value 380
8:56:24
그게 전부입니다. 이제 실행해 봅시다.
this is the total sales that we have inside our data
8:56:27
SQL은 하나의 값 380을 반환할 수 있습니다.
and this is the highest level of aggregations
8:56:31
이것이 우리 데이터에 있는 총 판매입니다.
so with that we have solved the task we have the total sales
8:56:34
그리고 이것이 가장 높은 집계 수준입니다.
across all orders we don't have to group up anything
8:56:37
이로써 우리는 작업을 해결했습니다. 총 판매를 얻었습니다.
let's move to the next example let's say that in the next task
8:56:40
모든 주문에 걸쳐 그룹화할 필요가 없습니다.
this time we want to find the total sales but for
8:56:43
다음 예제로 넘어가 봅시다. 다음 작업에서는
each product so not for the all orders for each product we want to find the total sales so this time we
8:56:50
이번에는 각 제품에 대한 총 판매를 찾고자 합니다.
don't need only one value we need one value for each
8:56:53
모든 주문이 아니라 각 제품에 대해 총 판매를 찾고자 합니다.
product in order to do that now we're going to go and use
8:56:57
그래서 이번에는 하나의 값이 아니라 각 제품에 대한 값을 필요로 합니다.
the group by function and we're going to group up by
8:57:00
그렇게 하려면 이제 그룹화 함수를 사용하고
the product id and group up and need as well the
8:57:03
제품 ID로 그룹화할 것입니다.
dimension in the selection so i'm going to do it like this
8:57:06
선택에서 차원도 필요합니다. 이렇게 할 것입니다.
so that's it let's go and execute the query now
8:57:09
그게 전부입니다. 이제 쿼리를 실행해 봅시다.
as you can see in the results we don't have one value we don't have the highest aggregations this time we are drilling down to the next level of details so the level of
8:57:18
결과에서 보시다시피 하나의 값이 없고, 이번에는 다음 세부 사항 수준으로 내려가고 있습니다.
details here is the product id we have one row
8:57:21
여기서 세부 사항은 제품 ID입니다. 우리는 하나의 행을 가지고 있습니다.
for each product so for the first product we have 140 the
8:57:25
각 제품에 대해 첫 번째 제품은 140입니다.
next one 105 and so on so as you can see we are
8:57:28
다음 제품은 105이고, 계속해서 우리는
now splitting the data at the level of product id
8:57:31
이제 제품 ID 수준에서 데이터를 분할하고 있습니다.
and we went from 10 orders now in the results we have four orders and that's because we have four products so the number of rows at the output going to be defined by the dimension
8:57:43
10개의 주문에서 4개의 주문으로 줄어들었습니다. 이는 4개의 제품이 있기 때문입니다.
the product id and with that we have solved the task we have the
8:57:46
출력의 행 수는 차원에 의해 정의됩니다.
total sales for each product all right guys so let's keep progressing our
8:57:49
제품 ID와 함께 이로써 우리는 작업을 해결했습니다.
examples now the next one gonna be a little bit advanced
8:57:52
우리가 같은 집계를 가지고 총 판매량을 찾는 곳입니다.
where we have the same aggregation find the total sales
8:57:56
각 제품에 대해 추가 세부 정보를 제공하십시오.
for each product additionally provide details such
8:58:00
주문 ID와 주문 날짜를 포함하여 이미 해결한 첫 번째 부분입니다.
order id and the order date so as you can see we have already
8:58:03
각 제품의 총 판매량을 찾고 있으며, 추가 정보를 추가해야 합니다.
solved the first part we are finding the total sales for each product now we just have to add some additional
8:58:09
주문 ID와 주문 날짜와 같은 정보를 추가해야 합니다.
information like the order id and the order date so let's go over
8:58:12
여기에서 선택에 추가하겠습니다. 주문 ID와
here and just add it in our select so order id and
8:58:15
주문 날짜를 가져오고, 실행해 보겠습니다.
let's have the order dates so let's go and
8:58:18
그것을 실행해 보겠습니다. 이제 SQL이 행복하지 않을 것입니다.
execute that just gonna make it a little bit bigger so let's
8:58:21
오류가 발생하고 선택에 추가하는 내용이 그룹화에 포함되지 않았다고 말합니다.
go but now as you can see sql will not be happy connect through an
8:58:24
그룹화에는 제품 ID라는 하나의 차원만 있습니다.
error and says the stuff that you are adding to your selects are not included in the group by so as you can see in the group by we have only one dimension or one field called the product id
8:58:34
우리의 선택에는 주문 ID, 주문 날짜 및 제품 ID라는 세 가지 차원이 있습니다.
But in our selection, we have three dimensions, the order ID, the order date and the product ID.
8:58:40
선택과 그룹화 간에 일치하지 않기 때문에 SQL은 이를 허용하지 않습니다.
So there is no matching between the select and group by and SQL will not allow it.
8:58:45
이제 모든 것을 그룹화에 추가하자고 할 수 있습니다.
And now you might say, you know what, let's add everything to the group by. So with that, we're going to get our aggregation and as well, we're going to get our details.
8:58:52
주문 ID, 주문 날짜 및 제품 ID를 추가하겠습니다.
So let's try that. I'm just going to zoom out a little bit. And instead of having the product ID, let's add everything.
8:58:58
이제 일치가 생겼고 SQL에서 오류가 발생하지 않아야 합니다.
So the order ID, order date and the product ID. So now we have matching and SQL should not throw any error.
8:59:04
이제 작업을 해결했는지 확인해 보겠습니다. 작업은 두 부분으로 나뉩니다.
Let's go and execute it. So now let's check whether we have solved the task. The task has two parts, right?
8:59:09
우리는 집계를 수행하고 세부 정보를 제공해야 합니다.
We have to do the aggregations and to provide details. So as you can see, we have solved the second part.
8:59:14
세부 정보, 주문 ID 및 주문 날짜가 있습니다.
We have the details, order ID and order dates. But now the first part finding the total sales for each product is destroyed.
8:59:21
하지만 첫 번째 부분인 각 제품의 총 판매량이 파괴되었습니다.
Because if you check the results, we have the product ID 101. It has the total sales of 10.
8:59:28
결과를 확인하면 제품 ID 101의 총 판매량이 10입니다.
but in the third order we have it as a 20 for
8:59:31
세 번째 주문에서는 20으로 나타납니다.
the same product so actually the data is not aggregated and
8:59:34
같은 제품에 대해 데이터가 집계되지 않았습니다.
that's because we are aggregating at different levels and we have included
8:59:37
서로 다른 수준에서 집계하고 있습니다.
way more stuff that we don't need for the aggregations
8:59:40
우리는 집계에 필요하지 않은 더 많은 항목을 포함했습니다.
we are aggregating at the order id level so as
8:59:43
주문 ID 수준에서 집계하고 있습니다.
you can see now we are hitting the limits of group by we cannot
8:59:46
이제 우리는 그룹화의 한계에 도달하고 있습니다.
provide aggregations and as well provide additional informations from our data you have to pick one that's why we have to go to the second option where we can use the window functions.
8:59:56
그룹화 부분을 제거하겠습니다.
So let's do that. I'm just going to get rid of the group by part.
9:00:00
모든 필드를 루트로 되돌리겠습니다.
and as well all the fields let's back to the root so
9:00:03
이제 우리는 판매의 합계를 가지고 있습니다.
now we have the sum of sales and if execute this i'm
9:00:06
이제 우리는 윈도우 함수를 사용해야 합니다.
going to get one value so we are at the highest level of aggregations so
9:00:09
이름을 제거하겠습니다.
now we need to use the window function i'm just going to remove the
9:00:13
이것은 윈도우 함수입니다.
name and now we're going to tell sql this is a
9:00:16
10개의 행이 생성되었습니다.
window functions using over after the aggregations or the functions tells sql we are talking about window functions so let's just execute it like this and with that we got
9:00:26
각 행마다 동일한 값이 있습니다.
10 rows and that's because we have 10 orders and
9:00:29
모든 주문의 총 판매량입니다.
for each row we have exactly the same value so we have the total
9:00:32
SQL은 이것이 윈도우 함수임을 이해합니다.
sales of all orders for each row so as you can see
9:00:35
SQL은 모든 데이터를 한 행으로 그룹화하지 않아야 합니다.
sql understand this is a window function and
9:00:38
정확히 같은 행 수를 유지해야 합니다.
scale should not like group all the data in one row it
9:00:42
입력과 같은 행 수를 유지해야 합니다.
should keep exactly the same rows or same number of rows
9:00:45
제품별로 데이터를 나누어야 합니다.
like the input so with that we have the window function
9:00:48
또 다른 표현으로는 제품 ID입니다.
but we have to split the data by the products so now we can use the keyword partition by it's like the group by
9:00:54
그에 따라 총 판매량이 있습니다.
but another wording products id the same dimension so
9:00:57
제품 이름별로 총 판매량이 있습니다.
with that we have the total sales by
9:01:00
출력에서 여전히 같은 행 수를 가지고 있습니다.
products as a name so let's go and execute this
9:01:04
10개의 주문이 있습니다.
so now as you can see in the output we still have the same number of rows we
9:01:07
결과는 변경되었습니다.
have 10 orders we have 10 rows but the result
9:01:10
이제 같은 차원을 추가하겠습니다.
did change because now we are aggregating the data at the level of product id in order to understand the results we have to add more informations to our select so now let's add the same dimension it can be the product id
9:01:22
이 제품들은 항상 동일한 판매량을 가지고 있습니다.
I'm just going to add it at the front over here. So let's select. And as you can see, now it makes more sense.
9:01:28
이제 윈도우 함수의 마법이 시작됩니다.
We have those products and they have always the exact same sales and as well for the next product and so on.
9:01:35
이제 주문 ID와 같은 추가 정보가 필요합니다.
And now here comes the magic of the window function. We can add more information to our select statement without having any errors.
9:01:41
그래서 이제 우리는 주문 ID와 같은 추가 정보가 필요합니다.
So now we need additional information like the order ID.
9:01:45
그래서 우리는 여기로 가서 주문 ID를 말할 수 있습니다.
so we can go over here and say order id order
9:01:48
날짜, 어떤 유형의 열이든 선택에 추가할 수 있습니다.
date any type of column you can add it to your select
9:01:51
그리고 이제 실행해 보겠습니다. 보시다시피 이제 우리는
and let's go and execute so as you can see now we got
9:01:54
결과를 얻었습니다. 선택한 세 가지 차원이
the result even though that those three dimensions in the select
9:01:58
창 집계의 일부가 아니더라도
are not part of the window aggregation so
9:02:01
그로 인해 우리는 작업을 해결했습니다. 추가 정보가 있습니다.
with that we have solved the tasks we have additional informations we
9:02:05
주문 ID, 주문 날짜가 있으며, 각 제품의 총 판매량을 찾는 작업의 첫 번째 부분도 있습니다.
have the order id the order date and as well the first part of the task to find the total sales for each product so each of those values are the total sales
9:02:14
각 제품에 대한 총 판매량이 있으며, 이를 통해 우리는 작업을 해결했습니다.
for each product and with that we have solved the tasks
9:02:17
그리고 이것이 우리가 실제로 창 함수가 필요한 이유입니다.
and this is exactly why we need window functions in real
9:02:20
프로젝트는 정말 복잡해지며, 서로 다른 작업을 한 쿼리에서 수행하고 있습니다.
projects things get really complicated you are doing different
9:02:23
그래서 집계를 하고 다른 작업을 하며, 단순히
tasks in one query so you are doing aggregations you are
9:02:26
집계에 집중하는 것으로는 충분하지 않습니다. 항상 추가 정보를 추가해야 합니다.
doing some other stuff so just focusing on
9:02:30
쿼리에 정보를 추가해야 하며, 보시다시피 우리는 그룹을 사용합니다.
the aggregations is not going to be enough you have always to add additional
9:02:33
단순한 분석을 수행하지만 상황이 복잡해지면
information to your query so as you can see we use group i
9:02:36
분석에서는 창 함수를 사용하여
to do simple analyzes but as things get complicated
9:02:39
집계를 보여주고 추가 정보를 추가합니다.
in the analytics we use the window functions in
9:02:42
보시다시피 우리는 그룹을 사용하여 단순한 분석을 수행하지만, 상황이 복잡해지면 분석에서는 창 함수를 사용하여 집계를 보여주고 추가 정보를 추가합니다.
order to show the aggregations and as well add additional informations
9:02:45
좋습니다, 여러분. 이제 SQL 창 함수의 구문으로 들어가 보겠습니다. 모든 부분을 다룰 것이며, 이를 사용하는 방법을 이해할 수 있도록 하겠습니다.
so as you can see we use group i to do simple analyzes but as things get complicated in the analytics we use the window functions in order to show the aggregations and as well add additional informations
9:03:01
좋습니다, 여러분. 이제 SQL 창 함수의 구문으로 들어가 보겠습니다. 모든 부분을 다룰 것이며, 이를 사용하는 방법을 이해할 수 있도록 하겠습니다.
all right everyone so now we're gonna go and dive into the syntax of the sql window functions we're gonna cover everything each part of the syntax for you to understand how to use them
9:03:11
좋습니다. 먼저 기본 구성 요소를 이해하는 것부터 시작하겠습니다.
so let's go all right so let's start first by understanding the basic components
9:03:14
각 창 구문의 기본 부분이 있습니다.
or the basic parts of each window syntax mainly
9:03:18
우리는 두 부분이 있습니다. 첫 번째 부분은 창 함수가 될 것입니다.
we have two parts the first part gonna be the window function we
9:03:22
평균과 같은 것이며, 두 번째 주요
have like some average and so on the second main
9:03:25
부분은 오버 클로즈가 될 것이며, 오버 클로즈 내부에는
part gonna be the over close and inside the over close
9:03:28
우리는 세 가지 다른 부분이 있습니다. 첫 번째는
we have three different parts the first one gonna be the
9:03:31
파티션 절, 두 번째는 정렬 절, 그리고
partition clause the second order clause and
9:03:34
마지막으로 프레임 절이 있으며, 이 모든 것이 구성 요소입니다.
the last one we have the frame clause and those are all components
9:03:37
그 창 함수 안에서 사용할 수 있는 것들입니다. 그래서 두
that you can can use inside that window function so two
9:03:40
주요 부분은 창 함수와 오버 절입니다. 자세히 살펴보겠습니다.
main parts window function and the offer close and inside
9:03:44
예를 들어, 다음과 같은 창 함수가 있습니다.
the over we have partition order and frame let's go more in details
9:03:47
여기에서 많은 것들이 진행되고 있음을 알 수 있습니다. 이해할 것입니다.
so for example we have the following window function so
9:03:50
단계별로, 구성 요소별로 시작하겠습니다.
you can see we have a lot of stuff going on here we're gonna understand
9:03:53
왼쪽에서 첫 번째부터 시작하겠습니다. 여기에서 무엇이 있습니까?
them step by step component by component let's start
9:03:56
함수 창 함수입니다. 창 함수란 무엇입니까? 여기에서 평균이 있습니다. SQL의 다른 함수와 마찬가지로 사용할 수 있습니다.
from the left from the first one so what do we have over here we have
9:03:59
창 위에서 계산을 수행하기 위해 사용됩니다. 첫 번째로
a function window function so what is a window function like here we have the average it's like any other function in sql you can use it in order to do
9:04:07
창에서 해야 할 일은
calculations on top of the window so the first thing
9:04:11
창의 기능을 정의하는 것입니다. 이전에 배운 것처럼 긴
to do or to define in a window is to define the
9:04:14
SQL에서 사용할 수 있는 많은 창 함수 목록이 있습니다.
function of the window and as we learned before we have a long
9:04:17
우리는 이를 세 그룹으로 나눕니다. 첫 번째는
list of many window functions available in sql and
9:04:20
집계 함수입니다. 우리는 카운트, 합계, 평균, 최대값을 가지고 있습니다.
we group them into three groups the first one we have the
9:04:23
모든 이러한 함수는 그룹화에도 사용할 수 있습니다. 이는 집계에 사용됩니다. 두 번째 그룹은 순위 함수입니다.
aggregate functions so we have the count sum average maximum
9:04:27
우리는 행 번호, 순위 및 타일 등을 가지고 있습니다. 이 그룹을 사용하여 데이터에 순위를 매길 수 있습니다.
all those functions we have them as well for the group by so those are used for the aggregations the second group of functions we have the ranking functions.
9:04:37
마지막 그룹은 값을 부르거나 때때로 분석 함수라고 부릅니다.
So we have the row number, rank and tile and so on. So we can use those groups in order to give a rank for our data.
9:04:43
여기에는 리드, 레그, 첫 번째 값 및 마지막 값과 같은 매우 중요한 함수가 있습니다.
The last group we call it value or sometimes analytics functions.
9:04:47
특정 값에 접근하기 위해 사용할 수 있습니다. 물론 우리는 모든 것을 하나씩 배우고, 개념을 이해하고, 몇 가지 예를 들어 사용할 때를 이해할 것입니다.
So here we have very important functions like the lead, lag, first value and the last value in order to access a specific value.
9:04:54
좋습니다. 이제 계속 진행하여 창 구문 다른 부분을 이해해 보겠습니다.
And of course, we're going to go and learn all of them one by one, understanding the concepts, some examples and as well for you to understand when to use them for data analyzers.
9:05:03
좋습니다. 이제 계속 진행하여 창 구문 다른 부분을 이해해 보겠습니다.
All right, so now let's keep moving, understanding the other parts of the window syntax.
9:05:07
이제 평균 함수 안에 'sales'라는 필드 이름 또는 열 이름이 있습니다. 이것은 함수 표현식이라고 합니다.
Now, inside the function average, we have here a field name or column name called sales. This called a function expression.
9:05:14
값, 매개변수 또는 함수에 전달할 수 있는 인수와 같습니다. 여기에서 여러 가지를 사용할 수 있습니다.
It's like a value, a parameter, or argument that we can pass it to the function. And here we can use multiple different stuff.
9:05:21
예를 들어, 함수에 따라 다릅니다. 그래서 여기서는
For example, depend on the function, of course. so here it could be
9:05:24
순위에서 사용을 허용하지 않기 때문에 비어 있을 수 있습니다.
empty like here in the ranking it doesn't allow to use an
9:05:27
항상 비어 있어야 하거나 우리는
expression so it should be always empty or we
9:05:31
예제에서 사용한 것처럼 열을 사용할 수 있습니다.
can use a column like in the example we use the sales so
9:05:34
우리는 열 이름을 인수나 표현식으로 사용합니다.
we use the column name as an argument or an expression
9:05:37
평균을 찾기 위해 판매의 평균을 찾고 있습니다.
for the average we are finding the average of sales
9:05:40
숫자만 사용할 수 있으며, 예를 들어 리드에서는 판매 숫자 등을 가질 수 있습니다.
or we could use a number so here in the intile we
9:05:43
걱정하지 마세요. 제가 설명할 것입니다. 여기에는 여러 가지가 있습니다.
are allowed only to use numbers or we could have multiple stuff for example in the lead we can have sales the numbers and so on so things get complicated
9:05:52
또는 전체 조건 논리를 가질 수 있습니다.
don't worry about it i'm going to explain that so here we have multiple stuff
9:05:56
예를 들어, 여기에서 우리는 케이스 승리를 가지고 있습니다.
or we can have a whole conditional logic
9:05:59
합계 안에서 전체를 다루고 있습니다.
so for example here we have the case win so on
9:06:02
여기서는 합계를 위한 표현식이라고 합니다.
inside the sum so the whole thing over
9:06:05
여기서 우리는 복잡한 논리를 구축할 수 있으며, 이의 출력은
here called an expression for the sum so as you
9:06:08
논리는 함수 합계에 전달될 수 있습니다. 즉, 함수의 표현식으로 다양한 것을 사용할 수 있습니다.
can see we can build here a complex logic and the output of this
9:06:11
논리는 함수 합계에 전달될 수 있습니다. 즉, 함수의 표현식으로 다양한 것을 사용할 수 있습니다.
logic can be passed to the function sum so that means as an expression for the function we can use different stuff of course depends whether the function allows it or not
9:06:20
좋습니다. 이제 함수의 표현식에서 허용되는 데이터 유형을 이해하기 위해 간단히 살펴보겠습니다.
All right, so now let's have a quick overview in order to understand which data types are allowed in the expressions for those functions.
9:06:27
집계 함수를 살펴보겠습니다. 카운트 함수는 모든 데이터 유형을 허용하지만, 합계, 평균, 최소, 최대는 숫자 데이터 유형만 허용합니다.
Let's see the aggregate functions. As you can see, the count function accept any data type, but the others like the sum, average, min, max, they allow only numerical data types.
9:06:38
좋습니다. 이제 랭크 함수로 넘어가겠습니다. 표현식은 매우 간단합니다. 비어 있어야 합니다.
All right, so now let's move to the rank function. The expressions, it's pretty easy. It should be empty.
9:06:43
이 함수들 안에 인수나 다른 것을 허용하지 않습니다.
It doesn't allow any argument or anything inside those functions.
9:06:46
보시다시피, 모두 비어 있지만, 숫자 값을 허용하는 것은 끝 타일 하나뿐입니다.
So as you can see, all of them are empty, but only one that accepts numerical values, which is the end tile.
9:06:52
숫자 값을 정의해야 합니다. 이제 마지막 유형으로 넘어가겠습니다. 우리는 값 함수를 가지고 있습니다.
You have to define a numeric value. And now moving on to the last type, we have the value functions.
9:06:57
그들은 표현식 안에 모든 데이터 유형을 허용합니다. 각 함수는 고유한 사양이 있으며, 표현식에서 사용하는 데이터 유형에 주의해야 합니다.
They accept any data types inside the expressions. So as you can see, each function has its own specifications and you have to be careful which data type you are using in the expressions.
9:07:08
좋습니다. 이제 다음으로 넘어가겠습니다. 우리는 윈도우 구문에서 매우 중요한 부분이 있습니다. 지금까지 무엇이 있습니까?
OK, so now let's keep moving to the next one. We have a very important part in the window syntax. So so far, what do we have?
9:07:14
우리는 함수가 있고, 표현식이 있습니다. 일반적인 것입니다. 우리는 그룹별로 사용한 적이 있습니다.
We have a function, we have an expression. It's like usual stuff. We have done that before using the group by.
9:07:20
이제 SQL에 윈도우 함수로 작업하고 있다고 알려야 합니다. 일반적인 것이 아닙니다.
Now we have to tell SQL that we are dealing with the window function. It's not a normal one.
9:07:25
그렇게 하려면 키워드 over를 지정해야 합니다.
In order to do that, we have to specify the keyword over.
9:07:29
구문에서 두 번째 주요 부분은 over 절입니다. 이를 사용하여 창을 정의합니다.
So the second main part in the syntax is the over clause. And we use it in order to define a window.
9:07:35
그 안에서 partition by, order by, frame과 같은 여러 요소를 정의할 수 있습니다. 하지만 모든 것은 선택 사항입니다.
And inside it, we can define multiple stuff like the partition by, the order by, the frame. But all those stuff are optional.
9:07:42
그것을 건너뛰고 비워둘 수 있습니다. over의 주요 작업은 SQL에 우리가 여기서 창 함수와 관련이 있음을 알리는 것입니다.
We can skip it and leave it empty. So the main task of the over it tells first SQL we are dealing with the window function here and as well you can use it in order to define a window of your data.
9:07:54
이제 over 절 내부의 모든 것을 다룰 것입니다. 첫 번째는 partition by입니다.
So now we're going to go and cover everything inside the over clause and we're going to start with the first one the partition by.
9:08:04
이제 over 절 내부의 창을 정의하는 방법을 배울 것입니다. 우리가 정의할 수 있는 첫 번째 부분은 partition by입니다.
All right so now we're going to learn how to define a window inside the over clause. The first part that we can define is the partition pie.
9:08:11
예를 들어 여기서 우리는 카테고리별로 partition을 정의해야 합니다.
so for example here we have partition by category we have to define
9:08:15
그 차원은 group by와 매우 유사합니다.
that dimension it's very similar to the group by another wording
9:08:18
첫 번째 부분은 partition 절이 될 것입니다.
so the first part is going to be the partition clause what
9:08:21
그것은 전체 데이터 세트를 나누는 것입니다.
it's going to do it's going to divide the entire data sets
9:08:25
그룹으로 나누거나 창 파티션이라고 부를 수 있습니다.
into groups or you can call it windows partitions
9:08:29
여기서 SQL에 우리의 데이터를 나누는 방법을 알려줍니다.
so here we tell sql how to divide our
9:08:32
여기에는 두 가지 옵션이 있습니다. 아무것도 사용하지 않으면 비어 있습니다.
data and here we have two options let me just show you so if we don't use anything so we have it empty you see over and partition by is not used
9:08:41
무슨 일이 일어날 수 있는지 SQL이 전체 데이터를 사용할 것입니다.
what can happen is ql gonna use the entire
9:08:45
계산을 위해 전체 데이터를 하나로 계산할 수 있습니다.
data in order to do the calculations so the
9:08:48
우리는 SQL에 아무것도 나누지 말고 그대로 두라고 말하고 있습니다.
whole data the entire data can be counted as one
9:08:51
그대로 두는 두 번째 옵션은 데이터를 partition by로 나누는 것입니다.
window so we are telling sql don't divide anything leave
9:08:54
우리는 창을 정의합니다.
it as it is the second option that we have is to divide
9:08:57
예를 들어 제품별로 partition을 이렇게 정의합니다.
the data by partition pi so we define the window
9:09:01
SQL은 전체 데이터를 서로 다른 창으로 나눌 것입니다.
like this partition by products for example so sql
9:09:04
예를 들어 여기 두 개의 창이 있습니다.
gonna go and divide the entire data into different windows
9:09:07
이번에는 계산이 전체 데이터에 적용되지 않습니다.
for example here two windows and here this time the calculation
9:09:10
이번에는 서로 다른 창에 적용될 것입니다.
the sum of sales will not apply on the entire data
9:09:14
개별적으로 창의 합계를 찾을 것입니다.
set this time it's going to be applied on the different
9:09:17
판매의 합계를 첫 번째 창에서 전체 판매와 별도로 찾을 것입니다.
windows individually so we're going to find the sum
9:09:20
창 1의 판매 합계
of sales for window one separately from the total sales
9:09:23
창 2의 판매 합계
of window two all right so now we have this very simple example we
9:09:27
여기에는 세 가지 필드가 있습니다
have here three fields the month product sales they are really easy informations and now we have the following sql
9:09:33
윈도우 함수로 판매 합계를 구합니다
window function so we have sum of sales and
9:09:37
오버 절에서는 아무것도 사용하지 않습니다
inside the overclose we are not using anything so
9:09:40
파티션을 사용하지 않으니
we are not using partition by so how is kiel
9:09:43
데이터 세트를 나누지 않습니다
gonna define the window now is kiel gonna say okay i don't have
9:09:46
하나의 윈도우입니다
to divide anything the entire data set is
9:09:50
전체 데이터는 하나의 윈도우입니다
one window so sql gonna go over here and say
9:09:53
전체 데이터가 집계됩니다
the whole thing is one window so there is no partitions there is nothing we have only one
9:09:59
파티션을 사용하지 않으면
window so the entire data going to be aggregated so this
9:10:02
오버 절이 비어있으면
is what happens if you don't use partition by and you leave
9:10:05
하나의 윈도우가 됩니다
the over clause empty the entire data is one window
9:10:08
다음 예제로 넘어갑니다
all right so now let's move to the next example we don't want to have only one window we would like to have multiple windows so we have to divide the data by something so in the over clause we're going to define the window like the following
9:10:20
파티션으로 월을 나눕니다
partition by month so it's not empty we
9:10:24
이 열의 값이 나뉩니다
are now dividing the data by the filled month so
9:10:27
여기 두 개의 월이 있습니다
the values inside this column gonna divide
9:10:30
1월과 2월입니다
the data sets so here we have two months january
9:10:33
데이터를 두 세트로 나눕니다
and february so what can i do sql gonna go and
9:10:37
각 윈도우에서 계산됩니다
divide the data into two sets the first window gonna be this one of january so we have the first window gonna make it smaller and the second window gonna be the February.
9:10:48
1월과 2월로 나눕니다
So it's going to be two windows inside our data and the calculation going to be happening on each window separately.
9:10:54
파티션의 옵션을 살펴봅니다
So here as you can see we are using the month in order to divide our data sets into two windows one window for the January and another window for the February.
9:11:04
모든 행의 총 판매
So now let's have a quick overview about the options that we have with the partition by the first option as we learned we can just skip it so without partition by for example here
9:11:13
SQL 내부에서 두 번째 옵션
total sales across all rows and here we don't define anything
9:11:16
하나의 필드를 사용합니다
inside the sql the second option we can use
9:11:19
하나의 필드 하나의 열 예를 들어 파티션
one field one column for example partition
9:11:23
제품별로 하나의 차원을 사용하고 있지만
by products so we are using one dimension but
9:11:26
여러 열을 사용할 수 있습니다.
we can go and mix stuff we can use multiple columns
9:11:29
또는 예를 들어 여기서 파티션으로 여러 차원을 사용할 수 있습니다.
or multiple dimensions in the partition by for example here partition
9:11:32
제품 및 주문 상태별로 여기서 파티션으로
by product and order status so here with the partition by
9:11:35
우리 데이터를 나누기 위해 사용할 수 있는 차원 목록을 정의할 수 있습니다. 이 예에서는 제품과 주문 상태의 조합에 대한 총 매출을 찾으라고 말하고 있습니다.
we can define a list of dimensions that could be used in order to divide our data so in this example we We are saying find the total sales for each combination of products and order status.
9:11:47
파티션으로 작업하는 다양한 옵션입니다. 이제 모든 함수에 대한 개요를 다시 살펴보겠습니다.
So those are the different options on how to work with the partition by. So now let's have this overview again for all functions.
9:11:54
모든 함수에 대한 파티션은 선택 사항입니다.
The partition by for all those functions is optional.
9:11:56
모든 함수에서 파티션을 사용하지 않으면 오류가 발생하지 않습니다.
So if you don't use the partition by in all those functions, you will not get any errors.
9:12:02
이제 SQL로 돌아가서 이 절을 사용하여 연습을 시작하겠습니다. 자, 이제 다음 작업이 있습니다.
So now let's go back to SQL in order to start practicing with this clause. Okay, so now we have the following task.
9:12:07
모든 주문의 총 매출을 찾으세요. 그리고 우리는 제공해야 합니다.
Find the total sales across all orders. and we have to provide
9:12:11
주문 ID 및 주문과 같은 추가 정보를 제공해야 합니다.
additional informations like the order id and the order
9:12:14
날짜이므로 단계별로 해결해 보겠습니다.
date so let's go and solve it step by step first
9:12:17
상세 정보를 제공하고 싶으므로 주문 ID를 선택하겠습니다.
i would like to provide the details so i'm going to select the order id
9:12:20
및 주문 날짜를 선택하겠습니다.
and the order dates from the
9:12:23
판매 주문 테이블에서 다음으로
table sales orders and next we're going to
9:12:26
집계 작업을 수행해야 하므로 모든 주문의 총 매출을 찾아야 합니다.
work with the aggregations so we need to find the total sales across
9:12:29
여기서 세부 정보와 집계가 있으므로 그룹 바이를 사용할 수 없고 윈도우 함수를 사용해야 합니다.
all orders again since we have here details and aggregations we cannot use group by we have to use the window function so we're going to go
9:12:37
매출에 대한 합계 함수를 사용해야 합니다.
use the function sum for sales and
9:12:40
이제 SQL에 윈도우로 작업하고 있다고 알려야 합니다.
now we have to tell sql we are working with window
9:12:43
그래서 우리는 오버 절을 사용할 것입니다.
functions that's why we're going to use the over clause and now the
9:12:46
다음 단계는 윈도우를 정의하는 것에 대해 생각해야 합니다.
next step we have to think about defining the window so
9:12:50
작업을 확인해 보겠습니다. 모든 주문의 총 매출이라고 합니다.
let's check the task it says total sales across all
9:12:53
따라서 우리는 파티션을 나누거나
orders so that means we don't have to partition or
9:12:56
데이터 세트를 조각이나 파티션으로 나눌 필요가 없습니다.
divide the data sets into like chunks or partitions
9:12:59
우리는 데이터를 그대로 두어야 합니다. 전체 데이터가 하나의 창처럼 되어야 하므로 내부에서 파티션 pi를 사용하지 않습니다.
we have to leave it as it is like the whole data going to be one window and that's why we don't use partition pi inside
9:13:06
정의는 비워 두고 이제 이름을 지정합시다.
the definition we're going to leave it empty let's go now and give it a name
9:13:09
총 판매량이 될 것이며, 이제 실행해 봅시다.
it's going to be the total sales let's go and execute this
9:13:12
이제 결과를 추가합시다. 모든 주문이 있습니다.
and now add the results as you can see we have all the orders all
9:13:16
세부 사항과 함께 모든 주문의 총 판매량이 있습니다.
the details and as well we have the total sales across
9:13:19
모든 주문으로, 우리는 작업을 해결했습니다.
all orders so with that we have solved the tasks we
9:13:22
총 판매량과 주문에 대한 세부 사항도 있습니다.
have the total sales and as well some details about the order all
9:13:25
자, 이제 다음 작업으로 넘어갑시다. 매우 유사할 것입니다.
right so now let's move to the next task it's going to be very similar so
9:13:29
각 제품의 총 판매량을 찾아야 합니다.
it says find the total sales for each product and
9:13:32
주문 ID와 주문 날짜와 같은 추가 정보를 제공해야 합니다.
we have to provide additional informations like the order id and the order date
9:13:35
이번에는 전체 데이터를 나누어야 합니다.
so it's be very similar task but this time
9:13:38
창을 만들 것이며, 제품별로 나누게 됩니다.
we have to divide the entire data into
9:13:42
각 제품의 총 판매량을 말하고 있습니다.
windows and that's going to be by the product since we
9:13:45
데이터를 나누어야 하며, 정의할 것입니다.
are saying total sales for each product so this time
9:13:48
이렇게 파티션을 정의합니다. 우리는 사용할 수 있습니다.
we have to go and divide the data so we're going to define
9:13:51
차원 제품 ID로, 이제 실행해 봅시다.
the window like this partition by and we can use the
9:13:55
이제 총 판매량에서 전체 데이터의 총 판매량이 없습니다.
dimension product id let's go and execute this so now you can see in the total sales we don't have
9:14:01
더 이상 전체 데이터의 총 판매량이 없습니다.
anymore the total sales of the whole data but they are
9:14:04
결과를 이해하기 위해 제품 ID를 포함합시다.
divided but in order to understand the results let's go and
9:14:07
제품 ID를 포함하고 실행합니다.
include the product id in the results so
9:14:10
이제 결과를 보면 데이터가 네 개의 창으로 나뉘어 있습니다.
product id and execute so now by looking to the results
9:14:13
그것들을 봅시다. 제품 ID별로 나뉘어 있습니다.
you can see that the data is divided into four windows
9:14:17
이 차원이 파티션을 제어하게 됩니다. 첫 번째 창은 제품 ID 101입니다.
let's see them it's going to be by the product id so
9:14:20
다음 창은 102, 세 번째는 104, 마지막 창은 105로 단 한 행입니다.
this dimension going to be controlling the partition so the first window going to be the product id 101 so we have the total sales for this product 140 and the next
9:14:29
마지막 창은 102, 세 번째는 104, 마지막 창은 105로 총 판매량은 60입니다.
window gonna be 102 the third one 104 and the last window it's gonna be only one row the 105 and the total sales of 60.
9:14:38
그래서 우리는 이로써 작업을 해결했습니다. 우리는 총 판매량을 가지고 있습니다.
so with that we have solved the task we have the total sales for
9:14:42
각 제품에 대한 세부 정보도 가지고 있습니다. 이제 저는
each product and as well we have some details now i would like to
9:14:45
창 함수의 동적 기능을 보여드리겠습니다. 우리는
show you the dynamic of the window function we can add
9:14:48
여기서 전체 정의를 제거함으로써 서로 다른 수준에서 창 함수를 사용할 수 있습니다.
multiple aggregations on multiple levels let me show you what i mean let's say we stay with the the same example but we're gonna find the total sales across all orders and as well the total sales for each product.
9:15:01
여기서 우리는 첫 번째 작업에 대한 전체 데이터의 총 판매량을 가지고 있습니다.
So what we can do, we can do the window functions on different levels by, for example, here removing the whole definition.
9:15:07
다음은 제품 ID로 나누어진 총 판매량이 될 것입니다. 제품별로 이름을 바꿉니다.
So here we have the total sales for the entire data for the first task.
9:15:11
가서 이것을 실행해 보겠습니다. 이제, 음, 판매량도 추가하겠습니다.
And the next one is going to be the total sales, but divided by the product ID. Let's rename it by products.
9:15:19
가서 판매량을 추가하고 다시 실행해 보겠습니다. 이제 결과를 보면, 우리는 세 번의 판매량을 가지고 있지만, 서로 다른 세분화로 있습니다.
Let's go and execute this. And now, you know what, I'm going to go and add the sales as well, just to explain the flexibility of the window function.
9:15:26
첫 번째 판매량은 집계 없이 판매량 자체로, 판매의 가장 높은 세부 수준입니다.
So let's go add the sales and execute it again. And now by looking to the results, you can see we have the sales of formations three times, but with different granularities.
9:15:36
각 주문에 대한 판매량을 가질 것입니다. 다음은 창 함수로 총 판매량입니다.
The first sales, the sales itself without any aggregations, it is the highest level of details of the sales.
9:15:42
그래서 우리는 모든 주문의 총 판매량을 가지고 있습니다.
And we're going to have the sales for each order. The next one, the total sales with the window function, here we have the highest level of aggregation.
9:15:49
마지막으로 제품별 총 판매량이 있습니다. 이것은 중간 정도입니다.
so we have the total sales of all orders and
9:15:52
우리는 창에서 집계하고 있으며, 창은
the last one the total sales by product it's something like in the middle we
9:15:55
제품 ID입니다. 보시다시피 우리는 서로 다른 세분화가 있습니다.
are aggregating on a window and the window can be
9:15:58
집계의 세분화이며, 이것이 바로
the product id so as you can see we have different granularities
9:16:02
우리가 창 함수로 할 수 있는 유연성입니다.
of the aggregations and this is exactly the flexibility that
9:16:05
하나의 쿼리에서 모든 것을 할 수 있습니다. 자, 이제 계속 진행하여
we have with the window function we can do all those stuff
9:16:08
우리 작업에 추가하겠습니다. 각
in one query okay so now let's keep moving and adding stuff to
9:16:11
제품 조합과 다른 상태에 대한 총 판매량을 찾는 것입니다.
our task it's gonna say find the total sales for each
9:16:14
이번에는 데이터를 제품뿐만 아니라
combination of the products and the other status so
9:16:18
주문 상태라는 또 다른 차원으로 나누어야 합니다.
this time we have to divide the data not only by the product but as
9:16:21
이제 우리가 어떻게 할 수 있는지 봅시다. 주문 상태 차원을 보여주고
well with another dimension the order status so
9:16:25
결과를 확인한 후, 다음과 같은 것을 추가할 것입니다.
now let's see how we can do that i'm gonna just show the dimension order status and the results and we're gonna add the following thing so some
9:16:35
판매량을 창 함수로 사용하여
sales over since it's a window function and
9:16:38
이제 창 파티션을 정의해 보겠습니다.
let's go now and define the window partition by so
9:16:41
다시 제품 ID가 있지만 이 차원만 있는 것은 아닙니다.
we have again the product id but not only this dimension as
9:16:45
주문 상태도 있고, 이제 가보겠습니다.
well the order status and let's go and
9:16:48
제품별 판매라고 부르겠습니다.
call it sales by products and
9:16:51
상태를 바꾸고 싶습니다. 좋아요, 이제 실행해 보겠습니다.
status let me just rename those stuff okay so
9:16:55
이번에는 데이터를 두 개의 차원으로 나누고 있습니다.
let's go and execute all right so now let's check the results it is the last aggregation over here and as you can see here the aggregation has different granularities as the previous one and we have more details
9:17:06
첫 번째 창은 제품 ID와 주문 상태가 될 것입니다.
this time we are splitting the data by two dimensions so
9:17:10
이 두 행만 있을 것입니다. 주문 ID 101과 주문 상태가 배송되었습니다.
the first window gonna be the product id with the order status
9:17:13
다음 창은 동일한 제품이지만 다른 상태가 될 것입니다.
it's gonna be only those two rows so we have the order id 101 and the order status delivered so the total sales of this gonna be 10 plus 20 and we're gonna have 30.
9:17:24
다음 제품과 주문 상태는 102가 될 것입니다.
the next window gonna be the same product but with different status so it's gonna be the 101 shipped and we're gonna go and summarize those two values and we're gonna have 110.
9:17:35
102는 한 번만 있습니다.
the next product and order status gonna be the 102 and
9:17:38
102 배송은 한 번만 있습니다.
we have it only once so 102 delivered it's only once so
9:17:42
다음 파티션이나 창은 같은 값이 될 것입니다.
it's gonna be the same value the next partition or window
9:17:45
102는 두 행이 될 것입니다.
it's gonna be two rows 102 with the shift
9:17:48
그 두 가지는 60이 될 것입니다.
it's gonna be those two things 60
9:17:51
15를 더하면 75가 됩니다.
plus 15 we're gonna get 75 so as you can
9:17:54
여기서 제품 ID와 주문 상태가
see here the product id and the order status they
9:17:57
얼마나 많은 창을 얻을지 제어하고 있습니다.
are controlling how many windows we're gonna get so we get here around
9:18:01
좋아요, 이것이 오버 클로즈 내에서 창 정의의 첫 번째 부분이었습니다.
like six windows with the product id we got only four windows and without using anything inside the over clause we will get only one window so this is how the partition by works
9:18:16
다음 부분으로 넘어가겠습니다. 예를 들어 주문 날짜로 정렬할 수 있습니다.
all right so that was the first part of the window definition within the over close let's move to the next part we have the order by for example we can use order by order date it's just a field
9:18:26
주문 절은 데이터를 정렬하는 데 매우 중요합니다.
so the order clause is very important in order to sort your data
9:18:29
창 내에서 주문은 매우 중요합니다.
within a window so the order by is very important as
9:18:32
많은 함수에 대해, 개요를 확인하면
well for many functions so by just checking the overview
9:18:35
여기서 집계 함수에 대해 선택 사항입니다.
over here for the aggregate functions it is optional so you
9:18:39
순위 함수와 값 함수는 필수입니다.
could just leave it or add it but for the rank function and
9:18:42
데이터를 정렬하지 않고는 의미가 없습니다.
as well for the value functions they are a must so if you want to use those functions you must use the order clause because it makes no sense for example if you are ranking the data
9:18:53
데이터를 먼저 정렬하지 않고
without sorting your data first okay guys so now back to
9:18:56
우리의 아주 간단한 예제로 돌아가서
our very simple example and we have the following query so the function this
9:18:59
시간이 순위를 매기는 것이 될 것이고
time gonna be rank so we have to rank the data and the definition
9:19:03
창의 정의는 월별로 나누는 것입니다.
of the window gonna be partition by month so that means
9:19:06
그래서 우리는 데이터를 월별로 나눕니다.
we divide the data by the months so we have it over
9:19:09
여기서 두 번째 부분은 정렬할 것입니다.
here and then the second part gonna be order by
9:19:12
판매량 내림차순으로 정렬해야 합니다.
sales descending so we have to sort each window
9:19:15
내림차순으로 정렬한다는 것은 가장 높은 값부터 시작한다는 뜻입니다.
by descending order that means we start with the highest value and
9:19:19
가장 낮은 값으로 끝납니다. 자, 이제 isql이
we end up by the lowest value so let's see how isql
9:19:22
이것을 실행할 것입니다. 먼저 월별로 나누겠습니다.
gonna go and execute this so first partition by month
9:19:25
그래서 데이터가 두 개의 파티션으로 나뉘게 됩니다.
so it's going to divide the data into two partitions because we
9:19:28
월별로 두 개의 값이 있으므로
have two values by the month so let's see how
9:19:31
1월에 대한 하나의 창이 될 것입니다.
this is going to look like so one window for january
9:19:34
그리고 2월에 대한 또 다른 창이 될 것입니다.
and another window for february all right
9:19:37
이제 isql이 두 번째 부분으로 가서 판매량 내림차순으로 정렬을 실행합니다.
so now isql gonna go to the second part and execute order by sales descending so what can happen isql gonna go for each window separately and start sorting the data from the highest to to the lowest without checking the other window.
9:19:50
그 세 값 중에서 가장 높은 값은 이것입니다.
So in those three values, the highest one is this one. So it's going to be on top. Let me just sort it. This is going to be the lowest.
9:19:56
당신은 중간에 있을 것입니다. SQL이 정렬할 것입니다.
You're going to be in the middle. So SQL going to sort.
9:20:00
이 창을 다음 창과 별도로
this window separately from the next one and then once it's
9:20:03
정렬한 후에 두 번째 창으로 넘어갑니다.
done it's gonna go to the second one so the highest value gonna be
9:20:06
가장 높은 값이 될 것입니다.
this one you are the lowest let me
9:20:09
당신은 가장 낮습니다. 이렇게 해보겠습니다.
just do it like this so SQL gonna sort it like
9:20:12
SQL이 이렇게 정렬할 것입니다.
this the highest one is 70 the next one is 40
9:20:15
가장 높은 값은 70이고, 다음 값은 40입니다.
and the last one is five so with that SQL done with
9:20:18
마지막 값은 5입니다. 그래서 SQL은
the definition of the window so it's splitted by the
9:20:21
창의 정의는 월별로 나뉘어져 있습니다.
month and each window is sorted by the sales the next step is gonna go and rank those values so it's really simple in the
9:20:29
출력 결과는 데이터를 이렇게 정렬할 것입니다.
outputs it's gonna rank the data like this so the
9:20:32
첫 번째 값은 이 값이 될 것이고, 두 번째는 두, 세 번째는 세가 될 것입니다.
first one gonna be this value the next one gonna be two and the third one gonna be three so as you can see it's great sorting only this window and
9:20:40
두 번째 창에 대해 같은 작업을 반복할 것입니다.
it's gonna go and repeat the same stuff for the second
9:20:43
각 순위는 서로 별개입니다.
window so each rank is separately from the others so as you can
9:20:46
판매량에 따라 각 주문을 순위 매기기입니다.
see it's very simple this is how sql executes partition by together with the order by for the rank function all right so now let's have a quick task for the order by it says
9:20:55
최고에서 최저로, 추가 정보를 제공해야 합니다.
rank each order based on their sales from the highest
9:20:58
주문 ID와 주문 날짜와 같은 정보입니다.
to the lowest and we have to provide additional informations
9:21:01
기본적인 정보인 주문 ID, 주문 날짜가 있습니다.
like order id and order date so let's see how we can write the query
9:21:04
판매량을 포함하여 데이터를 순위 매길 것입니다.
so we have the basic stuff order id order date and
9:21:07
함수 rank를 사용할 수 있습니다.
the sales and now we're going to go and rank the data using window
9:21:11
이것은 윈도우 함수이며, 윈도우 정의를 제공해야 합니다.
function so we can use the function rank and
9:21:14
작업을 확인해보면 데이터를 나눌 필요가 없습니다.
then we're going to tell sql this is a window function and inside it we have now to provide the definition of the window so now
9:21:21
partition by를 사용할 필요가 없고, rank만 사용하면 됩니다.
checking the task you can see that we don't have to divide the data
9:21:24
rank를 사용할 때는 order by도 반드시 사용해야 합니다.
so we don't have to use partition by we have just to use rank
9:21:27
order by를 사용할 것이고, 필드는
and with rank we have to use the order by it is must
9:21:31
판매량을 기준으로 최고에서 최저로 정렬할 것입니다.
so we're going to use order by the field going to be
9:21:34
rank sales라고 부르고 실행해보겠습니다.
the sales and from the highest to the lowest so
9:21:37
결과는 최고에서 최저로 정렬될 것입니다.
let's just call it rank sales and let's go and execute this and as you can see our results going to be sorted from the highest to the lowest so you can see the sales 90 at the top and the lowest going to be the 10
9:21:48
최고 순위는 1, 최저 순위는 10이 될 것입니다.
and as well we have a rank so for the top rank it's going to be one and the lowest rank going to be 10.
9:21:53
SQL에서 순위를 빠르게 생성했습니다.
so as you can see we just quickly create a rank in sql
9:21:56
전체 과정은 매우 간단합니다.
it's very simple the whole thing is one window
9:22:00
partition을 사용하지 않기 때문에
since we are not using partition pi and of course if
9:22:03
오름차순으로 정렬하고 싶다면
you want to have ascending so from the lowest to the highest
9:22:06
선택적으로 제거할 수 있습니다.
you can just remove it because optionally gonna be ascending
9:22:09
쿼리를 실행해보겠습니다.
so let's go and execute the query so now we can see
9:22:12
주문이 정렬되어 있으므로 가장 낮은 것부터 시작합니다.
the orders are sorted the way around so we start with the lowest
9:22:16
그리고 가장 높은 것으로 끝나며, 물론 여기서도 같은 결과를 얻을 수 있습니다.
and end up with the highest and of course you're gonna get the same results if you go
9:22:19
여기서 오름차순을 추가하면
over here and add ascending so if
9:22:22
실행하면 정확히 같은 결과를 얻는 것을 볼 수 있습니다.
we execute you see we got exactly the same results so
9:22:25
이것이 창 정의 내에서 정렬을 사용하는 방법입니다.
this is how you use the order by inside the window definition
9:22:28
좋아요
okay
9:22:33
자, 이제 두 번째 부분의 윈도우 정의를 다뤘습니다.
guys so with that you have covered the second part of the window definition now
9:22:36
마지막 부분, 가장 고급 부분으로 넘어가겠습니다.
we're gonna go to the last part to the most advanced part of window
9:22:39
다음과 같은 내용이 있습니다. 우리는 행이 있습니다.
and we have the following stuff so we have rows
9:22:42
무한 진행을 우리는 프레임 절이라고 부릅니다.
unbounded proceeding we call this a frame clause
9:22:46
또는 윈도우 프레임입니다. 여기서 우리가 하는 것은
or window frame so what we are doing over here that
9:22:49
각 윈도우 내에서 계산에 관련된 행의 하위 집합을 정의하는 것입니다.
we are defining a subset of rows within each
9:22:52
완전히 이해합니다.
window that is relevant for the calculation totally understand
9:22:55
이것이 처음에는 혼란스럽거나 복잡하다면, 저에게도 그랬습니다.
if this is confusing at the start or complex it was for me as
9:22:59
그래서 우리가 할 것은 이 개념을 깊이 파고들어 어떻게 작동하는지 이해하는 것입니다. 단계별로 진행할 것이니 걱정하지 마세요.
well so what we're gonna do we're gonna deep dive into the concept in order to understand how this works and we're gonna do it step by step so don't worry about
9:23:06
좋습니다. 이제 프레임 절과 관련하여 무슨 일이 일어나고 있는지 기본부터 이해해 봅시다.
it all right so now let's understand what is going on with the frame clause from
9:23:10
이제 집계를 수행하고 윈도우 함수를 사용하지 않으면
the basics so now if you do aggregations and you don't
9:23:13
전체 데이터 또는 테이블 내의 행을 고려하게 됩니다. 하지만 우리가 할 수 있는 것은
use window function you're going to consider the entire data or
9:23:16
데이터를 파티션 pi를 사용하여 윈도우로 나누는 것입니다.
rows inside the table but what we can do we can go and divide
9:23:19
예를 들어 여기 윈도우 1과 윈도우 2가 있습니다.
the data using partition pi to a window so
9:23:23
이제 집계를 수행하면 윈도우 1의 모든 행이 집계될 수 있고, 그 다음 윈도우 2로 가서
for example here we have window one and window two now
9:23:26
모든 행을 집계합니다. SQL에서 우리가 할 수 있는 것은
if you go and do aggregations all the rows in the window one can be aggregated and then it's going to go to the window two and
9:23:32
모든 행을 윈도우 내에서 원하지 않는다고 말할 수 있습니다.
aggregate all the rows what we can do in SQL that we
9:23:35
윈도우 내의 행의 하위 집합을 원합니다.
can say you know what I don't want all rows inside the window
9:23:38
여기서 우리가 하는 것은 두 개의 창이 있다는 것입니다.
I want a subset of rows inside the window so
9:23:42
여기서 우리가 하는 것은 두 개의 창이 있다는 것입니다.
what we are doing over here is that we have those two windows but
9:23:45
우리는 범위를 지정하거나 하위 집합을 지정합니다.
we specify a scope or we specify subset
9:23:48
각 창에서 데이터의 하위 집합을 포함시키는 것입니다.
of data from each window to be involved in
9:23:51
집계는 물론 집계뿐만 아니라 순위 매기기와 다른 계산도 할 수 있습니다.
the aggregations of course not only aggregations we can do ranking other stuff so I mean calculations so here like we have a window inside a window so we are defining a scope of rows
9:24:02
계산에 모든 행이 포함되어야 하는 것은 아닙니다.
not all rows should be involved in the calculation but
9:24:05
특정 데이터의 하위 집합만 포함되어야 합니다.
only a specific subset of data and we can do that
9:24:08
프레임 절을 사용하여 이를 수행할 수 있습니다.
using the frame clause so again the partition by you
9:24:11
전체 데이터 세트를 여러 창으로 나누는 데 사용할 수 있습니다.
can use it in order to divide the entire data sets into
9:24:15
각 창 내의 모든 행을 고려하고 싶지 않다면,
multiple windows and now for the frame clause if you
9:24:18
계산에서 집중하고 특정 데이터만 지정하고 싶다면,
don't want to consider all the rows within each window in
9:24:21
각 창 내의 데이터 하위 집합만 지정할 수 있습니다.
the calculation you want to focus and specify only
9:24:24
프레임 절을 사용할 수 있습니다. 이제 구문을 이해해 봅시다.
a subset of data within each window then you can go and use the frame clause all right so now let's go and understand
9:24:30
프레임 절의 구문을 살펴보겠습니다.
the syntax of the frame clause let's have the following example
9:24:33
우리는 창 함수가 판매의 평균이라고 말하고 있습니다.
we are saying the window function is the average of sales and
9:24:37
그런 다음 우리는 창을 정의합니다.
then we define the window so we have the first part partition by categories
9:24:40
주문 날짜로 정렬한 다음,
order by order dates and then we have
9:24:43
프레임 절은 현재 행과 다음 행 사이의 행이 될 것입니다.
the frame clause it's going to be the following rows between current
9:24:47
현재 행과 무한히 진행되는 행 사이의 프레임입니다.
row and unbounded proceeding this is the frame
9:24:50
우리는 두 가지 유형이 있습니다.
types and we have two types we have the rows and groups
9:24:53
행과 그룹이 있습니다.
then we have like between and the range so
9:24:56
그런 다음 우리는 '사이'와 '범위'를 가집니다.
the first range going to be the frame boundary the lower
9:24:59
첫 번째 범위는 프레임 경계가 될 것입니다.
value and here it accepts three types of
9:25:02
여기서는 세 가지 유형의 키워드를 수용합니다.
keywords like the current row or a number of
9:25:05
현재 행 또는 특정 수의 이전 행이 될 수 있습니다.
preceding or the unbounded preceding and then
9:25:08
다음 행 또는 무한히 다음 행을 사용할 수 있습니다.
we have another frame boundary it's gonna be the higher values and
9:25:12
현재 행을 사용하여 다음 또는 무제한 다음을 사용할 수 있습니다.
it accepts the following stuff we can use the current row in following or unbounded following so as you can see we are defining like boundary or a range from low value to high value so now we have some rules
9:25:24
프레임 절을 사용할 수 없습니다.
we cannot use the frame clause without order by
9:25:27
정의에 order by가 있어야 합니다.
so order by must be exist in the definition in
9:25:30
프레임 절을 사용하기 위해
order to use frame clause and the second
9:25:33
하한은 상한보다 앞서야 합니다.
rule it says lower boundary must be before the higher boundary so
9:25:37
항상 하한에서 시작합니다.
always we start with the lower boundary and we end up having
9:25:40
상한을 전환할 수 없습니다.
the higher boundary you cannot switch that okay so now
9:25:43
간단한 예를 들어보겠습니다.
we have a very simple example we have the month and the sales and the following query sum of sales this is the window function and the definition of the window gonna be
9:25:51
월별로 정렬합니다.
order by month we are not using partition by just in order to make our
9:25:54
현재 행과 두 행 사이의
life easier and the frame clause is going to be defined like
9:25:57
SQL이 이를 실행하는 방법을 봅시다.
this rows between current row and the two
9:26:00
정의는 월별로 정렬됩니다.
following so now let's see how sql can execute this the
9:26:03
SQL은 현재 행의 프레임 정의로 작업합니다.
first definition order by month as you can see the methods are sorted already
9:26:07
두 개의 다음 행과 함께 SQL이 이 행을 처리합니다.
so now sql is going to work with the frame definition current row
9:26:10
첫 번째 행부터 시작합니다.
and the two following so sql is going to process this row
9:26:14
현재 행과 두 행까지의 범위입니다.
by row so it's going to start with the first row and it's going to be our current row as here in the sql so this is our
9:26:21
2개의 다음 행이 됩니다.
current row and we say the range until two rows two
9:26:24
포인터는 여기에서 두 개로 이동합니다.
following rows so it's going to be february and march so
9:26:27
프레임 경계가 있습니다.
that means the pointer going to be over here for the two
9:26:30
첫 번째 행에 대해 70을 얻습니다.
following so with us we have the frame boundaries and isquels have the following scope for the first row so we have three rows and the summarization of those three rows going to be around 70.
9:26:42
모든 행이 아니라 이 데이터 하위 집합만.
so what we get for the first row 70 because the scope is
9:26:45
첫 번째 행에서 스케일이 완료되었습니다.
not all rows but only this subset of data
9:26:48
두 번째 행으로 점프합니다.
okay so with that the scale is done with the first row it's gonna jump to
9:26:51
2개의 다음 행은
the second row so the pointer gonna be the current row at the february
9:26:54
4월에 있게 됩니다.
and the second two following gonna be at
9:26:58
4월이니까, 보시다시피 우리는 내려가고 있습니다.
april so with that as you can see we are sliding down
9:27:01
데이터의 하위 집합 또는 창에서 그렇게 됩니다.
in the subset of data or in the window and with that we
9:27:04
새로운 범위, 새로운 하위 집합과 모든 것의 요약이 생깁니다.
have a new scope a new subset and the summarization of all those
9:27:07
값은 45가 될 것이고, 그래서 그게 전부입니다. 이미 이해하셨을 거라고 생각합니다.
values gonna be 45 so that's it i think you get it already it's gonna go to the next one the pointer gonna be on march and the two following gonna be on june and And it's going to slide like this.
9:27:17
우리는 범위 내에 세 개의 행이 있습니다. 그 요약은 105가 될 것입니다.
We have those three rows in the scope. And the summarization of that is going to be 105. So now things get interesting for the next row.
9:27:25
현재 행의 포인터는 4월이 될 것입니다. 하지만 다음 두 개는 테이블의 끝 이후가 될 것입니다.
So the pointer for the current row is going to be April. But the two following is going to be like after the end of the table or something like that.
9:27:31
내려가면서 보시다시피, 이제 범위 또는 프레임의 하위 집합은 두 개의 행만 포함될 것입니다.
So as we slide down, as you can see, the scope now or the subset of the frame is going to be only two rows.
9:27:37
출력은 75가 될 것이고, 마지막 행으로 가면 현재 행이 될 것입니다.
And the output is going to be 75. And finally, if you go to the last row, it's going to be the current row.
9:27:43
이 하위 집합에는 행이 하나만 있을 것입니다.
and we're going to have only one row for this subset because the
9:27:46
다음 두 개는 테이블 밖에 있으며, 우리는 같은 값을 얻을 것입니다.
two following is just outside of the table and we're going to get the same value
9:27:49
요약과 같아서, 보시다시피 그게 전부입니다.
as the summarization so as you can see that's it it's
9:27:52
매우 간단하죠. 우리가 사용하는 프레임은
very simple right so the frame we use it in order to scope
9:27:55
계산에 관련된 행을 정의하는 것입니다.
which rows are involved in the calculations so
9:27:59
프레임의 경계를 정의하는 것만 하면 됩니다.
all what you have to do is to define the boundaries of the frame the lower and the upper boundary let's see what other options do we have with the frames okay so here we have
9:28:07
같은 예제지만 프레임의 경계를 재정의합니다.
the same example but we redefine the boundaries of the frame
9:28:10
현재 행 사이의 행은 이렇습니다.
like this rows between current row this is
9:28:13
첫 번째 경계와 무제한 다음이란 의미입니다.
the first boundary and unbounded following this means
9:28:16
우리는 항상 마지막 레코드를 목표로 합니다.
that we are targeting always the last record in the
9:28:19
정적이며, 이 예제에서는
window or in the table so unbounded following gonna be always
9:28:22
6월을 가리키고 있습니다.
static and it's gonna be in this example pointing to
9:28:25
이제 행별로 이동할 것이고 현재 행은
june and now it's gonna go row by row and the current road
9:28:29
1월의 시작처럼 될 것이고, 그 다음은 2월입니다.
gonna be like the start january and then february i'm just gonna take this example the pointer is on february
9:28:35
하위 집합 또는 프레임은 네 개가 될 것입니다.
and the subsets or the frame going to be those four
9:28:38
행은 2월, 3월, 4월, 6월이 될 수 있습니다.
rows so it can be February March April June so it can
9:28:41
네 개의 행이 될 것이고, 총 집계는 115가 될 것입니다.
be four rows and the total aggregation of that's
9:28:44
115가 될 것이므로 이렇게 할 수 있습니다.
going to be 115 so you can do
9:28:47
이전에는 더 유연하게 할 수 있었습니다.
it like this and previously it was like flexible more flexible
9:28:50
이전에는 두 개의 경계가 있었지만 이번에는 경계가 없는 경계가 있습니다. 즉, 항상 마지막 것이 경계가 됩니다.
it was two following but this time we have unbounded following that means always the boundary going to be the last one so as we are
9:28:59
여기에서 기록을 이동하면서 경계가
moving with the records over here the boundary
9:29:02
점점 작아질 것입니다.
is going to be smaller smaller and like
9:29:05
이렇게 마지막 두 개는 동일한
this and the last one they're going to be both in the same
9:29:09
기록에 있을 것입니다. 따라서 현재 기록도 경계가 없는
record so the current record is going to be as well the unbounded
9:29:12
따르기입니다. 다음 것을 보겠습니다. 창의 정의는
following okay let's see the next one the definition of the window going
9:29:15
이전의 한 행과 현재 행 사이의 다음 행이 될 것입니다.
to be the following rows between one preceding
9:29:18
여기서 한 행이 현재 행보다 낮습니다. SQL이 이를 실행하는 방법을 보겠습니다. 현재 3월에 있다고 가정합시다.
and the current row so here is the way around one proceeding is lower than the current row so let's see how sql gonna execute this let's say that we
9:29:27
이것이 현재 행입니다.
are currently at march so this is the current row
9:29:30
우리는 한 행 이전 사이에 있다고 말하고 있습니다. 즉, 한
and we are saying between one proceeding so that means one
9:29:34
행은 현재 행의 이전 행입니다. 따라서 프레임은
row before the current row so the frame
9:29:37
이렇게 될 수 있으며, 우리는 두 개의 행만 있습니다.
can be like this and we have only two rows so
9:29:40
값은 이 두 행의 요약이 될 것이고
the value going to be the summarization of those two rows and
9:29:43
40이 될 것입니다. 즉, 우리는 항상
it's going to be 40 so that means we are always targeting
9:29:46
현재 행 이전의 행을 목표로 하고 있습니다. 이제 계속 진행합시다.
the rows before the current row okay so now let's keep going
9:29:49
프레임에 대한 모든 것을 이해하기 위해 다른 옵션으로. 우리는 이렇게 다시 정의합니다. 경계가 없는
with the other options in order to understand everything about the frame so we redefine it like this rows between unbounded
9:29:56
이전과 현재 행 사이의 행. 따라서 경계가 없는 이전은
preceding and the current row so unbounded preceding gonna be the first row in the
9:30:00
테이블의 첫 번째 행 또는 창의 첫 번째 행이 될 것입니다. 따라서 이렇게 정적일 것입니다.
table or in the window so it's going to be static like this it's
9:30:03
첫 번째는 1월이 될 것이고, 현재 행이 3월에 있다고 가정합시다. 따라서 창 또는 부분 집합은 이렇게 보일 것입니다. 이 세 개의 행과 그 총합은 60이 될 것입니다.
going to be the first one january and let's say that we are at this current row in march so the window or the subset going to look like this those three rows and the total of that's going to be 60.
9:30:15
이제 SQL이 다음으로 진행하면서
so now as sql is proceeding to the next one
9:30:18
첫 번째 경계를 고정할 것입니다. 따라서 항상
it's going to fix the first boundary so it's going to be always pointing
9:30:21
1월을 가리키게 될 것이고, 부분 집합은 조금 더 커질 것입니다.
to january and the subset is going to be a little bit bigger until
9:30:24
마지막에 도달할 때까지.
we reach the last one and with that we're
9:30:27
부분집합을 사용하여 전체 행을 가질 것입니다.
going to have the subsets the whole rows so
9:30:31
그렇게 하면 정말 큰 유연성을 얻을 수 있습니다.
with that we get a really great flexibility on how to
9:30:34
부분집합을 정의하고 부분집합이 어떻게 이동하는지.
define the subset and how the subset is shifting through
9:30:37
현재 행을 항상 사용할 필요는 없습니다.
the window okay so now we are just having fun so we're just playing around
9:30:40
이 정의에서 이전 행과 다음 행 사이의 행을 사용할 수 있습니다.
with the boundaries we don't have always to use the current row so we can use for example here in this definition rows between one preceding and one
9:30:48
현재 행을 전혀 포함하지 않습니다.
following so we don't include at all the current row in
9:30:51
현재 행이 3월이 될 것이고 이전 행은 2월이 될 것입니다.
the boundaries so let's say again our current row
9:30:54
다음 행은 4월이 될 것이므로,
gonna be in march so one proceeding gonna be february
9:30:58
우리의 프레임은 세 개의 행이 될 것이고,
and one following gonna be april so with that
9:31:01
이렇게 하면 집계가 약간의 범위가 될 것입니다.
our frame gonna be the three rows and let
9:31:05
45가 될 것이고, 경계는 이전과 다음이 될 것입니다.
me get it like this and the aggregation of this gonna be around
9:31:08
마지막 옵션이 무엇인지 알게 될 것입니다.
45 so with that as you can see the boundary is gonna be one proceeding and one following so it should not be always the current row all right so now i think you already
9:31:16
모든 것을 가질 것입니다.
get it what's going to be the last option we're going to have everything so the
9:31:20
프레임의 정의는 무한히 이전 행과 무한히 다음 행 사이의 행이 될 것입니다.
definition of the frame going to be rows between unbounded preceding
9:31:23
무한히 이전 행은 1월이 될 것이고,
and unbounded following what we're going to have over here the
9:31:26
무한히 다음 행은 6월이 될 것입니다.
unbounded preceding going to be january and the unbounded following
9:31:29
이제 프레임은 모든 행이 될 것입니다.
going to be june and now the frame going
9:31:32
현재 행과 관계없이 항상 고정된 부분집합이 될 것입니다.
to be everything all the rows and it doesn't
9:31:36
우리가 여기 있거나 2월 또는 3월이라면,
matter where are we with the current row it's going to be always a fixed subset so it's going to be always everything so
9:31:42
모든 행을 고려할 것이고 총 판매량은 135가 될 것입니다.
So if we are over here or February or March, we're going to be considering all rows and the total sales of that's going to be 135.
9:31:51
모든 행에 대해 정확히 같은 결과를 얻을 것입니다.
So we will get the exact same results for everything for all rows.
9:31:56
그래서 그렇게 하면 복잡하지 않다고 생각합니다.
So with that, I think it's not that complicated, right? We just have to provide the boundaries and then the calculation can be depending on the frame on the subset of data.
9:32:05
SQL로 돌아가서 프레임워크를 이해하기 위해 연습을 시작합시다.
Okay, guys. So now let's go back to SQL and start practicing in order to understand how the framework.
9:32:11
이렇게 윈도우를 정의합시다.
So let's go and define a window like this. So sum of sales and the window definition like this.
9:32:17
주문 상태로 데이터를 나누겠습니다.
We're going to divide the data by order status.
9:32:21
데이터를 주문 상태별로 나누겠습니다.
And let's say we're going to sort it by order date. And let's define a frame like this.
9:32:27
현재 행과 두 개의 다음 행 사이의 행입니다. 이를 총 판매량이라고 부르겠습니다.
Rows between current row and two following. Let's give it a name total sales.
9:32:36
이제 실행해 보겠습니다. 이제 데이터를 살펴보겠습니다. SQL이 결과를 두 개의 섹션, 즉 배달 및 배송으로 나눌 수 있음을 알 수 있습니다.
So let's go and execute it. So now let's look to the data. Now you see that SQL can divide our results into two sections, two windows delivered and shipped.
9:32:44
데이터가 주문 날짜별로 정렬되어 있음을 알 수 있습니다.
And you can see that the data is sorted by the order date.
9:32:48
예를 들어, 이 상태가 배달된 경우, 1월 10일과 같은 것을 볼 수 있습니다.
So as you can see over here, for example, in this status delivered, we can see that first of January 10 and so on.
9:32:55
각 창에서 프레임을 정의했습니다. 예를 들어, 첫 번째 것을 살펴보겠습니다.
And then the third part, we have defined a frame in each window. So for example, let's take the first one.
9:33:01
현재 행입니다. 현재 행과 두 개의 다음 주문 사이의 프레임이라고 말할 수 있습니다.
So this is the current row. So we say the frame is between the current row and the two following orders.
9:33:08
즉, 범위는 이렇게 될 것입니다. 10 더하기 20, 25, 55가 될 수 있습니다.
So that means the scope going to be like this. So 10 plus 20, 25, it can be 55.
9:33:14
각 창의 마지막 레코드를 확인하는 것도 흥미롭습니다.
And now what is interesting as well to check here is the last record of each window.
9:33:18
이 창을 가져가고 마지막 레코드는 7번이 될 것입니다.
So now let's take this window over here and the last record going to be number seven.
9:33:22
이 주문과 현재 레코드라고 가정해 보겠습니다.
So this order and let's say this is the current records.
9:33:26
현재 레코드와 두 개의 다음 레코드 사이의 프레임이라고 말했습니다.
So we said the frame between current record and the two following.
9:33:30
하지만 이것이 이 창의 마지막 레코드이기 때문에 다음 두 개의 주문을 고려하지 않습니다.
But since it is the last record of this window, it will not go and consider the next two orders
9:33:36
그 두 개의 주문은 창 밖에 있기 때문입니다.
because those two orders are outside of the window
9:33:39
그래서 여기 30이 있고 SQL은 그렇지 않습니다.
and that's why we have here 30 and sql doesn't
9:33:42
모든 값을 요약하고 30이 됩니다.
go and summarize all those value so we have it 30
9:33:45
그 이후에는 아무것도 없기 때문에 이렇게 됩니다.
and there is nothing after that that's why
9:33:49
그래서 30이 될 것이고 프레임이 계산될 것입니다.
we will get 30 so as you can see the frame going to be calculated
9:33:52
하나의 창 내에서만 계산되므로
within one window so it will not consider
9:33:55
창 밖의 어떤 것도 고려하지 않으므로 이렇게 됩니다.
anything outside of the window so this is how the
9:33:58
프레임은 파티션 내에서 작동하므로 이제 몇 가지를 보여드리겠습니다.
frame works within partitions so now i would like to show you as well a few stuff about the frames we can use shortcuts but
9:34:05
우리는 그것을 진행하는 것과만 사용할 수 있습니다.
we can use them only with the proceeding so for example
9:34:08
정의가 이렇게 두 개의 진행으로 변경된다고 가정해 보겠습니다.
let's say i'm going to change the definition like this two proceedings
9:34:12
현재 행이므로 실행해 보겠습니다.
and current row so let's
9:34:15
결과를 얻을 수 있습니다. 이제 결과를 빠르게 확인하고 싶다면 이 주문을 예로 들어 보겠습니다.
go and execute it and we will get those results so now
9:34:18
결과를 빠르게 확인하고 싶다면 이 주문을 예로 들어보겠습니다.
if you want to check the results quickly let's take for example this order
9:34:21
이곳에서 우리는 항상 값을 요약하고 있습니다.
over here and we are always summarizing the values
9:34:24
두 개의 이전 주문을 의미하므로
of the two previous orders so that means those
9:34:28
세 개의 주문이 프레임에 포함될 것이고 출력은 55가 될 것입니다. 이제 SQL에 대한 단축키가 있지만
three orders going to be involved in the frame and the output going to be 55 so now there is a shortcut for sql but only
9:34:35
진행 중인 부분에서 범위를 제거할 수 있습니다.
for the proceeding where we can remove the range so
9:34:38
모든 것을 제거하고 이렇게 남길 수 있습니다.
we can go and remove everything and we can leave it
9:34:41
이렇게 진행하는 행을 만들고 가면
like this rows to proceeding and if you go and
9:34:44
실행하면 정확한 결과를 얻을 수 있습니다. 이것은
execute it we will get exact results so this is
9:34:47
창을 정의하는 빠른 방법 또는 단축키입니다. 하지만 이것은
a quick way or a shortcut on how to define a window but it only
9:34:50
진행 중인 부분에서만 작동합니다. 예를 들어, 여기로 가면
works with the proceeding so for example if i go over here
9:34:53
예를 들어, 무한대라고 말하면 작동할 것입니다.
and say for example unbounded it's gonna work so
9:34:57
무한대 사이의 결과를 얻을 것입니다.
we will get the results between the unbounded
9:35:00
진행 중인 부분과 현재 행 사이의 결과를 얻을 것입니다. 하지만 여기로 가서
proceeding and the current row but if you go over here and you
9:35:03
무한대를 설정하자고 하면 오류가 발생할 것입니다. 무한대를 제거하면 같은 일이 발생합니다.
say you know what let's have the unbounded following is we're
9:35:06
무한대를 설정하자고 하면 오류가 발생할 것입니다. 예를 들어, 하나는 SQL이 좋아하지 않을 것입니다.
gonna say there's an error and the same thing if you remove the unbounded
9:35:09
예를 들어, 다음 SQL은 좋아하지 않을 것입니다.
let's say for example one following sql will not like
9:35:12
그래서 진행 중인 것과 마지막 한 가지는 프레임에 대한 것입니다. 기본 프레임이 있으므로 사용하지 않으면
it so you can use the shortcut only with the proceeding and one last thing about the frames is that there is a default frame so if you don't use
9:35:21
프레임을 사용하지 않고 order by를 사용하면 어떤 일이 발생할 수 있습니다.
any frame and you use order by what can happen
9:35:24
기본 프레임을 사용할 수 있으므로 결과를 확인하면
is qul can use a default frame so if you check the result
9:35:27
여기 이 창에 대한 값이 있다는 것을 알게 될 것입니다.
you will notice that that's for this window over here those values
9:35:30
그 값들은 그곳의 전체 판매 값과 같지 않습니다.
are not like the whole values of the sales there
9:35:34
프레임처럼 숨겨진 프레임과 기본 프레임이 있습니다.
is like frame there is hidden frame and the default frame
9:35:37
SQL에서는 이렇게 됩니다: unbounded 사이의 행
in sql gonna be like this rows between unbounded
9:35:40
진행 중인 행과 현재 행.
proceeding and current row so
9:35:43
이것이 기본 프레임입니다. order를 사용하면.
this is the default frame if you you use order
9:35:46
이제 실행하면
by so now if you go and just execute it you will see that
9:35:50
정확한 결과를 얻을 수 있으니 조심하세요
we will get the exact results so be careful once you use
9:35:53
집계 함수와 함께 정렬할 때
order by with the aggregate functions there will be
9:35:56
숨겨진 프레임이나 기본 프레임이 있습니다
a hidden frame or a default frame like this between the
9:35:59
무제한 진행과 현재 행 사이에는 세 가지 방법이 있습니다
unbounded proceeding and the current row so that means there are three
9:36:02
이 시나리오를 수행하는 방법이 있습니다
ways in order to do this scenario of framework between unbounded proceeding and current row either write it like this or you can go and have a shortcut like this let me just execute it
9:36:12
같은 결과를 얻거나 완전히 제거할 수 있습니다
so we'll get the same result or just remove it completely we
9:36:16
기본 프레임은 정렬과 함께 작동합니다
will get as well the same results now again the hidden frame or
9:36:19
여기서 정렬을 제거하면
the default frame is only working with the order by so
9:36:22
결과를 확인해 보겠습니다
if you go for example here and remove the order by let's
9:36:26
전체 창이 집계됩니다
see the results the whole window will be aggregated so again
9:36:29
모든 행을 고려하게 됩니다
let me just select it so you can see that sql gonna
9:36:32
전체 창에 대한 총 매출이 나옵니다
consider all the rows in the aggregations and we will get the
9:36:35
정의된 프레임이 없습니다
total sales for the whole window so there will be no
9:36:38
정렬을 사용할 때만 나타납니다
frame defined only it's going to be present once you use
9:36:42
프레임 절차를 다루었습니다
order by all right friends so with the frame clause we have now
9:36:45
창을 정의하는 모든 구성 요소를 다루었습니다
covered all the components on how to define a window
9:36:48
창의 구문에 대해 모든 것을 다루었습니다
inside and over close and with that we have covered
9:36:51
함수에 대해
everything about the syntax of the window
9:36:54
함수는 괜찮습니다
functions okay
9:36:59
여러분, 이제 우리는 규칙, 또는 제한 사항을 이해하러 가겠습니다
guys so now we're going to go and understand the rules or let's say the limitations
9:37:02
창 함수의 사용에 대해 배워봅시다
of window functions so let's learn what you are
9:37:05
창 함수를 사용할 때 할 수 없는 것들입니다
not allowed to do while using window functions okay
9:37:08
첫 번째 규칙은 창을 사용할 수 있다는 것입니다
so the first rule of that you are allowed to use the window
9:37:11
함수는 선택 절에서만 사용할 수 있습니다
function only in the select clause and
9:37:14
여기서 우리는 다시 같은 예제를 가지고 있습니다.
as well in the order by clause so here we have again the same example
9:37:18
주문 상태에 따른 총 판매량을 찾고 있습니다.
where we finding the total sales by the order status so
9:37:21
선택 절에서 윈도우 함수를 사용했습니다.
as you can see we used the window function in the select clause
9:37:24
이것을 실행하면 오류가 발생하지 않을 것입니다.
and we didn't get an error right so now we can go and use it as well in the order by so let's say order by and let's go and copy
9:37:32
이름을 제외한 모든 것을 정렬할 수 있습니다.
everything but not the name in the order by so if i go and execute this there will be no errors and
9:37:38
예를 들어 내림차순으로 정렬해 보겠습니다.
isql gonna allow it and as you can see the result didn't change so
9:37:41
여기 내림차순을 입력하고 실행해 보겠습니다.
let's go and sort it for example descending so i'm gonna
9:37:44
가장 높은 값과 가장 낮은 값의 총 판매량을 갖게 됩니다.
write here descending and let's execute now we
9:37:47
우리는 선택 및 정렬에서만 사용할 수 있는 규칙을 가지고 있습니다.
have the total sales with the highest values then the lowest values
9:37:51
즉, 윈도우 함수를 사용할 수 없습니다.
so having this rule that we can use it only in select and order by
9:37:54
데이터를 필터링하기 위해서입니다.
that means we cannot use window functions in order to
9:37:57
이것을 실행하면 xql이 표시됩니다.
filter data so let me show you for example instead of order by let's have where clause where the total sales let's say bigger than 100.
9:38:06
그것을 할 수 없다고 말할 것입니다.
so let's go and execute this and as you can see xql
9:38:09
선택 및 정렬에서만 사용할 수 있습니다.
gonna say no you are not allowed to do that you can do that only for
9:38:13
데이터 필터링에 사용할 수 없습니다.
select and order by so we are not allowed to use it for
9:38:16
그룹화에서 사용할 수 없습니다.
filtering data using the where clause and as well you are
9:38:19
그룹화에서 사용할 수 없습니다.
not allowed to use it in the group by so if i go and do
9:38:22
같은 오류가 발생할 것입니다.
a group by and as well remove the condition over here
9:38:25
그룹화에서 윈도우 함수를 사용할 수 없습니다.
so if you execute it you're gonna get the same error you are
9:38:28
정렬 또는 선택에서만 사용할 수 있습니다.
not allowed to use the window function in the group by so only
9:38:31
두 번째 규칙으로 넘어갑니다.
with the order by or as well in the select
9:38:35
다른 윈도우 함수 안에서 사용할 수 없습니다.
clause okay so now to the second rule you cannot use
9:38:38
즉, 윈도우 함수를 중첩할 수 없습니다.
window functions inside another window function so
9:38:41
그룹화를 제거해 보겠습니다.
that means you cannot go and nest window functions together
9:38:44
이제 모든 것이 작동해야 합니다.
let me show you what i mean with that so let's remove the group by
9:38:47
이제 모든 것이 작동해야 합니다. 전체 윈도우 함수를 여기로 복사하고 중첩해 보겠습니다. 이제 매출 대신 다른 윈도우 함수 안에 윈도우 함수를 가질 수 있습니다.
now everything should be working let's take and copy the whole window function over here and let's just nest it so So instead of sales, we can have now window function inside another window function.
9:38:59
보시다시피, 이것이 내부 윈도우 함수이고 나머지는 외부 윈도우 함수입니다.
So as you can see, this is the inner window function and the rest, the outside is the outside window function.
9:39:05
이제 이것을 실행하면, 스케일이 다른 윈도우 함수의 맥락에서 윈도우 함수를 사용할 수 없다고 알려줄 것입니다.
So if I go and execute this, you will see that the scale can tell us you cannot use the window function in the context of another window function.
9:39:14
따라서 윈도우 함수를 사용하여 중첩할 수 없습니다. 보시다시피, 이것은 이러한 함수에 대한 또 다른 제한입니다. 알겠습니다.
So we cannot do nesting using window functions. So as you can see, this is another limitation for those functions. All right.
9:39:21
세 번째 규칙으로 넘어가겠습니다. 또는 윈도우에 대한 정보를 보겠습니다.
moving to the third rule or let's say an info the window
9:39:24
함수는 데이터를 필터링한 후 실행될 수 있습니다.
function can be executed after filtering the data with
9:39:27
where 절을 사용하여 예를 들어 보겠습니다. 자, 이제
the where clause let's have an example so okay so now let's
9:39:30
같은 정보를 원한다고 가정해 보겠습니다. 각 상태에 대한 총 매출이지만
say that i would like to have the same informations the total says for each status but
9:39:34
101과 102라는 두 제품에 대해서만
only for two products 101 and 102 so
9:39:37
그럼 해보겠습니다. where 절을 사용할 것입니다.
let's go and do that we're going to use the where clause
9:39:40
그런 다음 제품 ID를 지정할 것입니다. 우리는
and then we're going to say product id in we're
9:39:43
101과 102를 지정할 것입니다. 자, 이제 실행해 보겠습니다. 여전히 두 개의 파티션이 있습니다. 하나는 배송된 것, 하나는 발송된 것입니다.
going to specify 101 and 102 so let's go and execute this now you can see we still have two partitions, so one for the delivered and one for the shipped.
9:39:53
하지만 총 매출은 두 제품에만 집중하고 전체 데이터 세트를 필터링했기 때문에 줄어들었습니다.
But the total sales is reduced because we are only focusing on two products and we filtered the whole data sets.
9:40:00
SQL이 어떻게 작동하는지 보겠습니다. 먼저 where 절이 실행됩니다.
so how sql works first the where clause is going to be executed
9:40:03
그런 다음 윈도우 함수가 계산됩니다. 즉, 먼저 필터링하고 그 다음 집계가 이루어집니다. 알겠습니다, 여러분. 이제 마지막 규칙으로 넘어가겠습니다. 가장 흥미로운 규칙입니다.
and then the window function is going to be calculated so that means first filtering and then aggregations okay guys now we're going to move to the last rule to the most interesting one and it says the following
9:40:14
윈도우 함수는 같은 열을 사용할 경우에만 group by 절과 함께 사용할 수 있습니다. 제가 무슨 뜻인지 설명하겠습니다. 하지만 먼저 커피 한 잔.
you are allowed to use the window function together with the group by clause only if you use the same columns so let me explain what do i mean but first some coffee
9:40:26
다음 작업을 해보겠습니다. 고객을 순위 매기라고 합니다.
let's have the following task and it says rank the customers
9:40:29
총 매출을 기준으로 고객을 순위 매기라고 합니다. 이제
based on their total sales so now it
9:40:32
정말 쉬워 보이지만, 확인해 보면 두 가지 계산이 있습니다.
sounds really easy but if you check it you have here two calculations
9:40:36
첫 번째는 고객을 순위 매기는 것이고, 두 번째 계산은 집계입니다. 각 고객의 총 매출을 찾아야 합니다. 자, 이제 단계별로 어떻게 해결하는지 보여드리겠습니다.
the first one you have to rank the customers and the second calculation is an aggregation you have to find the total sales for each customers okay so now i'm going to show you step by step how i usually solve those tasks
9:40:48
우선 총 매출을 확인해 보겠습니다. 이것은 집계입니다.
so for now let's check the total sales it is an aggregation
9:40:51
그렇다면 sum 함수를 사용할 수 있습니다. 이 함수는
right so we can use the sum function and this function is
9:40:54
group by와 윈도우 모두에서 사용할 수 있습니다.
available in both group by and as well in the window
9:40:57
그렇다면 지금은 group by를 사용할 것입니다. 그 이유는
function so for now i'm going to go with the group by and that's
9:41:00
작업이 매우 간단하기 때문입니다. 다른 것을 보여줄 필요가 없습니다.
because the task is very simple we don't have to show any other
9:41:03
세부사항은 필요 없으니 집계에 관한 것입니다.
details right so it's all about aggregations so
9:41:07
그룹화를 사용하지 않는 이유는 고객을 순위 매기는 첫 번째 부분에서
why not using the group by and now to the first part where we have to rank the customers we cannot use the rank function with a group by right group
9:41:15
여기서는 집계만 사용하므로
uses only aggregations so here we are forced to
9:41:18
윈도우 함수를 사용해야 합니다.
use the window function so that means for the rank i'm going to use window
9:41:21
총 매출에 대한 함수는 그룹화를 사용할 것입니다.
function for the total sales i'm going to use a group by so
9:41:24
이제 단계별로 진행해 보겠습니다.
now let's do it step by step so first we have to find the
9:41:28
각 고객의 총 매출을 찾는 것입니다.
total sales for each customer using group by it's
9:41:31
매우 간단하니 모든 것을 제거하겠습니다.
very simple so i'm just going to remove all those stuff
9:41:34
우리의 선택문에는 고객 ID와
in our select statements we need the customer id and
9:41:38
그룹화된 고객 ID가 필요합니다.
then we don't need a window function over here and then after that from we're going to have a
9:41:43
이제 고객을 그룹화하고
group by customer id so now i'm just grouping the customers
9:41:46
모든 매출의 합계를 찾겠습니다.
and finding the sum of all sales let's
9:41:49
결과에서 네 명의 고객이 있습니다.
go and execute this so now as you can see in the results we have four
9:41:52
그래서 네 개의 행이 있습니다.
customers and that's why we have four rows and as well we have the
9:41:56
총 매출을 확인해 보겠습니다.
total sales so let's say the half of the tasks is
9:41:59
이미 해결된 절반의 작업입니다.
already solved right now what is missing that we
9:42:02
무엇이 부족한지 확인해 보겠습니다.
need to rank so let's go and build that the second step we're going to use the rank function and we can define a window for that
9:42:10
순위를 매길 필요가 있습니다.
So over and inside it will not partition the data at all because it's already like a grouped up.
9:42:15
총 매출을 기준으로 데이터를 순위 매기고 있습니다.
So what we're going to do over order by the rank function always needs an order by. Don't worry about it. We can talk about it later.
9:42:21
이제 복사해서 정렬 후에 붙여넣겠습니다.
So now we are ranking the data based on the total sales. That means the sum of sales.
9:42:26
내림차순으로 설정하겠습니다.
So what we're going to do, let's just go and copy this and put it after the order by. And now we have to decide whether ascending or descending.
9:42:33
이제 고객 순위가 매겨졌습니다.
It's going to be descending. So the highest sales first and then the lowest sales.
9:42:36
그룹화와 함께 윈도우 함수가 있습니다.
so now as you can see we have now a rank customers and we have a window function now together with the
9:42:43
이제 실행해 보겠습니다.
group by so now let's go and excuse this and see whether
9:42:46
ISQL이 허용하는지 확인해 보겠습니다.
isql gonna allow it so let's run it and as you can see
9:42:49
isql이 실행되고 각 고객의 순위를 얻습니다.
isql runs it and we will get the rank for each
9:42:52
고객 중 세 번째 고객이 총 매출이 가장 높습니다.
customers so the customer three has the highest total
9:42:56
판매 후 첫 번째 고객과 마지막 고객은
sale then the customer number one and the last one gonna be customer
9:42:59
총 매출이 가장 낮은 두 번째 고객입니다. 알겠죠, 우리는
number two with the lowest total sales all right so we
9:43:02
작업을 해결했습니다. 이제 고객을 기반으로 순위를 매깁니다.
solved the tasks we have now rank the customers based
9:43:05
총 매출을 기준으로 하며, SQL은
on on their total sales so as you can see sql allows you
9:43:08
그룹화와 함께 윈도우 함수를 사용할 수 있습니다. 하지만
to use window function together with the group by but only
9:43:12
하나의 규칙이 있습니다. 윈도우 안에서 사용하는 모든 것은
with one rule anything that you are using inside the window
9:43:15
그룹화의 일부여야 합니다. 예를 들어, 우리는 매출의 합계를 사용하고
function should be part of the group by so
9:43:18
매출의 합계는 그룹화의 일부입니다. 맞죠?
for example we fulfill the rule because we are using the sum of sales and
9:43:21
그래서 이제 내가 가면, 합계를 사용하지 않음으로써 규칙을 깨게 됩니다.
the sum of sales is a part of the group by right
9:43:24
합계 대신 매출만 사용하면, SQL은 허용하지 않을 것입니다.
so now if i go i just break the rule by not using the
9:43:27
매출이 그룹화의 일부가 아니기 때문에
sum just using the sales so if i just remove the sum and use only the sales sql will not allow it
9:43:34
SQL은 이 점에 대해 매우 엄격합니다. 모든 것을 사용하려면
because the sales is not part of the group by so
9:43:37
하나의 쿼리에서 서브쿼리 없이 사용해야 합니다.
as you can see a scale is very strict with this if you want to use everything in
9:43:40
정확히 같은 열을 사용해야 합니다. 예를 들어,
one query without using like sub queries and so on
9:43:43
여기에서 매출 대신 고객 ID를 사용하면
you have to use the exact same columns so for example
9:43:46
고객 ID가 그룹화의 일부이므로 SQL은
if i go over here instead of sales i use the customer id so
9:43:50
허용합니다. 따라서 그룹화와 함께 윈도우 함수를 사용할 때 주의하세요.
since the customer id is a part of the group by sql
9:43:54
같은 열을 사용한다면 문제가 생기지 않을 것입니다.
can allows it so be careful using window function together with the group by as long as you are using the same columns nothing gonna go wrong
9:44:01
SQL이 허용할 것입니다. 이제 나는 가서 수정할 것입니다.
and isquels gonna allows it okay so now i'm just gonna go and fix
9:44:04
이제 실행해 보겠습니다.
this and let's run it so
9:44:07
이제 보시다시피, 이러한 단계를 따르면 정말 쉽습니다.
now as you can see it's really easy if you follow those steps first
9:44:10
먼저 그룹화를 사용하여 쿼리를 작성하세요. 윈도우 함수는 생각하지 마세요.
build the query using group by so don't you think about the window function
9:44:14
그룹화를 작성한 후, 다음 단계는 마지막 단계입니다.
just build the group by and then the next step the last
9:44:17
창 함수 정의 및 구축
one you go and define and build the window function
9:44:20
단일 쿼리로 분석 사용 사례 해결
so that you can solve really nice analytical use cases with a simple one query without having you to build like some queries
9:44:27
그룹화와 창 함수 사용
and so on you can go and use group by together with the window functions
9:44:30
SQL의 네 가지 규칙
all right guys so those are the four rules for the sql
9:44:33
윈도우 함수 모두
window functions all
9:44:38
좋은 친구들, 이제 SQL 윈도우 함수에 대한 간단한 요약을 해보겠습니다.
right friends so now let's have a quick recap about the sql window functions
9:44:41
정의부터 시작하겠습니다. 이는 계산을 수행하게 됩니다.
let's start with the definition it's gonna go and perform calculations like
9:44:45
데이터의 하위 집합에 대한 집계 작업을 수행하면서
aggregations on top of subset of data without
9:44:48
세부 정보를 잃지 않는다는 의미입니다. 즉, 집계를 수행할 수 있으며 동시에 세부 정보를 잃지 않습니다. 물론
losing the level of details so that means we can do aggregations and at the same time we are not losing the details now of course there is a lot
9:44:56
윈도우 함수와 그룹 바이 사이에는 많은 유사성이 있습니다.
of similarity between the window function and the group by but the
9:44:59
주요 차이점은 윈도우 함수가 그룹 바이와 비교할 때 매우
main difference is that window functions are very
9:45:02
강력하고 동적이라는 것입니다. 우리는 그룹 바이보다 훨씬 더 많은 함수를 가지고 있습니다.
powerful and dynamic compared to the group by we
9:45:05
하지만 데이터 분석을 하고 있고 고급 사용 사례가 있다면 윈도우 함수를 사용해야 합니다. 이는 복잡하고 고급 데이터 분석에 더 적합합니다. 반면에 간단한 질문이 있다면
have way more functions than the group by right but now if you are
9:45:09
간단한 데이터 분석을 위해 그룹 바이를 사용하여 집계 함수를 사용할 수 있습니다.
doing data analyzes and you have an advanced use case then you have to go and use window function it's more suitable for complex and advanced data analyzes but in the other hand if you have a simple question
9:45:21
물론 같은 쿼리에서 사용할 수 있습니다.
simple data analyzes then you can go and use the aggregate
9:45:24
같은 선택에서 그룹 바이와 윈도우 함수를 혼합할 수 있습니다.
functions using the group by and of course you can go and
9:45:27
단 하나의 규칙이 있습니다. 같은 열을 사용해야 합니다.
use them in the same query in the same select you
9:45:30
물론 첫 번째 단계는 그룹 바이를 수행한 다음 나중에 같은 쿼리에서 윈도우 함수를 수행하는 것입니다.
can go and mix the group by together with the window function with
9:45:34
이제 윈도우 구성 요소에 대한 다음 포인트로 넘어가겠습니다. 우리는 두 가지 주요 구성 요소가 있습니다. 첫 번째는
only one rule you have to use the same columns and
9:45:37
윈도우 함수이고 두 번째 부분은 윈도우
of course the first step is to do the group by and then later you do the window function in the same query and now to the next point about the window components we have two main components the first one is
9:45:48
정의입니다. 오버 클로즈를 사용하고 오버 안에서
the window function and the second part is the window
9:45:51
세 가지를 정의할 수 있습니다. 데이터를 나누고 싶다면
definition using the over close and inside the over
9:45:54
윈도우를 생성하기 위해 partition by를 사용할 수 있습니다.
close we can define three things if you want to divide the data
9:45:57
두 번째 섹션은 정렬을 위한 order by입니다.
to create windows you can use the partition by
9:46:01
정렬을 위해 사용됩니다.
the second section we have the order by in order
9:46:04
데이터를 정렬하고 마지막 부분에서 지정할 수 있습니다.
to sort your data and the last part you can go and specify
9:46:07
각 프레임 내에서 데이터의 하위 집합을
a subset of data like a frame within each
9:46:10
이제 마지막 부분으로 넘어가겠습니다. 규칙이 있습니다.
window now let's move to the last part we have rules for
9:46:13
SQL 윈도우 함수의 첫 번째 사항은
the sql window functions so the first thing is that if you have
9:46:16
두 개의 윈도우 함수 또는 여러 개의 윈도우 함수를
two window functions or multiple window functions you
9:46:19
함께 중첩할 수 없고, 가야 합니다.
cannot go and nest them together you have to go and
9:46:22
여러 개의 서브 쿼리를 사용해야 합니다. 다음 포인트는
use multiple sub queries the next point is
9:46:25
윈도우 함수를 오직
that you can use the window function only in the
9:46:28
SELECT와 ORDER BY 절에서만 사용할 수 있습니다. 예를 들어
select and the order by clause so for example you
9:46:31
WHERE 절과 함께 윈도우를 사용할 수 없습니다.
cannot use the window together with the where clause in order
9:46:35
데이터를 필터링하는 것에 대해 이야기하자면
to filter the data talking about filtering data how
9:46:38
SQL은 항상 윈도우 함수를 실행합니다.
sql gonna go and execute the window function it's always
9:46:41
SQL이 데이터를 필터링한 후, 알겠습니다.
after sql filter the data all right so those
9:46:44
SQL 윈도우 함수에 대한 기본 사항입니다.
are the basic stuff about the sql window function so with that we have
9:46:47
SQL의 윈도우 함수에 대한 기본 사항을 배웠습니다.
learned the basics about the window functions in sql and
9:46:50
다음으로 함수에 대해 이야기할 수 있습니다. 첫 번째 그룹은 윈도우
next we can start talking about the functions so the first group is the window
9:46:54
집계 함수이며, 여기서 데이터 요약 방법을 배울 수 있습니다.
aggregate functions and here we can learn how to summarize our data
9:46:57
특정 행 그룹에 대해, 자, 갑시다.
for a specific group of rows so let's go okay
9:47:04
우리 데이터에 다음 정보가 있다고 가정해 보겠습니다.
guys let's say that in our data we have the following informations we
9:47:07
월과 판매량이 있습니다. SQL에서 집계 함수를 적용하면
have the months and the sales now if you apply any aggregate functions in sql what can happen sql going to go through all rows of the window or the entire data and start aggregating the data.
9:47:19
결과적으로 SQL은 단일 집계 값을 제공합니다.
So that means in the result, in the output, SQL going to give you one single aggregated value.
9:47:25
SQL은 모든 값을 요약합니다. 예를 들어, 총 판매량은 175입니다.
SQL going to go and summarize all those values. And in the output, you're going to find, for example, here, the total sales are going to be 175.
9:47:32
또는 평균을 사용하거나 데이터를 세는 등의 작업을 할 수 있습니다.
Or you can use the average or count the data and so on.
9:47:35
집계 함수는 마지막에 윈도우 또는 전체 데이터에 대한 집계 값을 제공합니다.
So the aggregate functions going to deliver at the end one aggregated value for a window or for the entire data.
9:47:43
자, 이제 모든 집계 함수의 구문을 빠르게 살펴보겠습니다.
Okay so now let's have a quick overview of the syntax of all aggregate functions. Most of them follow the same rule.
9:47:49
그래서 먼저 평소처럼 함수 이름을 정의해야 하고, 이 예제에서는 평균을 사용합니다.
So first as usual we have to define the function name and in this example we have the average.
9:47:53
그 다음으로 내부에 표현식을 정의해야 합니다. 비워둘 수 없습니다.
Then to the next part we have to define inside it as well the expression. We cannot leave it empty.
9:47:59
여기서는 판매를 사용하고, 모든 함수에 대한 두 번째 규칙은 이 필드의 데이터 유형이 숫자여야 한다는 것입니다.
So here we are using the sales and the second rule for all functions beside the count the data type of this field should be a number.
9:48:07
고객의 이름이나 그런 것을 평균낼 수 없으므로 정의해야 합니다.
And this of course makes sense right so we cannot find the average of the
9:48:10
숫자를 정의한 다음, 다음으로 프레임을 정의해야 합니다.
first name of customers or something like that so we have to define
9:48:13
숫자를 정의한 다음, 다음으로 프레임을 정의해야 합니다.
a number then next we have to define the frame so
9:48:16
우리는 파티션 파이를 가지고 있으며, 선택 사항이므로 사용할 수도 있고, 사용하지 않을 수도 있습니다.
we have the partition pie and it is optional so you could
9:48:19
사용할 수도 있고, 사용하지 않을 수도 있으며, 다음으로 정렬 기준이 있습니다.
use it or leave it depends and then the next one we have the order by
9:48:22
선택 사항이며 필수는 아닙니다.
it is as well optional it is not a must or required so
9:48:26
사용할 수도 있고 사용하지 않을 수도 있습니다. 이는 집계 함수의 전체 정의가 비어 있을 수 있음을 의미합니다. 살펴보겠습니다.
you could use it or leave it that's mean the whole definition of the window could be empty for the aggregate functions let's have a look
9:48:33
모든 함수에 대해 카운트, 합계, 평균, 최소값이 있습니다.
to all functions so we have the count sum average min
9:48:36
최대값이며, 보시다시피 카운트만 모든 것을 허용합니다.
max and as you can see only the count accepts all
9:48:39
표현식이나 인수로서 모든 다른 데이터 유형은
data types as an expression or arguments all others
9:48:42
숫자를 데이터 유형으로 가져야 합니다. 그리고 모든 함수에 대해 파티션은 선택 사항입니다.
require you to have a number as a data type and for
9:48:45
주문 및 프레임도 마찬가지입니다. 따라서 여기서는 모든 것이 선택 사항입니다.
all functions the partition by is optional the same for
9:48:48
이제 우리가 할 일은 각 함수에 대해 깊이 파고들어 어떻게 작동하는지, 사용 사례는 무엇인지 이해하고, 물론 SQL에서 연습하는 것입니다. 첫 번째 함수인 카운트부터 시작하겠습니다.
order by and frame so everything is optional over here so
9:48:52
좋습니다. 카운트 함수는 무엇인가요? 정말 간단합니다. 각 윈도우 내의 행 수를 반환합니다.
now what we're going to do with that we're going to go and deep dive into each of those functions in order to understand how they work what are the use cases and of course going to practice in sql so we're going to start with the first one with the function count
9:49:08
각 서브셋 내에 몇 개의 행이 있는지 이해하는 데 도움이 될 것입니다.
okay so what is the count function it's really simple it's going to return
9:49:11
데이터의 서브셋 내에서 몇 개의 행이 있는지 이해하는 데 도움이 됩니다.
the number of rows within each window so it's going to help
9:49:14
자, 이제 SQL이 이 함수와 어떻게 작동하는지 이해해 봅시다. 좋아요, 여러분. 이제 우리는 다시 이 매우 간단한 주문 예제를 가지고 있습니다. 다음과 같은 정보가 있습니다. 제품과 판매가 있습니다.
you to understand how many rows do you have within each subset
9:49:17
이제 우리는 매우 간단한 작업을 해결하고자 합니다. 각 제품 내에 몇 개의 주문이 있는지요?
of data so now let's go and understand how sql works with this function all right guys so now we have again this very simple example for the orders and we have the following informations we We have the products and sales.
9:49:28
이를 해결하기 위해 카운트 함수를 다음과 같이 사용할 수 있습니다.
And now we want to solve a very simple task. How many orders do we have within each product?
9:49:33
카운트라고 말한 다음 인수나 표현식으로 별표를 전달합니다.
So in order to solve it, we can use the function count like the following.
9:49:37
그렇게 하면 SQL에게 테이블에 몇 개의 행이 있는지 세라고 지시하는 것입니다.
So we can say count and then we pass for it an argument or expression, the star.
9:49:42
이렇게 하면 SQL에 우리 테이블에 몇 개의 행이 있는지 세라고 지시하는 것입니다.
So with that, we are telling SQL, go and count how many rows do we have in our table.
9:49:47
하지만 우리는 제품으로 파티션된 윈도우 정의가 있습니다. 이제 무엇을 할까요?
But we have a window definition like this over partition by products. So now what is going to do?
9:49:52
우리는 데이터 세트를 두 개의 파티션으로 나눌 것입니다. 하나는 모자용, 다른 하나는 장갑용입니다.
We're going to go and divide the data sets into two partitions. We're going to have one partition for the caps and another one for the gloves.
9:50:00
그래서 우리는 데이터를 윈도우로 준비했습니다.
so with that square prepared our data into windows and we
9:50:03
각 윈도우 내에 몇 개의 행이 있는지 집계를 할 준비가 되었습니다.
are ready to do aggregations so how many rows do we have within each window
9:50:06
이 윈도우에는 세 개의 행이 있을 것입니다.
it's gonna be three so for this window it's gonna be three rows
9:50:09
다음 윈도우에도 세 개의 행이 있습니다.
and as well for the next window we have as well three rows
9:50:12
그래서 우리는 세 개, 세 개, 세 개를 가질 수 있습니다. 매우 간단하죠? 우리는 각 윈도우 내의 행 수를 찾고 있습니다.
so we can have three three and three it's very simple right guys we are just finding the number of rows within each window but now with
9:50:20
하지만 이제 집계 함수와 함께 null에 매우 주의해야 합니다.
aggregate functions we have to be very careful with the null
9:50:23
여기에서 보시다시피 count star에 대한 값입니다.
values for the count star as you can see over here
9:50:27
우리는 판매에 대해 아무것도 지정하지 않고 있습니다.
we are not specifying anything about the sales so we are just
9:50:30
행 수를 찾아달라고 말하는 것입니다. 즉, SQL은
saying find me the number of rows so that means sql will
9:50:33
null을 한 행으로 계산할 것입니다.
just count the nulls as one row so that means if we are using the
9:50:37
별표를 함수의 인수로 사용하면 null은 영향을 미치지 않습니다.
star as an argument for the function counts the null
9:50:40
null이 있든 없든 우리는 데이터 내의 행 수를 세고 있습니다.
will not affect anything so whether we have nulls or not we are
9:50:43
하지만 어떤 시나리오에서는 null을 무시해야 합니다.
just counting how many rows do we have inside our data
9:50:46
예를 들어, 내가 세고 싶은 경우를 생각해 봅시다.
but in some scenarios we should be ignoring the nulls
9:50:49
각 제품 내에 몇 개의 셀이 있는지 세고 싶습니다.
in our account for example let's say that i would like to count
9:50:52
즉, null이 있는 경우 세지 않아야 합니다.
how many cells do we have within each product that
9:50:55
이 작업을 수행하기 위해 우리가 할 것은
means if you have nulls it should not be counted so
9:50:59
여기에서 별 대신 필드 판매를 사용할 것입니다.
now in order to achieve this task what we're gonna do we're gonna use
9:51:02
이제 우리는 SQL에게 각 윈도우 내에 몇 개의 행이 있는지 맹목적으로 세지 말라고 말하고 있습니다.
instead of a star over here we're gonna have the field sales so now with this we are telling SQL don't just count blindly how many rows do we have within each window you should be very careful with the values
9:51:14
각 윈도우 내에 몇 개의 셀이 있는지 찾아보세요.
find how many cells do we have within each window
9:51:17
이제 첫 번째 윈도우에서 어떤 일이 발생할 수 있는지 봅시다.
so now let's see what can happen for the first window we
9:51:20
세 개의 셀이 있습니다. 세 개의 값이 있습니다.
have three cells so we have three values so the number of
9:51:23
행 수는 정확하지만 다음 윈도우에서는 몇 개의 셀이 있습니까?
rows is correct but for the next one how many cells do
9:51:26
우리는 두 개가 있습니다. 그래서 이 셀과
we have we have two so we have this cell and
9:51:30
그 다음 70이 있지만 마지막 것은 null이므로
then the 70 but the last one is null so it will not
9:51:33
카운트되지 않을 것입니다. 무시될 것입니다. 그래서 우리는
be counted it will be ignored that's why we're
9:51:36
출력에서 값 2를 얻을 것입니다. 우리는 두 개의 셀이 있습니다.
going to get in the output the value two we have two cells so
9:51:39
결과가 변경되었고 이제 null 값에 더 민감해졌습니다.
as you can see the result did change and we are now more sensitive
9:51:43
null 값에 더 민감해졌으니 카운트를 지정할 때 주의하세요.
to the null values so be careful what you are
9:51:46
이렇게 열 이름을 사용하면 null을 무시하지만 별표를 사용하면
specifying for the count if you are using a column name like this it
9:51:49
각 파티션 내에서 몇 개의 행이 있는지 찾을 것입니다.
will ignore the nulls but if you have a star it's just
9:51:52
결과를 나란히 비교하면
gonna go and find how many rows do we have within each partition
9:51:55
카운트 함수 내에서 열을 지정하면 null에 민감해져서 무시됩니다.
okay so now if you go and compare the results side by side you can see that
9:51:58
카운트 함수 내에서 별표를 사용하면 어떻게 될까요? SQL은 그것을 세기만 할 것입니다.
if you specify a column within the count function it's gonna be sensitive with the nulls so it's gonna ignore it and will not use it within the aggregations that's That's why we have here only two rows.
9:52:10
테이블 내의 행 수를 찾을 것입니다. 왼쪽에서 같은 작업을 수행할 수 있는 방법이 하나 더 있습니다.
But if you go and use the star within the count function, what can happen? SQL just going to go and count it.
9:52:15
별표 대신 1을 사용할 수 있습니다. 그래서 사람들은 count 1을 사용하고 같은 윈도우 함수를 사용할 수 있습니다.
So we're going to find the number of rows that we have inside our table. And there is one more way in order to do the same thing here on the left side.
9:52:23
우리는 정확히 같은 결과를 얻을 것입니다. null도 카운트되고 무시되지 않을 것입니다.
You can use instead of star, you can use a one. So you might find it somewhere that people are using count one and then the same window function.
9:52:31
그래서 이제 어떤 것을 사용해야 하는지 물어볼 수 있습니다. 1 또는 별표? 글쎄요, 상관없다고 말하고 싶습니다.
And we will get exactly the same result. So the nulls will be counted and will not be ignored.
9:52:36
그래서 이제 성능에 대해 생각하고 있다면, 두 가지 사이에 큰 차이를 찾지 못했습니다.
So now you might ask me which one should I use the one or the star? Well, I would say it doesn't matter, right? We are getting the same results.
9:52:42
그래서 두 가지를 모두 시도해보고 더 나은 성능을 제공하는 것을 선택할 수 있습니다.
And if you are thinking about the performance, I hardly find any differences between them.
9:52:46
카운트 함수는 다른 모든 집계 함수와 비교하여 특별한 경우가 있습니다. 모든 데이터 유형을 허용합니다.
So you can go and try both of them and stick with the one that is giving you like more better performance.
9:52:52
즉, 숫자, 문자, 날짜 등을 사용할 수 있습니다.
Now we have special case for the count function compared to all other aggregate functions. It allows any data type.
9:52:58
즉, 판매 대신 카운트를 위해 제품을 지정할 수 있습니다.
So that means we can use numbers, we can use characters, dates, and so on.
9:53:02
제품에 대해 몇 개의 행이 있는지 세어볼 것입니다. 그래서 여기서는 3이 될 것입니다.
So that means we can go and specify something like the products for the count instead of sales. So we can go over here and say products.
9:53:08
여기에는 null이 없으므로 이렇게 세어질 것입니다. 그래서 우리는 3개의 행이 있습니다.
And it's going to go and count how many rows do we have for the product. So it's going to be three over here.
9:53:13
우리는 데이터 내의 행만 세고 있습니다. 그래서 이것은 하나로 카운트되지 않을 것입니다.
And since here we don't have any nulls, it's going to go and count it like this. So we have three rows. And be careful here, we are not counting the unique rows.
9:53:21
그래서 우리는 캡이 세 번 있습니다. 그래서 여기서는 3이 됩니다.
We are just counting the rows that we have inside our data. So this will not be counted as one. And this as well would not be one.
9:53:28
그래서 이제 이 매우 간단한 예제를 통해 총 행 수를 찾습니다.
So we have three times the caps. That's why we have here three. okay
9:53:31
이제 이 매우 간단한 예제를 통해 총 수를 찾아보겠습니다.
so now we have this very simple example find the total number of
9:53:34
주문 수를 찾는 것은 매우 간단한 작업입니다.
orders this is very simple task in order to find how
9:53:37
몇 개의 행이 있는지, 테이블에 몇 개의 레코드가 있는지 알아보겠습니다.
many rows how many records do we have inside the table
9:53:41
주문을 해결해 봅시다.
orders so let's go and solve it so
9:53:44
주문 테이블에서 모든 데이터를 선택하는 것으로 시작하겠습니다.
let's start by selecting just star from the table orders
9:53:47
이렇게 하면 10개의 주문이 있습니다. 매우 간단하고 쉽습니다. 하지만 수천 또는 수백만 개의 행이 있다면 이렇게 할 수 없습니다.
without anything like this so as you can see we have 10 orders it's very simple it's very easy as well but now let's say that you have thousands or millions of rows you cannot do it like this by just checking
9:53:58
행을 확인하는 대신, 카운트 함수를 사용할 것입니다.
the rows what you're gonna do you're gonna go and use the function count so
9:54:01
여기에서 카운트 스타라고 말해보겠습니다.
we can go over here and say counts star and then let's
9:54:05
총 주문이라는 이름을 붙여보겠습니다.
give it a name total orders so let's
9:54:08
실행해 보겠습니다. 하나의 레코드만 얻었습니다.
go and execute it so as you can see we got only one record
9:54:11
10개의 주문이 있으므로 이것이 총 주문 수입니다.
one value we don't see any other details we
9:54:14
예를 들어, 우리는 몇 개의 주문이 있는지, 몇 명의 고객, 제품, 직원 등이 있는지 알 수 있습니다.
got the 10 orders so this is the total number of orders this is very helpful in order to understand the content of your data so this we call it overall analyzes or let's say having the big numbers about your business
9:54:27
이러한 큰 숫자는 비즈니스를 추적하고, 주문과 고객에 대해 얼마나 잘하고 있는지 이해하는 데 도움이 됩니다.
For example, how many orders do we have? How many customers, products, employees, and so on.
9:54:32
보고의 기본 사항입니다. 이제 주문 ID와 주문 날짜와 같은 세부 정보를 제공하겠습니다.
So having those big numbers can help us to track our business, to understand how well we are doing with the orders and with the customers and so on.
9:54:40
주문 ID와 주문 날짜를 선택하겠습니다. 물론 이렇게 할 수는 없습니다.
So this is the basics of reporting. Now let's go and extend our task by saying provide details such as the order ID and the order dates.
9:54:48
실행해 보겠습니다. 오류가 발생할 것입니다.
So let's go and do that. So select order ID, order dates. And now, of course, we cannot do it like this.
9:54:55
여기에서 선택의 세부 수준이 다릅니다.
So let me just execute it. We will get an error because
9:54:58
이 문제를 해결하기 위해 사용할 것입니다.
here we have different level of details in our select so in
9:55:01
오버 절을 사용하여 SQL에 이 정보를 제공합니다.
order to solve this what we're going to do we're going to use the
9:55:05
윈도우 함수입니다. 이제 실행해 보겠습니다.
over clause and with that we are telling SQL this
9:55:08
이로써 작업을 해결했습니다. 세부 정보가 있습니다.
is a window function so now let's go and execute it
9:55:11
주문 ID 또는 날짜가 있으므로 가장 높은 수준의 세부 정보입니다.
so with that you can see with that we have solved the task we have details we
9:55:14
가장 높은 수준의 집계가 있습니다. 총 주문 수입니다.
have the order id or the dates so this is the highest level of details since we have the order id and as well
9:55:21
전체 주문 테이블의 주문 수입니다.
have the highest level of aggregations we have the total
9:55:24
이제 계속 진행하여 작업에 더 많은 내용을 추가하겠습니다.
number of orders in the entire table orders so
9:55:27
이제 계속 진행하여 작업에 더 많은 내용을 추가해 보겠습니다.
now let's keep going and add more stuff to our task let's say that
9:55:30
총 주문 수를 찾고 싶습니다.
we want to find the total number of orders but
9:55:33
각 고객에 대해, 즉 이번에는
for each customers so that means this time we have
9:55:36
고객별로 데이터를 나누어야 합니다.
to go and divide our data by the customers so
9:55:39
고객 ID로 나누어 주문을 호출해 보겠습니다.
let's go and do that we're going to use as well a window function so count star over we have to divide the data using partition by and we're going to use the field
9:55:49
고객 정보도 보고 싶습니다.
customer id so let's call it orders by
9:55:53
쿼리에 추가할 것입니다.
customers and i would like to see as well the customer informations
9:55:56
이제 실행해 보겠습니다.
in the query that's why i'm gonna go and add it all right so
9:55:59
먼저 데이터를 나누어야 합니다.
that's all let's go and execute it now as we learned before that
9:56:02
네 명의 고객이 있습니다.
is clear first gonna go and divide the data so that means we have
9:56:05
첫 번째 고객 ID는 1이며, 3개의 주문이 있습니다.
four customers we're gonna get four windows the first window
9:56:08
마지막 고객 ID 4는 1개의 주문만 있습니다.
gonna be for the customer id number one and as you can see we have three rows that's why we have here three orders and And the same thing for the customer two, we have three orders, customer three, three orders,
9:56:20
이제 총 주문 수와 고객별 주문 수를 확인해 보겠습니다.
but only the last customer, the customer ID number four, we have only one row and one order.
9:56:25
우리는 서로 다른 범주 간의 비교를 하고 있습니다.
So now if you go and look to the total orders and the orders by customers, you can see now we are not doing the overall analysis.
9:56:31
이를 통해 고객의 행동을 이해할 수 있습니다.
We are doing like comparison between different categories. And of course, in this example, the category is the customers.
9:56:37
세 명의 고객이 동일한 수의 주문을 가지고 있습니다.
And with that, we can understand as well the behavior of our customers.
9:56:41
고객 ID 4는 1개의 주문만 있습니다.
So you can see that we have three customers that has exactly the same amount of orders. So they are very similar.
9:56:48
이 고객은 다른 고객들과 다른 행동을 보입니다.
But we have one extreme, which is the customer ID number four. This customer has only one order.
9:56:54
간단한 쿼리로 비즈니스를 분석할 수 있습니다.
So this is the only customer that has different behavior than all other customers.
9:56:59
데이터를 나누고 카운트를 사용하면,
So you see, with very simple query, we are able now to analyze our business and understand the behavior of our customers.
9:57:06
이제 함께 비교할 수 있습니다.
so if you divide the data by partition by and using count
9:57:09
다음으로 특별한 경우를 이해해 보겠습니다.
you can go and now compare stuff together all
9:57:12
카운트 함수와 함께 다룰 것입니다.
right so now let's keep moving next we're going to understand the special cases that we
9:57:15
고객의 총 수를 찾는 작업입니다.
have with the function count so now we have this very simple
9:57:19
모든 고객의 세부 정보를 제공해야 합니다.
task it says find the total number of customers and
9:57:22
추가로 모든 고객의 세부 정보를 제공해야 하므로, 해결하기 매우 쉬울 것 같습니다. 우리가 할 일은 모든 고객의 정보를 선택하는 것입니다.
additionally we have to provide all customers details so i think it's very easy to solve what we're going to do we're going to go and select star since we need all
9:57:30
판매 고객의 세부 정보를 살펴보면 다섯 명의 고객이 있습니다.
details from customers from sales customers so let's just have a look so we have five customers
9:57:37
그리고 함수는 count star over입니다.
and the function is count star over and
9:57:40
전체 테이블의 고객 수를 찾기 위해 데이터를 나눌 필요가 없습니다.
we don't have to divide the data since we have to find the total number of
9:57:43
그래서 새로운 것은 없습니다. 우리는 다섯 명의 고객이 있습니다.
customers for the entire table and it's going to be total customers
9:57:47
그래서 새로운 것은 없고, 우리는 다섯 명이 있습니다.
so nothing new that's it we have five
9:57:50
고객이 있고, 이제 우리가 이전에 배운 것처럼, 별표를 카운트 함수에 전달하면, 스케일에게 테이블 고객 안에 몇 개의 행이 있는지 세라고 말하는 것입니다.
customers and now as we learned before if you are passing the star to the count function what you are telling to scale is that just go and count how many rows do we have inside the table customers.
9:58:00
그래서 SQL은 그냥 가서 세기 시작할 것입니다. 우리는 다섯 명의 고객, 다섯 개의 행이 있다고 말할 것입니다.
So SQL just going to go and start counting. I'm going to say we have five customers, five rows.
9:58:05
그래서 데이터 안에 null이 있든 없든 상관없이, 성이나 점수에 null이 있든, 그냥 행의 수를 셀 것입니다.
So it doesn't matter whether we have nulls inside our data, like in the last name or the score, it's just going to count the number of rows.
9:58:12
이제 다음 작업이 있다고 가정해 보겠습니다. 고객의 총 점수를 찾으라고 할 것입니다.
So now let's say that we have the following task. It's going to say find the total number of scores for customers.
9:58:19
이 작업에서 필요한 것은 데이터 안에 몇 개의 점수가 있는지를 알아내는 것입니다.
So what do we need with this task is to find out how many scores inside our data.
9:58:22
보시다시피, 우리는 약 네 개의 점수가 있지만, 마지막 고객은 점수가 없습니다. 그래서 우리는 그것을 null로 가지고 있습니다.
So as you can see, we have around four scores, but the last customer doesn't have any score. So we have it as a null.
9:58:29
그래서 결과는 네 개여야 합니다. 우리는 이제 별표를 사용할 수 없습니다.
so the result should be four we cannot go now and use the star for
9:58:32
왜냐하면 우리는 다섯 개를 얻을 것이기 때문입니다. 우리는 점수를 세러 가야 합니다.
it because we're going to get five we have to go and count the
9:58:35
그래서 우리가 어떻게 할 것인지 봅시다. 우리는 또한 세겠지만 이번에는 점수를 셀 것입니다.
scores so let's see how we're going to do that we're going to count
9:58:38
그리고 윈도우의 정의는 비어 있을 것입니다. 그래서 총 점수와
as well but this time the score and
9:58:42
이제 실행해 보겠습니다. 그래서 이제 결과에서 우리는
the definition of the window going to be empty so total scores and
9:58:46
네 개의 점수를 얻었고, 이는 매우 정확합니다. 왜냐하면 SQL은 null을 무시했기 때문이고, SQL은 이제 하나의 열에만 집중하고 있으므로, 이러한 값에 집중하고 null은 세지 않을 것입니다.
let's go and execute this so now we can see in the results we got
9:58:49
이것은 데이터의 품질을 확인하는 데 정말 좋습니다. 그래서 데이터 안에 null이 없을 것이라고 기대한다고 가정해 보겠습니다.
four scores which is very correct because sql did ignore the null and sql now focusing only on one column so focusing on those values, the nulls will not be counted.
9:58:59
그래서 모든 기록을 수동으로 살펴보는 대신, 이렇게 고객의 총 수를 찾을 수 있습니다.
This is really great in order to check the quality of your data. So let's say that you are not expecting any nulls inside your data.
9:59:05
그리고 나서 총 점수의 수를 세러 갈 수 있습니다. 그리고 차이가 있다는 것을 알 수 있습니다.
So instead of going manually through the whole records, what you can do, you can go and find the total number of customers like this.
9:59:12
그래서 데이터를 확인함으로써, 나는 알 수 있습니다. 우리는 하나의 null이 있다고
And then you can go and count the total number of scores. And you can see there is a difference.
9:59:17
우리 데이터의 모든 기록을 확인하지 않고도 말할 수 있습니다. 그래서 우리는 그것으로
So by just checking the data, I can say, you know what, we have one null without
9:59:23
우리 데이터의 품질을 확인하고 매우 빠르게 이해할 수 있습니다.
checking every record in our data so with that we can check
9:59:26
점수 필드에 얼마나 많은 null이 있는지 확인할 수 있으며, 동일한 작업을 수행할 수 있습니다.
the quality of our data and understand very quickly how
9:59:29
필드 점수에 null이 몇 개 있는지 확인하고 같은 작업을 할 수 있습니다.
many nulls do we have in the field score and you can do the same
9:59:32
예를 들어, 첫 번째 이름을 보여드리겠습니다.
stuff for example for the first name show it to you so
9:59:35
이제 복사해서 첫 번째 이름이라고 해봅시다.
i'm just gonna go and copy this and let's say first name or
9:59:39
국가라고 해봅시다. 그래서 국가로 진행하겠습니다.
let's say country actually so i will go with the country
9:59:42
국가 총계를 진행하겠습니다. 결과를 확인해보면
so let's go with the country total countries so let's go and execute this so now if you check the result you can see we have
9:59:49
SQL은 국가에 집중할 것이고 null을 찾지 않을 것입니다.
So SQL is going to go and focus on the countries and it will not find any nulls.
9:59:54
여기 완전한 데이터가 있습니다. null이 없습니다.
So we have here complete data. We don't have any nulls because the total data is going to be
10:00:00
고객 수는
number of customers is equal to the total number of values within
10:00:03
국가와 관련된 데이터 품질이 매우 좋습니다.
the country and i can immediately find okay the
10:00:06
카운트 함수에 대해 배운 것이 있습니다.
data quality of the country is very good all right so now one
10:00:09
별표나 1을 사용하여 행 수를 셀 수 있습니다.
more thing about the count function that we have learned before we can use either
10:00:12
행 수를 세어보겠습니다. 별표 대신 1을 사용하겠습니다.
star or one in order to count how many rows do we
10:00:15
이제 실행해보겠습니다. 결과가 동일합니다.
have so let's just try it i'm just going to go and duplicate it and instead of having a star let's have one just going to give it a name here it's going to be one and you are star
10:00:26
이 두 쿼리 사이에 차이가 없습니다.
So let's go and execute it. So now if you check the output, we got exactly identical results.
10:00:31
보통 별표를 사용합니다. SQL 윈도우 함수 카운트의 중요한 사용 사례에 대해 이야기하겠습니다.
So there is no difference between those two queries. It's up to you. You can try it and check the performance.
10:00:37
데이터 분석에 사용하는 데이터는 보통 품질이 좋지 않습니다.
I usually go with the star instead of one. Okay, so now we're going to talk about a very important use case for the SQL window function count that I frequently use in my real projects.
10:00:46
데이터 품질 문제를 발견하지 못하고 정리하지 않으면,
The data that we use for data analysis has usually bad data quality.
10:00:51
분석을 하면 나쁜 결과를 낼 것입니다.
And if we don't find those data quality issues and we don't clean it before doing,
10:00:55
결과가 나쁘고 분석이 나쁩니다.
the analyzes what's gonna happen we're gonna deliver bad
10:00:58
결정이 나쁩니다. 일반적인 데이터 품질 문제는
results bad analyzes which can lead to bad
10:01:01
프로젝트에서 마주칠 수 있는 문제입니다.
decisions and one very common data quality issue that
10:01:04
중복입니다. 중복은 데이터 분석에 매우 나쁩니다.
you might encounter in your project or on your data is that having
10:01:08
중복을 발견하기 위해 SQL 윈도우 함수 카운트를 사용할 수 있습니다.
duplicates duplicates are really bad for doing data analyzes
10:01:11
주문 테이블에 중복 행이 있는지 확인합니다.
so now in order to discover or let's say identify the duplicates in our data we can go and use the sql window function count so now let's go and have some examples okay so now the task says
10:01:23
주문 테이블을 확인하면 많은 주문이 있지만 중복을 찾는 방법은?
check whether the table orders contains any duplicate rows. So how are we going to do that?
10:01:28
여기 테이블 주문을 확인해보면 많은 주문이 있지만 중복을 어떻게 찾을까요?
By checking now the table orders over here, we can see that there are many orders, but how to find out the duplicates?
10:01:34
첫 번째 단계는 테이블 주문의 기본 키가 무엇인지 이해하는 것입니다.
Well, the first step is to understand what is the primary key of the table orders.
10:01:39
우리가 보통 하는 일은 데이터 모델이 있는지 확인하는 것입니다.
So what we usually do, we go and check the data model if there is one.
10:01:43
예를 들어, 이 과정에서는 다음과 같은 데이터 모델이 있으며, 주문 ID가 주문의 기본 키로 정의되어 있음을 알 수 있습니다.
So for example, for this course, we have the following data model and we can see that it is defined that the order ID is the primary key for the orders.
10:01:51
제품 ID는 제품의 기본 키입니다.
the product id is primary key for the products so that
10:01:54
즉, 우리의 주문 테이블에서는 주문 ID가 기본 키입니다.
means for our table the orders we have the order id as
10:01:57
기본 키는 고유해야 하며 중복이 포함되어서는 안 됩니다.
the primary key and it should be unique it should not contain any
10:02:00
이제 데이터를 확인해 보겠습니다.
duplicates so now let's go to our data and
10:02:03
데이터를 살펴보면 주문 ID에 중복이 없다는 것을 알 수 있습니다.
check the order id by just looking at the data you can see that
10:02:07
모두 고유하므로, 하나, 둘, 셋, 넷 등입니다. 하지만 실제 프로젝트에서는 이렇게 할 수 없습니다. 기본 키가 고유한지 확인하기 위해 쿼리를 작성해야 합니다.
we don't have any duplicates right all of them are unique so
10:02:10
하지만 이제 기본 키는 일반적으로 고유하다고 말할 수 있습니다. 테이블을 구축할 때 DDL에서 정의할 수 있기 때문입니다.
we have one two three four and so on but of course in real projects you cannot do it like this you have to go and build a query in order to find out whether the primary key is unique.
10:02:19
그건 사실입니다. 이렇게 되어 있다면 중복을 찾을 필요가 없습니다.
But now you might say the primary keys are usually unique because we can define it in the DDL, in the rules of building the table.
10:02:27
하지만 일반적으로 데이터 분석에서는 많은 파일과 많은 데이터를 추가 데이터베이스에 내보내며, 이러한 규칙을 만들지 않습니다.
Well, that's true. If you have it like this, then you don't have to find any duplicates.
10:02:31
따라서 이제 소스에서 가져온 기본 키의 품질을 확인하기 위해
But usually in data analysis, we export a lot of files and a lot of data inside an extra database, and we don't build such a rules.
10:02:39
count 함수를 사용할 수 있습니다. 그러니 가서 작성해 보겠습니다.
So now in order to check the quality of the primary keys that you get from the
10:02:42
먼저 주문 ID를 세부사항으로 선택하겠습니다.
source we can use the count function so let's go and build
10:02:45
이제 다음 작업을 수행할 것입니다. count와
it i'm just gonna select the order id first as a detail
10:02:48
그런 다음 별표를 입력하고 창을 정의해 보겠습니다.
and now we're gonna do the following so count and
10:02:52
이것은 파티션될 것이며, 여기에서 필드는
then star and let's go and define the window
10:02:55
기본 키가 될 것입니다. 그래서 제가 확인하고 있는 주문 ID입니다.
so it's gonna be partitioned by and here the field gonna be the
10:02:58
이 필드의 품질을 이제 확인하고 있습니다. 중복이 포함되어서는 안 됩니다.
primary key so the order id i'm checking
10:03:01
이제 이름을 부여하겠습니다.
now the quality of this field this should not
10:03:05
기본 키 확인이라고 하겠습니다. 이제 제 기대는
contain any duplicates and we're gonna go and give it a name
10:03:08
이 결과가 최대 1이어야 한다는 것입니다.
check primary key so now my expectation at
10:03:11
기본 키로 파티션됩니다.
that's the result of this should be at maximum one
10:03:14
즉, 각 기본 키에 대해 하나의 행이 있다는 의미입니다.
that means we have one row for each primary key and that means
10:03:17
또한 고유하므로, 우리가 하나 이상의 항목이 있다면
as well it is unique so if we've got anything more than
10:03:20
하나 이상의 항목이 있다면 중복이 있다는 의미입니다. 쿼리를 실행해 봅시다.
one then it means we have duplicates let's go and run
10:03:23
쿼리를 실행해 보시면, 결과에서 각 기본 키에 대해
the query and as you can see in the results we get for each
10:03:26
기본 키 하나가 있으므로, 좋습니다. 즉, 데이터에 중복이 없습니다.
primary key one so that's great that means we don't
10:03:29
데이터에 중복이 없고 기본 키는 고유하므로, 테이블 주문이 깨끗합니다.
have any duplicates inside our data and the primary
10:03:32
테이블 주문이 깨끗하다는 의미입니다. 이제 중복이 없음을 확인해 봅시다.
key is unique so that that means the table orders is clean
10:03:36
중복이 없음을 확인해 봅시다. 여기에는 주문이라는 다른 테이블이 있습니다.
and we don't have any duplicates inside it now let's
10:03:39
주문이라는 다른 테이블을 확인해 보겠습니다. 먼저
check our database we have here another table called orders
10:03:43
데이터를 선택하겠습니다. 주문에서 선택합니다.
archive let's go and check the table so first i'm just
10:03:46
주문 아카이브에서 선택하겠습니다. 판매.주문 아카이브를
going to go and select the data so select from orders
10:03:49
확인하여 결과를 보겠습니다. 여기서 우리는
archive so sales dot orders archive let's
10:03:54
주문 테이블과 정확히 동일한 구조를 가지고 있습니다.
check the results and here we can see that we
10:03:57
주문 테이블과 정확히 동일한 구조를 가지고 있으므로
have exactly the same structure as the table orders so
10:04:00
이제 데이터 품질이 정말 깨끗한지 확인해 보겠습니다.
now let's go and check whether the data quality is real clean so
10:04:03
이제 우리가 할 것은 이전과 정확히 동일한 쿼리를 사용할 것입니다.
now what we're going to we're going to use exactly the same query as before but
10:04:07
주문 테이블 대신 주문 아카이브를 사용할 것입니다.
instead of using the table orders we're going to take the orders archive
10:04:10
그게 다입니다. 실행해 봅시다.
so that's it let's go and execute
10:04:13
데이터를 확인해 보면, 모든 곳에 중복이 없음을 알 수 있습니다.
it so now by checking the data you can see that we don't have everywhere
10:04:17
때때로 동일한 기본 키에 대해 두 개의 행이 있습니다.
one sometimes we have two rows for the same primary
10:04:20
정말 나쁜 상황입니다. 주문 ID가
key which is really bad so we have here for the order id
10:04:23
네 개일 때, 동일한 주문이 두 개 있습니다.
four we have two orders with the same order
10:04:26
주문 ID 여섯에 대해서도 마찬가지입니다.
id and as well for this order id six
10:04:29
세 개의 주문이 있으며, 이는 중복입니다.
we have three orders that means those stuff
10:04:32
중복이며 데이터 모델에 어긋납니다.
are duplicates and they are against our data model so
10:04:35
우리가 그것으로 무엇을 할 수 있는지
now what else we can do with that to generate a list specifically for
10:04:39
데이터 품질 문제에서 중복이 있는 경우
the data quality issue where we have duplicates so anything
10:04:42
그것을 수행하기 위해 서브 쿼리를 사용할 것입니다.
that has one we are not interested in it in
10:04:45
예를 들어, 별을 선택한다고 가정해 봅시다.
order to do that we're going to use the sub query so
10:04:48
첫 번째 쿼리를 서브 쿼리로 사용할 수 있습니다.
let's say select star from and then we
10:04:51
우리의 필터에서 체크 기본 키가
can use the first query as a sub query and
10:04:54
하나보다 큰 경우만 필요합니다.
we're going to say in our filter where the check primary key is
10:04:58
중복이 있는 경우만 필요합니다.
higher than one so that means i need only the order id where
10:05:01
중복이 있는 기본 키 목록이 있습니다.
we have duplicates so let's go and execute this now
10:05:04
주문 ID 4와 주문 ID 6이 있습니다.
i have a list with the primary keys where we have duplicates
10:05:07
윈도우 카운트 함수는 데이터 품질 문제를 찾는 데 훌륭합니다.
so we have the order id four and as well the order id six so
10:05:11
SQL 윈도우 함수 카운트에서 가장 중요한 사용 사례 네 가지입니다.
guys as you can see the window count function is wonderful in order to find data quality issues like the duplicates all right guys so those are the four most important use cases in the sql window function count.
10:05:22
첫 번째는 전체 분석을 수행하는 데 사용할 수 있습니다.
So the first one we can use it in order to do overall analyzes
10:05:26
카테고리 분석을 수행하는 데 사용할 수 있습니다.
or we can use it in order to do category analyzes like
10:05:29
고객 행동에 대한 분석을 수행했습니다.
we have done the analyzes on the customer behavior or
10:05:32
데이터 내의 널 값을 확인하는 데 사용할 수 있습니다.
another use case we can use it in order to check the nulls inside our data and the last use case we can use it in order to identify or discover the data quality issue duplicates in our data.
10:05:43
다음 함수는 합계입니다.
So now let's go and check the next function we have the
10:05:46
모두 합치기
sum all
10:05:51
좋아요, 이제 sum 함수가 무엇인지 이해해 봅시다. 매우 간단합니다.
right so now let's understand what is the sum function it's very simple
10:05:54
모든 값의 합계를 반환할 수 있습니다.
it can return the sum of all values within
10:05:57
각 창에서, 이제 SQL이 어떻게 작동하는지 이해해 봅시다.
each window so now let's go and understand how sql works
10:06:00
이 함수로, 좋아요, 매우 쉽고 우리는
with this function all right so this is very easy and we are using
10:06:03
같은 간단한 예제를 사용하고 있으며 이제 우리는
the same simple example and now we would like to find the
10:06:06
각 제품의 총 판매량을 찾고자 합니다. 따라서 우리는 다음과 같이 정의할 수 있습니다.
total sales for each product so we can define like
10:06:09
판매의 합계를, 우리는 찾고 있으므로
this sum of sales since we are finding the
10:06:12
총 판매량을 정의하고 이렇게 창을 설정합니다.
total sales and then we define the window like this over
10:06:15
제품별로 나누어 보겠습니다.
partition by products so as we learned is going to
10:06:19
모자와 장갑을 위한 두 개의 창으로 나누겠습니다.
go first and divide our data into two windows so
10:06:22
모자와 장갑을 위한 두 개의 창으로 나누겠습니다.
one window for the caps and another window for the gloves
10:06:25
이제 isql이 창을 정의한 후 데이터 집계를 시작합니다.
right so now after isql defined the windows it's going to go and
10:06:28
판매량의 합계를 구하기 위해 세 개의 판매량을 요약합니다.
start aggregating the data so the sum of sales that means for the first window we have the three sales and it's going to go and just simply summarize
10:06:36
모든 값을 더하면 20과
all those values so we are adding 20 plus
10:06:39
10과 5를 더하면 35가 됩니다.
10 plus 5 and we will get the result 35 so
10:06:43
출력에서 모든 곳에 35가 표시됩니다.
in the outputs we will get everywhere 35
10:06:46
첫 번째 창에 대한 내용은 이렇습니다.
so that's it for the first window and as you can see sql
10:06:49
각 창 내에서 데이터를 집계할 것입니다.
gonna go aggregate the data within each window separately
10:06:52
모자에 대한 데이터를 집계할 것이므로
so that means as we are aggregating the data for the caps sql
10:06:56
장갑에 대한 것은 확인하지 않습니다.
will not check anything with the gloves so they are completely
10:06:59
따라서 이제 다음 창으로 이동합니다.
separated so now it's gonna go for the next window
10:07:02
여기 두 개의 값과 null이 있습니다.
and here we have two values and null so again
10:07:05
여기 null은 무시됩니다.
here the null will just be ignored so what we're gonna have we're
10:07:08
30과 70을 더하면
gonna have 30 plus 70 and the total sales for
10:07:12
총 판매량은 100이 됩니다.
that's gonna be 100 so as you can see it is very
10:07:15
매우 간단합니다.
simple right so 100 100 and so guys
10:07:18
여기에는 특별한 경우가 많지 않습니다.
that's it it's really simple we don't have here like a lot of special cases like the count function it's only that it ignores the null in the calculation and as well the requirement here it allows only
10:07:30
정수만 사용할 수 있습니다.
integers or let's say numbers so we cannot go and say sum
10:07:33
제품은 숫자가 아니므로
the products since the products are not numbers they are characters
10:07:36
합계에 숫자만 사용할 수 있습니다.
so you can only use numbers for the sum
10:07:39
이제 몇 가지 작업과 사용 사례를 살펴보겠습니다.
function let's go now and have some tasks and some use cases
10:07:42
SQL에서 총 판매량을 찾는 연습을 해보겠습니다.
in order to practice in sql find the total sales across
10:07:45
모든 주문에 대한 총 판매량을 찾기 위해
all orders and as we'll find the total sales for each product
10:07:49
주문 ID와 주문 날짜와 같은 세부 정보를 제공해야 하므로, 주문 ID와 주문 날짜를 선택해 보겠습니다.
and additionally we have to provide some details like the order id and the order dates so let's go and do that select order id order dates
10:07:57
그리고 판매량도 가져오고 이제 모든 주문에 대한 총 판매량을 찾아야 합니다.
and let's get as well the sales and now we have to find the total sales across
10:08:00
모든 주문에 대한 총 판매량을 찾기 위해 윈도우 함수 합계를 사용할 것입니다.
all orders that means we're going to use the window function sum
10:08:03
판매량과 윈도우의 정의는
sales and the definition of the window going to
10:08:07
비어 있을 것이며, 데이터를 나눌 필요가 없기 때문에
be empty since we don't have to divide the data so that's
10:08:10
총 판매량을 선택해야 합니다.
its total sales and we have to select the table sales
10:08:14
주문 테이블을 선택해야 합니다.
orders so that's it let's go and execute
10:08:17
그래서 이제 실행해 보겠습니다.
it so that's as you can see we got all the details that we need and as well the total sales the summarization of all those sales in one field
10:08:26
보시다시피 필요한 모든 세부 정보를 얻었고, 총 판매량도 확인했습니다.
So with that, we have our overall analysis, one big number for our reporting.
10:08:30
이제 전체 분석이 완료되었습니다. 보고를 위한 하나의 큰 숫자가 있습니다.
We know how much sales we did made in the entire business. So now let's go for the next task.
10:08:35
전체 비즈니스에서 판매한 금액을 알고 있습니다. 이제 다음 작업으로 넘어가겠습니다.
It says total sales for each product. I think you know already what we're going to do. So sum of sales. And we're going to do it like this.
10:08:42
각 제품의 총 판매량을 나타냅니다. 우리가 할 일을 이미 아실 것 같습니다.
Partition by product ID. So that says we're going to call it sales by products.
10:08:51
판매량의 합계를 구할 것입니다. 이렇게 진행하겠습니다.
And with that, we are dividing the data by the product. So let's go ahead and execute it.
10:08:55
제품 ID로 파티션을 나누겠습니다. 즉, 제품별 판매량이라고 부를 것입니다.
so as you can see we don't have the product information so let's go and
10:08:58
그렇게 하면 데이터를 제품별로 나누게 됩니다. 이제 실행해 보겠습니다.
add the product id in the query just in order to
10:09:01
보시다시피 제품 정보가 없으므로
analyze the results so we can see from the data that the
10:09:04
쿼리에 제품 ID를 추가하여 결과를 분석하겠습니다.
winner is the product id 101 so as you can see we have here the highest sales if you compare it with the other products and the lowest one gonna be the products id 105.
10:09:15
데이터에서 제품 ID 101이 승자라는 것을 알 수 있습니다.
so as you can see we can use the window function sum together with the partition
10:09:18
다른 제품과 비교했을 때 가장 높은 판매량을 기록했습니다.
by in order to compare stuff to do comparison
10:09:21
가장 낮은 판매량은 제품 ID 105입니다.
between the products in order to understand the performance for example
10:09:24
보시다시피 윈도우 함수 합계를 파티션과 함께 사용할 수 있습니다.
of the products so it's really great analyzes for
10:09:27
제품 간의 성과를 비교하기 위해
the performance all right now we're gonna move to a very interesting use case for
10:09:31
비교 분석을 수행할 수 있습니다.
the aggregate functions not only for the sum but as well for the others it
10:09:34
제품의 성과를 이해하기 위해.
is the comparison analyzes okay so let's understand quickly what is the comparison use cases so it's gonna go and compare the current value for example let's say we are currently at the month of march and the sales is 30.
10:09:46
현재 판매량과 집계된 값을 비교할 것입니다.
So we're going to compare this value that current sales with an aggregated value.
10:09:51
예를 들어, 총 판매량을 합계 함수로 계산해 보겠습니다.
For example, let's say the total sales using the sum function.
10:09:54
현재 값을 총 판매량과 비교하면 어떤 일이 발생할까요?
So what happened if you compare the current value with the total sales you are comparing here or doing analysis called part to whole analysis?
10:10:02
이번 달의 판매량이 총 판매량에 비해 얼마나 중요한지 이해하는 데 도움이 될 것입니다.
We're going to help us to understand how important was the sales in this month compared to the total sales, or we can go and compare it to the best months to the highest value.
10:10:12
예를 들어, 가장 높은 값은 6월이며, 이번 달을 연중 최고의 달과 비교할 수 있습니다.
For example, the highest value is June, and we can go and compare this month with the best months of the year or to the lowest month in the year, or we can go and
10:10:20
현재 달의 판매량을 평균과 비교하여
compare the sales of the current month with the average in order to
10:10:24
우리가 일반적인 판매량보다 높은지 낮은지 이해할 수 있습니다.
understand are we above the typical sales or below
10:10:27
평균은 매우 중요한 분석입니다.
the average and this is very important analysis in order to
10:10:30
현재 데이터의 성과를 연구하고 이해하기 위해서입니다.
study and understand the performance of the current data
10:10:33
좋습니다, 사용 사례를 이해하기 위해 예제를 살펴보겠습니다.
all right let's have an example in order to understand the use case find
10:10:37
각 제품 판매가 총 판매에 기여하는 비율을 찾습니다. 그러니 단계별로 해결해 봅시다. 우리가 할 일은 선택하는 것입니다.
the percentage contribution of each product sales to the total sales so let's go and solve it step by step what we're gonna do we're gonna go and let's select
10:10:46
주문 ID와 함께 제품 ID와 판매를 가져옵니다.
the order id and as well let's take the
10:10:49
판매 주문에서 이렇게.
product id and the sales just like this
10:10:52
가서 실행해 봅시다. 자, 이제 결과에서 방정식의 첫 번째 부분을 얻었습니다. 우리는 판매를 가지고 있습니다.
from sales orders so let's
10:10:56
여기서는 특별한 것이 없습니다. 이제 총 판매가 필요합니다.
go and execute it okay so now as you can see in the results we got the first part of the equation we have the sales so nothing like a crazy over here now we need the total sales
10:11:06
모든 데이터에 대한 판매의 합계를 구할 것입니다. 정의는
over all data so what we're gonna do we're gonna have the sum of sales and the definition gonna be
10:11:13
비어 있습니다. 이것이 총 판매입니다. 이제
empty so this is the total sales let's
10:11:16
가서 실행해 봅시다. 이제 방정식에 필요한 모든 것이 있습니다.
go and execute it so now we have everything for the equation we
10:11:19
판매와 총 판매를 가지고 있으며, 이것으로 충분합니다.
have the sales and as well the total sales and that is enough
10:11:22
기여 비율을 찾기 위해서입니다.
in order to find the percentage of the contribution so
10:11:26
그 계산은 매우 간단할 것입니다. 우리는
the calculation for that is going to be very simple we're going to divide the
10:11:29
판매를 총 판매로 나눌 것입니다. 정말 간단합니다.
sales by the total sales so it's really simple
10:11:32
가서 그렇게 해봅시다. 판매를 총 판매로 나누는 것입니다. 그래서 우리는 전체 윈도우 함수를 복사할 것입니다.
let's go and do that it's going to be the sales divided by the total sales so we're going to go and copy the whole window function
10:11:39
여기에서 100을 곱할 것입니다.
over here and then we're going to multiply it with 100 so
10:11:43
그게 전부입니다. 가서 실행해 봅시다. 이제 당신은 다음과 같은 것을 알아차릴 것입니다.
that's it let's go and execute it so now you notice that in
10:11:46
출력에서 우리는 0을 얻었습니다. 이는 데이터 유형 때문입니다.
the output we got zeros this is because of the data type
10:11:49
이제 왼쪽에 있는 테이블로 가면
so now if we go to our table over here on the left side you
10:11:52
주문이 데이터 유형을 가지고 있음을 알 수 있습니다.
can see that the orders has the data type
10:11:55
정수형이기 때문에 정수를 나누면
of integer so if you divide integers you will not get
10:11:58
소수점이나 십진수를 얻지 못합니다. 데이터 유형을 변경해야 합니다. 이제 우리가 할 것은 그 중 하나의 데이터 유형을 변경하는 것입니다.
a float or decimal number you have to go and change the data type so now what we're going to do we're going to go and change the data type for one of them so
10:12:05
여기에서 판매에 충분하므로 다음 문을 사용할 것입니다.
it's enough for the sales over here so we're going to use the following statement
10:12:09
판매를 부동 소수점으로 변환합니다.
so cast sales as floats
10:12:12
그게 다입니다. 정수를 부동 소수점으로 변환하고 있습니다.
so that's it i'm just converting the integer to floats so
10:12:15
그게 다입니다. 이름을 주겠습니다. 이는 총의 백분율이 될 것입니다.
that's it let me just give it a name so it's going to be percentage of
10:12:19
총이므로 그게 다입니다. 실행해 보겠습니다. 이제 출력에서 우리는 총의 백분율 또는 기여의 백분율을 얻었습니다.
total so that's it let's go and execute it so now in the output you can see we got now the percentage of the total or let's say percentage of contribution
10:12:29
이제 그 숫자들을 다룰 것입니다. 왜냐하면
so now what we're going to do with that we're going to go around those numbers because we have
10:12:32
소수점이 많기 때문입니다. 이를 위해 반올림을 사용할 것입니다.
lot of decimals in order to do that we're going to use the round
10:12:35
이와 같은 함수로 두 개의
function like this then we're going to have two
10:12:38
소수점이 생기고 실행해 보겠습니다.
decimals and let's go and execute it
10:12:41
이제 보시다시피 읽기가 정말 쉬워졌습니다. 왜냐하면
so now as you can see it is really easier to read because
10:12:44
소수점이 두 개만 있기 때문에 주문 비율을 즉시 찾을 수 있습니다.
we have only two decimals and we can find immediately that the order rate
10:12:47
총에 가장 큰 기여를 하는 것입니다.
is the highest contributor to the total so
10:12:51
이것을 부분 대 전체 분석이라고 부릅니다. 우리는
this is what we call part to whole analyzes where we find
10:12:54
총의 백분율을 찾습니다. 이는 각 주문의 성과를 이해하기 위한 매우 일반적인 분석입니다.
the percentage of total it is very common analyzes in order to understand the performance of each order compared
10:13:01
총에 대한 것입니다. 이것은 창 함수가
to the total so this is an example how the window function
10:13:04
현재 값을 집계된 값과 비교하는 데 어떻게 도움이 되는지에 대한 예입니다. 자, 여러분, 창 함수 합계에 대한 모든 것입니다. 다음으로 평균 함수에 대해 이야기하겠습니다.
is helping us here to compare the current value with an aggregated value all right everyone so that's all for the window function sum next we're going to talk about the average function
10:13:18
좋습니다. 이제 평균 함수가 무엇인지 이해해 봅시다. 이름에서 알 수 있듯이 각 창 내의 값의 평균을 찾습니다. 이제 SQL이 어떻게 작동하는지 이해해 봅시다.
all right so now let's understand what is an average function as the name says it's going to find the average of values within each window so now let's go and understand how sql works
10:13:27
평균으로, 자 이제 매우 간단한 예제와 작업으로 돌아갑니다.
with the average all right so now back to our very simple example and the task
10:13:31
각 제품의 평균 판매를 찾으라고 합니다.
says find the average sales for each product so
10:13:34
정말 쉽습니다. 평균을 사용하고 열을 전달할 것입니다.
it's really easy we're going to use the average then pass to it the column
10:13:37
판매를 정의하고 이렇게 제품별로 파티션을 설정합니다.
sales and we define the window like this partition by products
10:13:40
첫 번째로 할 일은 윈도우를 정의하는 것입니다.
so the first thing that is going to go is to define the
10:13:43
우리의 데이터를 두 개의 파티션으로 나누기 위해 윈도우를 설정합니다.
window so it can divide our data into two partitions one
10:13:47
모자용과 장갑용으로 나누고, 이제 평균을 계산하는 방법을 모두 아시리라 믿습니다.
for the caps and one for the gloves and now i hope that everyone knows how to calculate the average so as you know that is going to go and summarize all the values and divide it by the
10:13:56
모든 값을 요약하고 행의 수로 나누는 것입니다.
number of rows so it's going to go and summarize 20 plus
10:13:59
20 더하기 10 더하기 5를 세 행으로 나누고,
10 plus 5 and divide it on three rows and
10:14:02
출력은 11이 될 것이므로 각 행에 대해 계산할 것입니다.
the output is going to be 11 so we're going to get it for each row
10:14:05
SQL이 모든 것을 무시한 것을 볼 수 있습니다.
so as you can see sql just ignored everything in
10:14:08
다음 윈도우에서는 모자에만 집중합니다.
the next window we are focusing only on the caps now
10:14:12
SQL은 두 번째 윈도우로 가서 같은 집계를 시작할 것입니다.
sql is going to go to the second window and start doing the same aggregations but here we have the special case of null so the null is going to be ignored in the calculations and we're going to have it like this It's going to say, you know what, 30 plus 70.
10:14:23
우리는 두 개의 행만 포함하고 있습니다.
And we are just including two rows. So it's going to be divided by two. And the average is going to be 50.
10:14:29
각 행에 대해 결과 50을 얻게 될 것입니다.
So we will get the result 50 for each row. And we are completely ignoring the nulls.
10:14:34
판매에서 null을 찾으면 0을 의미합니다.
But now we might be in a scenario where your users understand the business like this. If we find a null in the sales, it means a zero.
10:14:41
판매가 없으므로 실제로는 0입니다.
So there is no sales and it is actually a zero. But we store it in the database as a null.
10:14:46
따라서 제공한 평균은 정확하지 않습니다.
So that means the average that you have provided is not really correct. We have to divide by three.
10:14:51
null을 처리한 후 집계를 수행해야 합니다.
So that means first we have to handle the nulls before doing the aggregations, before finding the average.
10:14:57
이제 SQL에서 null을 처리하는 방법에 대한 전체 장이 있습니다.
Now we're going to have a whole chapter on how to handle nulls in sql what are
10:15:00
현재는 qualisk 함수를 사용할 것입니다.
the different functions but for now we're gonna go with the function qualisk
10:15:04
이제 우리는 판매를 사용하지 않을 것입니다.
okay so now what we're gonna do we will not use the sales as it
10:15:07
qualisk 판매를 사용하고 0으로 대체할 것입니다.
is first we're gonna handle the nulls so that means we're
10:15:11
SQL은 여기로 가서 null을 찾으면 0으로 대체할 것입니다.
gonna use the qualisk sales and replace it with zeros so as you can see we are not using immediately the sales we are handling it first and then we're gonna find the average
10:15:20
그것은 평균에 영향을 미칠 것입니다.
So SQL is going to go over here and if it finds any null, I'm going to go and replace it with zero.
10:15:26
이제 세 개의 행이 있습니다.
And that's going to have then an effect on our average over here. So it's going to be 30 plus 7 plus 70, but now plus zero.
10:15:33
따라서 두 개가 아닌 세 개로 나눌 것입니다.
And now we have three rows. So instead of dividing by two, it's going to go and divide it by three. And the total result is going to be like this, 33.
10:15:41
출력에서 각 행에 대해 33을 얻게 될 것입니다.
So that means we're going to have in the output 33 for each row.
10:15:44
그것은 이제 비즈니스의 기대를 충족하고 있다는 의미입니다.
And with that, we are now fulfilling the expectation from the business.
10:15:49
null이 있으면 0으로 처리되고 결과는
if you have a null it's going to be handled as zero and the result can be
10:15:52
더 정확하게 될 수 있습니다. 매우 까다롭습니다.
more accurate you see right it is very tricky if
10:15:55
데이터 분석 및 집계를 할 때 매우 주의해야 합니다.
you are doing data analyzes and aggregations be very careful with
10:15:59
null을 이해하고 비즈니스에 대한 의미를 이해해야 합니다.
the nulls understand them understand what they mean for the business
10:16:02
그들을 올바르게 처리해야 정확한 결과를 얻을 수 있습니다.
handle them correctly in order to get correct
10:16:05
이제 SQL을 연습하기 위해 돌아가 보겠습니다.
results in your analyzes so now let's go back in order to practice sql using some tasks and use cases okay so let's start with the basics we have the following task
10:16:14
모든 주문의 평균 판매량을 찾고
find the average sales across all orders and
10:16:17
각 제품의 평균 판매량도 찾고 세부사항을 잊지 마세요.
as well find the average sales for each product and don't forget the details
10:16:21
이제 단계별로 해결해 보겠습니다. 선택하세요.
so now let's go and solve it step by step so select
10:16:24
주문 ID, 주문 날짜를 선택하고
order id order date and let's
10:16:27
판매량을 가져오고 평균 판매량을 찾아봅시다.
get the sales as well let's go and find the average sales so it's going to be a window function and we have the sales inside it the usual stuff the window going to be empty so average
10:16:38
판매량을 테이블이라고 부를 것입니다.
sales we're going to call it the table going to be sales
10:16:41
주문이므로 이제 실행해 보겠습니다.
orders so that's it let's go
10:16:44
모든 것을 선택해야 합니다. 그래서 무엇을
and execute it oh we have to select everything of course so what
10:16:47
SQL이 출력에서 한 일을 요약할 것입니다.
sql did in the output we're going to go and summarize all those values
10:16:51
그 후 10으로 나누면 평균이 나옵니다.
and then divide it by 10 so with that we have the average
10:16:54
38의 평균 판매량이 매우 쉽습니다.
sales of 38 very easy so this
10:16:57
전체 분석이라고 부르는 것입니다. 다음으로 넘어갑시다.
is again what we call an overall analysis let's move to the next one find the average sales for each product so again we're going to go and build the window function like
10:17:06
각 제품의 평균 판매량을 찾고 창 함수로
this average sales over and we can divide it by product id and we're going to call it average sales
10:17:14
제품 ID로 나누고 평균 판매량이라고 부를 것입니다.
by products and we're going to go and add the product id
10:17:17
쿼리에 추가하겠습니다. 이제 실행해 보겠습니다.
in the query so that's it let's go and
10:17:21
무언가를 놓쳤습니다. 그래서
execute and we missed something here so it is
10:17:24
파티션을 다시 실행할 것입니다. 다음 데이터가 있습니다.
the partition by we're going to execute again so with that we have the following data so that was going to go and divide the data so for example
10:17:31
이 제품에 대해 네 개의 주문이 있습니다. 그래서 무엇이
for this product we have those four orders so what's
10:17:34
이 제품에 대해 우리는 네 가지 주문이 있으므로
gonna happen is we're gonna go and summarize the four values and
10:17:37
네 가지 값을 요약한 다음 네로 나누겠습니다. 그래서 여기 35가 있습니다. 다음 주문도 마찬가지로 세로 나누고 마지막 주문은 하나로 나누겠습니다. 그래서 60이 있습니다.
then divide it by four that's why we have here 35 the same thing for the next order it's gonna divide it by three and the last one is just gonna divide it by one that's why we have 60.
10:17:48
보시다시피 집계는 각 창에 대해 별도로 수행할 수 있습니다.
so as you can see the aggregation can be done separately for each window
10:17:51
그리고 이것은 서로 다른 제품 간의 평균을 비교하는 데 매우 좋은 방법입니다.
and this is as well very nice way in order to compare the
10:17:55
그렇다면 이제 널을 처리하는 방법을 배우기 위해 예를 들어 보겠습니다.
averages between the different products okay so now let's have
10:17:58
다음 작업을 가정해 보겠습니다. 고객의 평균 점수를 찾으세요.
an example in order to learn how to deal with the nulls let's
10:18:01
다음 작업을 수행한다고 말하십시오. 평균 점수를 찾습니다.
say that we have the following task find the average scores of
10:18:04
고객과 고객 ID 및 성과 같은 추가 정보를 표시합니다. 이제 해결해 봅시다. 우리는 현재 고객 테이블을 타겟팅하고 있습니다.
customers and show as well additional informations like the customer id and the last name so let's go and solve this we are now targeting the table customers
10:18:15
먼저 이렇게 선택하고 고객 ID와 성을 포함해 보겠습니다.
so let's just select it first like this and now let's go and include the customer id and the last
10:18:23
이름과 점수도 포함하겠습니다. 하지만 이번에는
name and let's have as well the score but this
10:18:26
평균 점수를 찾으려고 합니다. 그래서
time we're gonna go and find the average score so it's
10:18:29
평균 점수가 될 것이고 데이터를 분할하지 않기 때문에
gonna be the average score and since we don't partition the data
10:18:32
정의는 이렇게 두겠습니다.
we're gonna leave the definition like this and
10:18:35
평균 점수가 될 것이니 그게 전부입니다.
it's gonna be the average score so that's it
10:18:38
이제 실행해 보겠습니다. 보시다시피 평균 점수가 있습니다.
let's go and execute it so now as you can see we have the average score
10:18:41
625는 네 개의 값을 요약하고 네로 나누게 될 것입니다. 하지만 여기에는 null이 있으므로 이제 비즈니스를 이해하거나 물어봐야 합니다.
of 625 is going to go and summarize the four values and divide it by four but here we have a null so now we have to understand the business or ask about it
10:18:52
고객 점수의 null이 의미하는 것은 무엇입니까? 0인가요, 아니면 비어 있는 것인가요?
what the null means in the scores of the customers is it zero or is it something empty
10:18:57
0이라면 우리가 가진 평균이 잘못된 것입니다. 왜냐하면
if it's zero then the average that we have is wrong because
10:19:00
다섯으로 나누어야 하고 네로 나누면 안 되기 때문입니다.
it should be divided by five and not four so
10:19:04
0이라고 가정해 봅시다. 그러면 null을 처리해야 합니다.
let's say it's zero that means we have to go and handle the
10:19:07
그래서 지금 우리가 할 것은 coalesce 함수를 사용할 것입니다.
nulls so what we're going to do now we're going to go and use the function coalesce
10:19:10
그래서 점수에 대해 coalesce하고
so coalesce and for the score and
10:19:14
null을 0으로 바꿉니다. 고객 점수가 있습니다. 이제 실행해 보겠습니다. 보시다시피 값이 있으면 정확히 같은 값이지만 null이 있으면 0으로 대체됩니다.
replace the null with zero so you are the customer score let's go and execute this so now So now as you can see if there is a value it's going to be exactly the same value but only if we have null it's going to be replaced with zero.
10:19:25
이제 평균을 수정해 보겠습니다. 이렇게 할 것입니다.
So now let's go and correct the average. I'm just going to do it like this.
10:19:29
전체를 복사하겠습니다. 하지만 이제 점수를 사용하는 대신 null을 처리한 점수를 사용할 것입니다.
So let's go and copy the whole thing but now instead of using the score we're going to use the score that is handled with nulls.
10:19:37
그래서 이제 전체를 복사하러 가는데, 점수를 사용하는 대신 null을 처리하는 점수를 사용할 것입니다.
So I'm just going to go and replace it like this. So here without nulls. So let's go and execute it.
10:19:44
그래서 이제 출력에서 더 유효한 결과를 얻고 있음을 알 수 있습니다. 이는 null이 0을 의미하는 경우에만 해당됩니다.
So now as you can see we are getting more valid result at the output compared to the previous one and this is only for the case if the null means 0.
10:19:52
그래서 여러분, 집계 작업을 할 때 null에 매우 주의해야 합니다. 집계를 수행하기 전에 올바르게 처리해야 합니다.
So guys as you see be very careful with the nulls especially if you are doing aggregations and handled correctly before doing any aggregations like
10:20:00
평균, 알겠습니다. 마지막 사용 사례로 넘어가겠습니다.
the average all right moving on to the last use case we have the
10:20:03
비교 분석이며, 작업은 평균보다 높은 모든 주문을 찾으라고 합니다.
comparison analysis and the task says find
10:20:06
판매가 평균보다 높은 모든 주문
all orders where the sales are higher than the average
10:20:09
모든 주문의 판매를 비교해야 합니다. 즉,
sales across all orders so that means we have
10:20:12
현재 판매와
to go and compare the current sales with the
10:20:15
집계된 값과 비교해야 합니다. 이번에는 판매의 평균입니다. 이제 단계별로 진행해 보겠습니다.
aggregated value and this time the average of sales so now let's go
10:20:18
그래서 단계별로 진행할 것입니다. 물론 주문 ID를 선택하고, 제품 ID를 가져와야 하며, 현재
and do it step by step so what we're gonna do we're gonna go and select of course the order id what do we need let's take the product id and we need the current
10:20:27
판매를 가져와야 합니다. 그래서 판매는 그대로 될 것이고
sales so it's going to be the sales as it is and
10:20:30
지금은 이게 전부입니다. 판매 주문에서
that's it for now so from sales orders
10:20:33
이제 결과를 확인하면 첫 번째 부분을 얻었음을 알 수 있습니다.
so that's it let's go and execute
10:20:36
우리는 각 주문의 판매를 가지고 있습니다. 이제 두 번째 부분, 모든 주문의 평균 판매가 필요합니다.
it so now by checking the result you can see that we got the first part of the
10:20:40
이를 위해 우리는 윈도우 함수 평균을 사용할 것입니다. 모든 주문을 대상으로 하므로 비어 있을 것입니다.
equation right we have the sales for each order now we need the second part the average sales across all orders in order to do that we're going to go and use the window function average
10:20:49
그래서 평균 판매라는 이름을 주겠습니다. 이제 실행해 보겠습니다.
sales and we're going to use over since across all orders that means it's going to be empty so let's So let's give it a name average sales.
10:20:57
출력에서 평균 판매를 얻었습니다. 38이 될 것입니다.
So let's go and execute it. So now in the output, we got the average sales. So it's going to be 38.
10:21:03
이제 평균보다 높은 모든 주문이 필요합니다.
So now we need all the orders that are higher than the average.
10:21:07
예를 들어, 주문 1은 평균보다 높지 않지만, 주문 4는 평균보다 높습니다.
So as you can see, for example, the order one is not higher, but the order four is higher than the average.
10:21:13
데이터를 필터링하기 위해서는 where 절에서 윈도우 함수를 사용할 수 없습니다.
So in order to filter the data, we cannot use the window function in the where clause, right?
10:21:18
그래서 우리가 할 일은, 안타깝게도, 서브쿼리를 사용할 것입니다.
So what we're going to do, sadly, we're going to go and use the subquery.
10:21:22
그래서 이렇게 될 것입니다. select star from
so it's going to be like this select star from and
10:21:26
그런 다음 조건을 외부에서 정의할 것입니다.
then we're going to define the condition outside
10:21:29
서브쿼리에서 판매가 평균 판매보다 높은 곳이 될 것입니다.
the subquery so it's going to be where the
10:21:32
그래서 평균 판매보다 높은 판매가 될 것입니다.
sales is higher than the average sales
10:21:36
그래서 그게 다입니다. 가서 실행해봅시다.
so that's it let's go and execute
10:21:39
이제 보시다시피 매우 간단합니다. 모든 주문을 받았습니다.
it and now as you can see it's very simple we got all the orders that
10:21:42
평균보다 높은 주문을 받았습니다. 모든 판매가 평균보다 높습니다. 첫 번째 쿼리에서 모든 작업을 수행할 수 있다면 좋겠지만, 그럴 수 없기 때문에
are higher than the average right so you can see all those sales are higher than the average it would be nice if we can do all those stuff in the first query but since we cannot do that
10:21:52
하위 쿼리를 사용하여 데이터를 필터링해야 합니다.
we need to use the sub queries in order to filter the data
10:21:56
그 후 우리는 그것의 중요성을 이해할 수 있습니다.
afterward so that we can understand the importance of that
10:21:59
비교 분석을 합니다. 예를 들어, 여기서 우리는 찾고 있습니다.
comparison analyzes for example here we are finding
10:22:02
또는 데이터가 평균 이상인지 평가하고 있습니다.
or evaluating the data whether they are above the average
10:22:05
또는 평균 이하인지 평가하고 있습니다. 이것은 비즈니스 분석에서 매우 중요합니다. 자, 여러분, 이제 창 함수 평균에 대한 모든 내용은 여기까지입니다. 다음에는 두 가지 매우 흥미로운 함수인 최소값과 최대값에 대해 이야기할 것입니다.
or below the average and this is very important in the business analyzes all right everyone so that's all for the window function average next we're going to talk about two very interesting functions the min and max
10:22:21
자, 여러분, 최소값과 최대값 함수는 무엇인가요? 매우
all right guys so what is min and max functions they are very
10:22:24
간단하지만 매우 강력한 분석 함수입니다.
simple but yet very powerful functions for analytics so
10:22:27
최소값은 단순히 최소값을 반환할 수 있는 함수입니다.
the min simply is the function that can return the minimum
10:22:30
또는 창 내에서 가장 낮은 값을 말할 수 있습니다.
or let's say the lowest value within a window where
10:22:34
최대값은 정확히 반대입니다. 최대값 또는 창 내에서 가장 높은 값을 찾을 것입니다. 이제 SQL이 이러한 함수와 함께 어떻게 작동하는지 이해해 봅시다.
the max it's exactly the opposite it's going to find the maximum value or the highest value within a window so now let's go and understand how SQL works with these functions.
10:22:44
좋습니다. 이제 동일한 데이터가 있고 두 가지 작업이 있습니다.
All right so now we have the same data and we have two tasks.
10:22:47
첫 번째는 각 제품의 최저 판매량을 찾는 것이고, 두 번째는 나란히 각 제품의 최고 판매량을 찾는 것입니다.
First we have to find the lowest sales for each product and the second one side by side we would like to find the highest sales for each product.
10:22:55
그래서 우리는 최소값과 최대값을 사용할 것입니다. 보시다시피 구문은 매우 간단합니다.
So we're going to go and use the min max and as you can see the syntax is very simple.
10:22:59
판매량의 최소값을 구하고, 파티션은 제품별로 할 것입니다. 여기에서도 같은 방식으로 최대값을 구할 것입니다.
Min the sales and then the partition going to be by the product and here as well the same stuff but having the max.
10:23:05
좋습니다. 이제 SQL이 첫 번째 쿼리를 어떻게 실행하는지 봅시다. 보통처럼 먼저 데이터를 준비할 것입니다. 그래서 데이터를 두 개로 나눌 것입니다.
Okay so now let's see how SQL going to execute the first query. As usual first it's going to prepare the data so it's going to split the data into two
10:23:11
하나는 모자용, 다른 하나는 장갑용입니다.
windows one for the caps and another one for the gloves and
10:23:15
그 후 각 창에서 최저 판매량을 검색할 것입니다.
after that it's going to search for the lowest sales within
10:23:18
각 창을 따로따로. 첫 번째 창에서는 다음과 같은 값이 있습니다: 20, 10, 5.
each window separately so for the first window we have
10:23:21
물론 최저값은 5가 될 것이므로 SQL은
the following values 20 10 and 5 and
10:23:24
여기와 모든 곳에서 이 값을 찾을 것입니다.
of course the lowest value is going to be the 5 so that's why sql is
10:23:27
여기와 모든 곳에서 이 창을 찾으려고 합니다.
going to find it over here and everywhere for this window
10:23:30
그 값은 5가 될 것이므로 우리는 제품 캡의 최저 판매로 설정했습니다. 이제 장갑을 위한 다음 창으로 넘어가겠습니다.
it's going to be the value 5 so we have it as the lowest sales for the product caps so now we're going to jump to the next window for the gloves
10:23:37
값이 5가 될 것이므로 제품 캡의 최저 판매량으로 설정합니다. 이제 장갑에 대한 다음 창으로 넘어갑니다.
and start searching the values so as you can see we have 30 70
10:23:40
null은 무시될 것이므로 이제
and null null will be ignored so now will
10:23:43
최저 값으로 간주되지 않을 것입니다. 그래서 이스라엘
not be considered as the lowest value so israel
10:23:46
30으로 최저 판매량을 찾으려고 합니다. 그래서 실제로
gonna find the lowest sales with the 30 so it's gonna be actually
10:23:49
이 창의 첫 번째 행과 값입니다.
the first row within this window and the value
10:23:53
각 행에 대해 출력은 30이 될 수 있습니다. 그래서
the output can be 30 for each row so that's
10:23:56
매우 간단합니다. 이제 다음으로 넘어갑시다. 같은 내용을 사용하지만
it it's very simple right now let's move to the next one we have the same stuff but using
10:23:59
최대값을 사용하여 데이터가 파티션됩니다. 첫 번째 파티션에 대해
max so the data is partitions and for the first partition
10:24:02
가장 높은 값이 무엇인지, 첫 번째 행이 될 것입니다.
what is the highest value it's gonna be the first row
10:24:05
20이므로 찾을 것이고
right the 20 so it's gonna find it and
10:24:08
출력에서 이 판매량 20을 얻을 것입니다.
in the output we will get the highest sales 20 for this
10:24:11
창이 끝난 후 두 번째 창으로 가서 가장 높은 값을 검색합니다. 여기에는 30과 70이라는 두 값이 있습니다. 70이 될 것입니다.
window and then it's gonna go to the second window and search for the highest value so here we have two values 30 and 70 and it's gonna be the 70 right so it's gonna point it over here and in the output we will get everywhere 70.
10:24:24
그래서 여러분, 정말 간단합니다. 이제 평균 시나리오로 돌아가 보겠습니다. 우리 비즈니스에서는 null을 판매량의 0으로 이해합니다. 즉, 먼저 null을 처리하고 0으로 바꿔야 합니다.
so guys it's really simple right now let's back to our scenario in the average where in our business we understand nulls as zero in the sales so that That means first we have to handle the nulls and replace it with zero.
10:24:35
그런 다음 값을 검색하러 갈 것입니다. 무슨 일이 일어날까요? null을 0으로 바꿀 것입니다.
And then we're going to go and search for the value. So what's going to happen? We're going to go and replace nulls with zero.
10:24:41
최대값에 대해서는 아무것도 변하지 않을 것입니다. 가장 높은 값은 70이 될 것입니다. 같은 출력을 얻을 것입니다.
For the max, nothing going to change. The highest value is going to be 70. And we're going to get the same output.
10:24:46
하지만 최소값에 대해서는 이제 새로운 최저 값이 있습니다. 더 이상 30이 아닙니다. 실제로는 0입니다.
But for the min, now we have new lowest value. So it's not anymore the 30. It's actually the zero.
10:24:53
SQL은 여기에서 30을 null로 바꿀 수 있습니다.
So SQL can go over here and replace the 30 with nulls.
10:24:57
null은 제품 장갑의 최저 판매량입니다.
So nulls is the lowest sales for the product gloves
10:25:01
다시 말해, null은 매우 까다롭고 이러한 함수는
so again guys the nulls are very tricky and those functions
10:25:04
null에 대해 매우 민감합니다. null이 의미하는 바를 이해하고 올바르게 처리하여 정확한
are really sensitive with the nulls understand what the
10:25:07
결과를 출력에서 얻을 수 있도록 합니다. 그래서 이제 SQL로 돌아갑시다.
nulls means and handle it correctly so that you get correct
10:25:10
정확한 결과를 얻기 위해 올바르게 처리합니다. 이제 SQL로 돌아가서
results in the output so that's it let's go back to SQL to
10:25:13
작업과 사용 사례를 제공하여 SQL을 연습해 봅시다. 모두 준비되셨나요? 기본적인 것부터 시작하여 모든 주문의 가장 높은 판매량과 최저 판매량을 찾습니다.
have some tasks and use cases in order to practice SQL all right everyone let's start with the basic stuff find the highest and lowest sales of all orders and as
10:25:22
각 제품의 가장 높은 판매량과 최저 판매량을 찾을 것입니다.
will find the highest and lowest sales for each product and
10:25:25
추가 정보를 제공해야 하므로 가서 해결합시다. 주문 ID를 선택합니다.
we have to provide additional informations so let's go
10:25:29
주문 ID를 선택하고 해결합시다
and solve it select order id order
10:25:32
날짜와 제품 ID를 가져옵시다
date and let's take as well the product id now let's
10:25:35
모든 주문의 최고 판매량을 찾아야 합니다
find the highest sales of all orders it's going to be the
10:25:38
판매량에 대한 최대 함수와
max function for the sales and the
10:25:41
모든 주문의 빈 창 함수가 될 것입니다
window function going to be empty sense of all orders so you
10:25:44
최고 판매량을 찾았으니 이제 모든 주문의 최저 판매량으로 가봅시다
are the highest sales let's go for the lowest sales of all orders it's going to be exactly the opposite the main
10:25:50
판매를 위한 기능입니다.
function for sales over then we
10:25:53
가장 낮은 판매량이 있으므로 자본을 더 크게 만들겠습니다. 테이블 판매 주문을 선택합시다. 그래서 실제로 판매를 설정해 보겠습니다.
have the lowest sales so i'm just gonna make it bigger capital so let's select the table sales orders so i think that sets let's have as well the sales actually
10:26:06
좋습니다. 이제 가서 실행해 보겠습니다. 지금 이건 매우 간단합니다.
all right so now let's go and excuse it so now this is very simple right
10:26:09
이것이 전체 판매입니다. 우리가 가진 가장 높은 판매량은 주문 8의 90입니다. 보시다시피 이제 가장 높은 수치를 가지고 있습니다.
this is the whole sales what is the highest sales we have the 90 of the order 8 so as you can see we have now the highest
10:26:16
판매량은 90이고 가장 낮은 판매량은
sales 90 and the lowest sales is the
10:26:19
10입니다. 첫 번째 주문이 가장 낮습니다. 그래서 매우 쉽습니다.
10 the first order is the lowest so it's very easy
10:26:22
이제 제품에 대해 같은 작업을 반복하겠습니다.
now we're gonna go and repeat the same stuff for the product so
10:26:26
제품 ID로 데이터를 분할해야 합니다. 그래서
we have go and partition the data by the product id so what
10:26:29
제가 할 일은 그냥 복사하고 붙여넣는 것입니다. 첫 번째는 제품 ID로 분할될 것이며, 제품별로 가장 높은 판매량을 보여줄 것입니다. 다음은 같은 작업이 될 것입니다.
i'm gonna do i'm just gonna go and copy paste stuff around so the first one gonna be partition by the product id so highest sales by product and the next one gonna be the same stuff
10:26:41
제품별로 복사하고 붙여넣기입니다.
copy paste by the product so
10:26:44
그게 전부입니다. 이제 실행해 보겠습니다.
that's it let's go and execute it so
10:26:47
이제 다시 데이터가 제품별로 분할되고 나뉘게 됩니다.
now again the data going to be partitions and divided by the product
10:26:50
첫 번째 창에서 가장 높은 판매량은 무엇인가요?
so for the first window what is the highest sales
10:26:53
90이 될 것이고 가장 낮은 판매량은 10이 될 것입니다. 그래서 정확히
it's going to be the 90 and the lowest sales is going to be the 10 so it's exactly
10:26:57
전체와 같습니다. 이제 두 번째로 가봅시다.
like the overall right now let's go to the second
10:27:00
여기에서 가장 낮은 판매량 또는 가장 높은 판매량을 볼 수 있습니다.
window over here we can see that the lowest or the highest sales
10:27:03
첫 번째는 60이고, 이번에는 가장 낮은 것이 15입니다. 이것은 SQL이 실행될 수 있음을 보여주기 위해 훌륭합니다.
is the 60 the first one and the lowest this time is 15 and this is great in order to see that the sql can execute
10:27:10
각 창에 대해 이러한 기능을 각각 별도로 실행할 수 있습니다.
each of those functions for each window separately so
10:27:13
마지막 창으로 가봅시다. 재미있는 창입니다. 판매량은 60입니다.
let's go to the last window it's funny one so the sales is 60 and
10:27:16
우리는 단 한 줄만 있으므로 가장 높을 것이고
we have only one row so it's going to be the highest and as well the
10:27:19
최저 판매량이 될 것입니다. 이를 통해 각 제품의 범위를 정의할 수 있습니다.
lowest sales so with that as you can see we can define a range for
10:27:22
각 제품의 범위는 서로 다릅니다. 예를 들어, 이 제품 101의 범위는 10에서 90까지입니다.
each product and the ranges are different from each product to another one for example for this product 101 the range from 10 until 90 but for the second product we have it between 15 and 60.
10:27:34
자, 다음으로 넘어가 보겠습니다. 이 창에서 제가 가장 좋아하는 것 중 하나입니다.
okay guys let's move to the next one which is one of my favorites in the window
10:27:37
함수에서 데이터를 필터링하는 방법입니다.
function where we filter the data using the min
10:27:40
최대 함수입니다. 다음 작업을 수행해 보겠습니다.
max functions let's have the following task it says show
10:27:43
가장 높은 급여를 받는 직원을 보여줍니다.
the employees who have the highest salaries so
10:27:46
이것은 매우 간단하게 들리지만, 창 함수를 사용하여 해결할 수 있습니다.
this sounds very simple but we can use the help of window
10:27:49
이제 직원 테이블로 작업하고 있습니다.
functions in order to solve it so now we are working with the table employees
10:27:53
데이터를 선택해 보겠습니다. 선택합니다.
let's just select the data so select from
10:27:56
판매 직원에서 선택합니다. 이제 다섯 명의 직원이 있습니다.
sales employees so that's it let's go and execute it so now we have five employees and we
10:28:04
서로 다른 급여를 가지고 있습니다. 가장 높은 급여를 찾아봅시다.
have those different salaries let's go and find the
10:28:07
최대 급여를 찾습니다.
highest salary so max salary and
10:28:11
창 함수를 사용해 보겠습니다. 하지만 데이터를 분할하지 않습니다.
let's use the window function over but we don't partition the data
10:28:14
전혀 분할하지 않으므로 이렇게 됩니다. 가장 높은 급여입니다.
at all so it's going to be like this highest salary
10:28:17
이제 실행해 보겠습니다. 결과를 확인하면 '가장 높은 급여'라는 새 열이 생겼습니다.
so let's go and execute it and now by checking the results we got a new column called highest salary and inside it we have the 90k so if you check those five salaries you can see that
10:28:28
가장 높은 급여는 마이클이라는 직원에게서 나왔지만, 여전히
the highest is from the employee michael but still
10:28:32
작업이 해결되지 않았습니다. 가장 높은 급여를 가진 직원만 보여줘야 합니다.
the task is not solved we have to show only the employees who
10:28:35
그래서 우리는 데이터를 필터링해야 합니다.
have the highest salaries so we have somehow to filter the
10:28:38
이 직원을 보여주기 위해 서브 쿼리를 사용해야 합니다.
data and only show this employee so in
10:28:41
WHERE 절에서 창 함수를 사용할 수 없기 때문에, 선택합니다.
order to do that we have to use the sub queries since
10:28:44
별을 선택합니다. 그리고 첫 번째 쿼리를 실행합니다.
we cannot use the window function in the where clause so what we're going to do select star from and then our first query
10:28:52
내부 쿼리가 될 것입니다. 다음 조건이 있습니다.
going to be the inner query so we
10:28:56
급여는 가장 높은 급여와 같아야 합니다.
have the following condition it's going to be the salary should
10:29:00
매우 간단합니다. 이를 통해 우리는 급여를 가장 높은 급여와 비교하고 있습니다.
be equal to the highest salary so
10:29:03
매우 간단합니다. 그래서 우리는 가장 높은 급여와 급여를 비교하고 있습니다.
it's very simple so with that we are comparing the salaries with the highest
10:29:06
급여가 일치하면 데이터가 표시됩니다.
salaries if there is a match the data going to be presented so
10:29:10
이제 실행해 보겠습니다. 그게 전부입니다. 보시다시피
let's go and execute that and that's it as you can see
10:29:13
우리는 가장 높은 급여를 가진 직원을 찾았습니다. 하지만 90k의 동일한 급여를 가진 직원이 여러 명 있다면, 물론 우리는 그것을 포함할 것입니다.
we got the employee with the highest salary but if there are like multiple employees with the same salary of 90k of course we're going to get it in
10:29:21
결과입니다. 마이클은 새로운 직장이 필요할 것 같습니다. 정말 최악입니다.
results i think michael gonna need a new job right this is the worst
10:29:30
그래서 이것은 윈도우 함수 최소 및 최대의 또 다른 사용 사례입니다.
so this is another use case for the window functions min max
10:29:34
좋습니다. 이제 비교 분석의 사용 사례로 넘어갑니다.
all right so now we come to the use case of the comparison analysis
10:29:37
현재 판매량을
where we want to compare the current sales with the
10:29:40
최고 및 최저 값과 비교하고 싶습니다. 그래서 우리는 다음 작업을 수행해야 합니다. 각 판매량의 편차를 최소 및 최대 판매량에서 찾으십시오. 보시다시피, 이것이 우리의 판매량이고, 이것이 가장 높고, 이것이 가장 낮습니다.
highest and the lowest value so we have the following task it says find the deviation of each sales from the minimum and the maximum sales amount so now as you can see this is our sales this is the highest and this is the lowest.
10:29:52
이제 우리는 데이터를 서로 빼서 편차를 구해야 합니다. 매우 간단합니다.
So now we just have to go and subtract the data from each other's in order to get the deviation. So it's very simple.
10:29:57
첫 번째 편차를 구해 보겠습니다. 우리는
Let's get the first deviation where we're gonna go
10:30:00
최저값과 판매량을 빼야 합니다.
and subtract the sales with the lowest value
10:30:04
이렇게 될 것입니다. 이제 우리는 여기서 무엇을 하고 있는지
so it's gonna be like this so now what we are doing over here
10:30:07
최저 판매량에서 판매량을 빼고 있습니다.
we are subtracting the sales from the lowest sales
10:30:10
모든 기록에서 우리는 당신을 호출할 것입니다.
of all records so we're gonna go and call you
10:30:13
최소에서의 편차입니다.
deviation from min so
10:30:16
이제 실행해 보겠습니다. 이제 우리는 이러한 값에서
let's go and execute it so now we can see from those values
10:30:19
현재 값이 얼마나 멀리 떨어져 있는지 볼 수 있습니다.
how far is the current value from
10:30:23
극단적인 값, 여기서 극단적인 값은 최저 값입니다.
the extreme the extreme here is the lowest value so
10:30:26
이것은 당신의 극단을 분석하는 정말 좋은 방법입니다.
this is a really great way on to analyze the extremes in your
10:30:29
데이터입니다. 이제 우리는 극단에 가까워지고 있습니다.
data so now as we are near to the extreme the
10:30:32
값이 낮아질 것입니다. 여기에서 우리는 0을 가지고 있습니다. 이것은 최저입니다. 왜냐하면 우리는 그것을 극단으로 정확히 가지고 있기 때문입니다.
value gonna be low so as you can see here we have a zero this is the lowest because we have it exactly as the extreme so actually this is our value so the 10.
10:30:42
이제 다음 값은 극단에서 조금 멀리 떨어져 있습니다.
now the next one is little bit far away from the extreme which
10:30:45
15입니다. 그래서 우리는 여기에서 5로 가지고 있습니다. 이것은
is 15 so we have it here as a 5 so this is not
10:30:48
우리의 극단 값에서 멀리 떨어져 있지 않습니다. 그리고 만약 당신이 확인한다면,
far away from our extreme value and then if you check
10:30:51
여기서 우리는 80이라는 값을 가지고 있으므로 거리가 매우 멉니다
this value over here we have it 80 so the distance is very far
10:30:55
극단적인 값에서 가장 낮은 판매량과 멀리 떨어져 있습니다
away from our extreme value the lowest sales so
10:30:58
이것은 정말 멋진 분석으로, 데이터의 판매를 분석하고 평가하기 위해
this is really nice analyzes in order to analyze and evaluate the sales of your data now of course we can go and evaluate our data with an another
10:31:07
극단적인 값에서 가장 높은 판매량을 얻기 위해
extreme which is the highest sales so in order to
10:31:10
그것을 하기 위해 우리는 먼저 가장 높은 값을 얻자고 말할 것입니다
do that so we're gonna first say let's get the highest
10:31:14
죄송하지만, 이것은 가장 높은 판매량입니다
sorry this one the highest sales and
10:31:17
판매량에서 그것을 빼면 당신은
subtract it from the sales so you are the deviation from
10:31:21
최대값에서 그것을 빼면
the max so let's go and execute it so
10:31:24
이제 출력에서 우리는 정확히 반대의 거리를 얻을 것입니다
now we can see in the output we're gonna get exactly the opposite distances so the order number one is the farest from the extreme so as you can see we
10:31:33
80이라는 값과 주문 h가 있습니다
have the value of 80 and the order h
10:31:36
동일한 값이므로 거리가 0입니다
is the identical one so that's why we have the distance of zero
10:31:39
이제 우리는 매우 빠르게 어떤 데이터 포인트가
so now we can see as well very quickly which data points are
10:31:43
극단적인 값에 가장 가까운지 볼 수 있습니다
the nearest to the extreme to the highest sales so as you can see guys using the window function mean and max it is very powerful in order to understand and evaluate your data points to the extremes
10:31:58
자, 이제 우리는 매우 중요한 사용 사례에 집중할 수 있습니다
all right everyone so now we can focus on very important use case one of the must know use cases for that aggregations is doing running total and rolling total.
10:32:08
이 두 개념은 데이터 분석과 보고서 작성에 매우 중요합니다
These two concepts are very important for data analysis and doing reporting that you must know the key use case for those two concepts is to do tracking.
10:32:16
예를 들어, 우리는 현재 총 판매량과 목표 판매량을 추적할 수 있습니다
For example, we can go and track the current total sales with the target sales in our business and as well, it's great in order to do historical analysis for the trends.
10:32:26
좋습니다, 이제 질문은 롤링 총계란 무엇인가입니다
Okay, so now the question is what is running a rolling total? They are basically very similar.
10:32:32
그들은 기본적으로 매우 유사합니다
they're going to go and aggregate a sequence of members and
10:32:35
그들은 멤버의 시퀀스를 집계할 것입니다
the aggregation going to get updated each time we add a new member
10:32:38
집계는 새로운 멤버를 추가할 때마다 업데이트됩니다
to the sequence a sequence could be like a time sequence
10:32:41
시퀀스는 시간 시퀀스와 같을 수 있습니다
that's why we call this type and analyzes over
10:32:45
그래서 우리는 이 유형을 분석한다고 부릅니다
time so now we still have the question what is the difference between the
10:32:48
시간에 따라 우리는 여전히 질문이 있습니다
running and the rolling totals the running total can
10:32:51
러닝과 롤링 총계의 차이는 무엇인가요
go and aggregate everything from the beginning until the
10:32:54
현재 데이터 포인트까지 모든 것을 집계할 수 있습니다
current data point without dropping off any
10:32:57
이전 데이터에서 롤링 총계에 있는 반면
old data where on the other hand in the rolling total it's
10:33:00
특정 시간 창에 집중할 것입니다.
gonna go and focus on a specific time window like the
10:33:03
지난 30일 또는 지난 두 달 동안
last 30 days or the last two months and each
10:33:06
새로운 구성원이나 데이터 포인트를 추가할 때마다
time we add a new member or a new data point to the window we
10:33:10
가장 오래된 데이터 포인트를 제거할 것입니다.
will be dropping off the oldest data point in the window
10:33:13
롤링 또는 이동 창의 효과를 얻을 것입니다.
and with this we're gonna get the effect of rolling or
10:33:17
이 개념을 이해하기 위해 매우 간단한 예를 들어보겠습니다.
let's say shifting window okay i totally understand if this might be complicated now let's go and have very simple example in order to understand this concept and as well how we can solve it using SQL.
10:33:26
이제 간단한 예가 있습니다. 월과 판매 데이터를 나란히 보여드리겠습니다.
All right, guys. So now we have a very simple example. We have the month and sales and we have it twice because I want to show you side by side how SQL works with the running total and the rolling total.
10:33:36
왼쪽에서의 작업은 각 월의 판매 총계를 찾는 것입니다.
So now what is the task on the left side? We want to find the running total of sales for each month.
10:33:42
오른쪽에서는 각 월의 3개월 롤링 총계를 찾고자 합니다.
And on the right side, we would like to find three month rolling total of the sales for each month.
10:33:48
오른쪽은 고정된 창만 있습니다.
So they sound very similar, but on the right side, we have only fixed window. So now how we can solve this using SQL.
10:33:55
왼쪽에서는 판매의 합계를 사용할 수 있습니다.
On the left side, we can use some of sales. So we want to go and aggregate all the sales using the sum function.
10:34:01
창의 정의는 월별로 정렬하는 것입니다.
And the definition for the window can be like this order by month. And of course, you can go and do anything like you can have here an average.
10:34:08
평균을 사용하면 실행 평균을 얻을 수 있습니다.
And if you use an average with order by, you will get the running average or the running max or the running count and so on.
10:34:15
오른쪽에서도 같은 방식으로 할 수 있습니다.
So that means always if you go and mix an aggregate function together with an order by, you will generate an effect of running total.
10:34:22
판매의 합계를 월별로 정렬할 수 있습니다.
Now on the right side, we can have the same stuff. we
10:34:25
지금까지 모든 것이 왼쪽과 같습니다.
can have an aggregate function together with order by so sum
10:34:29
왜 이렇게 생성되는지 궁금할 수 있습니다.
of sales order by month so far we have everything like
10:34:32
우리는 여기서 미친 듯이 지정하지 않았습니다.
the left side right but now you might ask why is qur gonna go and generate this
10:34:35
모든 것은 정의와 관련이 있습니다.
effect the running total we didn't here specify like crazy
10:34:39
프레임 절에 관한 것입니다.
stuff right it's all about the definition of
10:34:42
프레임 절을 지정하지 않으면 숨겨진 것을 얻습니다.
the frame clause so now do you remember if you use an order by and
10:34:45
기본 프레임 절은 이렇게 보일 것입니다.
you don't specify a frame clause you will get like hidden
10:34:48
행은 무한히 진행되고 현재 행 사이에 있습니다.
or let's say default frame clause and it's gonna look like this
10:34:52
실행 총계의 정의는 이렇게 될 것입니다.
rows between unbounded proceeding and current
10:34:55
행과 실행 총계의 정의가 무엇인지
row and what was the definition of the running total it's going to go
10:34:58
모든 데이터를 처음부터 집계할 것입니다
and aggregate all the data from the very first beginning
10:35:01
현재 위치에서 현재 행을 유지하면서
well the unbounded proceeding until the
10:35:04
이전의 모든 멤버를 포함해야 하므로 실행 총계의 정의는
current position the current row without dropping off
10:35:07
기본값의 정확한 정의가 될 것입니다
any old members so that means the definition of the running total
10:35:10
기본의 정확한 정의가 될 것이다
gonna be the exact definition of the default
10:35:14
실행 총계가 될 것이고 이제 오른쪽으로 가보겠습니다
frame clause that's why it's going to go and generate the effect of
10:35:17
여기서도 같은 내용을 다루고 있습니다. 우리는 집계할 것입니다
the running total now let's go to the right side the rolling total
10:35:20
데이터를 합계 함수를 사용하여 집계할 것입니다
here again we have the same stuff right we're gonna go and aggregate
10:35:24
데이터를 월별로 정렬할 것입니다. 그래서 우리는
the data using the sum function and we're gonna go and
10:35:27
실행 총계의 효과를 생성하고 있습니다
sort the data order by month so with that we are as well generating
10:35:30
항상 프레임을 지정해야 합니다. 이 예에서는 3개월입니다
the effect of running total so each time you
10:35:33
새로운 월이 생기면 포함하지 않기를 원합니다
use order by with aggregate function so now in the running total we want always to specify a frame so here in this example three months
10:35:39
최신 월을 포함하지 않기를 원합니다. 항상 고정된 윈도우로
so that means if we are getting a new month we don't want
10:35:42
이 고정된 윈도우 효과를 가지려면
to include the latest months we want always to be fixed window
10:35:46
프레임 절을 재정의해야 합니다
now in order to have this fixed window effects
10:35:49
기본값으로 두면 프레임이 계속 확장됩니다
we have to go and redefine the frame clause because
10:35:52
이 효과를 예제에서 보게 될 것입니다
if you leave it as a default like the running total the frame gonna keep
10:35:56
이렇게 정의합니다. 두 개의 이전 행 사이
extending you will see this effect in the example so now we
10:35:59
현재 행까지. 총 행 수가
define it like this rows between two preceding
10:36:02
각 윈도우에 포함될 것이며 최대
and current row so the total number of rows gonna
10:36:05
3개월이 될 것입니다. 이제 당신은 생각할 수 있습니다
be included in each window gonna be maximum of
10:36:08
당신이 말하는 것이 무엇인지 이해하지 못할 것입니다
three months so now i know you might think para
10:36:11
예제를 통해서만 이해할 수 있습니다
what you are talking about you didn't didn't get anything it's total normal
10:36:15
이것을 수행하기 위해 왼쪽에서 시작하겠습니다
you will understand it only with an example so in
10:36:18
이것을 이해하려면 예를 들어야 하므로
order to do this let's start with the left side so first is going to
10:36:21
데이터를 정렬하여 가장 작은 월부터 정렬합시다
go and sort the data so everything is sorted from the smallest month
10:36:24
가장 높은 월까지, 즉 1월부터 7월까지 모든 것이
until the highest one so from january until july everything
10:36:28
좋고 이제 작업을 시작할 것입니다
is good and now is going to go and start working with
10:36:31
프레임은 무한 진행을 나타내며, 항상 1월을 가리킵니다
the frame so the frame says unbounded proceeding so this is going to be static it's going to be always pointing to january this is the unbounded
10:36:39
데이터 세트의 첫 번째 행을 앞서고 이제
preceding the first row in the data set and now of
10:36:42
우리는 위에서 아래로 시작할 것입니다 현재 행은
course we are starting from top to button the current row going to be pointing
10:36:46
1월을 가리키고 있습니다. 프레임은 이렇게 보일 것입니다
as well to january so the frame going
10:36:49
이 행의 총 판매량은 20이므로
to look like this it's going to be only one row and
10:36:52
출력은 20이 될 것입니다. 이제 오른쪽으로 이동합시다
the total sale of this row going to be 20 so that's why we're
10:36:55
테이블 앞에서 프레임은
going to have the output 20 so now let's move to the right side the current row going to be as well january and what is the two preceding we don't have it yet so it's going to be pointing maybe somewhere here
10:37:04
또한 하나의 행이 될 것입니다. 출력에서 우리는 정확히
before the table so again what is the frame it's
10:37:07
같은 결과인 20을 얻을 것입니다
going to be as well one row so in the output we will get exactly
10:37:11
현재 총계와 누적 총계 사이에 차이가 없습니다
the same result 20 so so far there is no differences
10:37:14
계속 진행합시다. 이제 다음 행으로 이동할 것입니다
between the running total and the rolling total but
10:37:17
프레임이 오른쪽으로 확장될 것입니다. 이제 두 개의 월이 있습니다
let's keep going now we're going to go to the next row over here so what
10:37:20
이렇게 판매량을 계산할 수 있습니다
can happen to our frame it's going to go and extend right so we can have now two months in this frame and what is the total sales over here it's going to be 30 so we added a new member
10:37:31
프레임 내에서 모든 판매량을 계산하거나
you can calculate it like this either go and calculate all the sales
10:37:34
이전 집계 값에 새 멤버를 더할 수 있습니다
within the frame or you can go and say this is the
10:37:37
이전 값은 20이고 새 멤버는 10입니다
previous aggregated value plus the new member so
10:37:41
30이 될 것입니다. 둘 다 맞습니다
the previous one was 20 the new member is 10 we
10:37:44
이제 오른쪽으로 이동합시다. 2월이 될 것입니다
will get 30 both of them is correct so now let's move to
10:37:47
두 개의 이전 값은 여전히 ​​밖을 가리키고 있습니다
the right side what's gonna happen we're gonna be as well as february the
10:37:50
같은 집계가 발생할 것입니다. 30이 될 것입니다
two preceding is still like pointing somewhere outside and here the window gonna go and extend like this we have two months and the
10:37:58
미친 일이죠? 다음 달인 3월로 가봅시다
same aggregation gonna happen so we have 30 so so far nothing
10:38:01
미친 것 같지? 다음 달인 3월로 가보자.
crazy right let's go to the next month march the frame
10:38:05
연장이 될 거라서 이제 3개월이야.
gonna be extended so we have now three months and
10:38:08
여기서 집계가 60이나 30이 될 거야.
aggregation gonna be either here 60 or 30 plus
10:38:11
30이 되면 60의 누적 총액을 얻게 될 거야.
30 we will get the running total of 60 and now
10:38:14
오른쪽에서 무슨 일이 일어날지, 3월을 가리킬 거야.
on the right side what's gonna happen we're gonna point as well to march and
10:38:17
이번에는 두 개의 이전이 1월을 가리킬 거야. 이번이 전체 고정 프레임을 얻는 첫 번째야.
this time the two preceding gonna be pointing to january and this is the first time we are getting the whole fixed frame right so we have
10:38:25
여기서 3개월이 이 프레임에 있어. 그럼 총액은?
here three months in this frame so what is the
10:38:28
그 총액은 60이 될 거야. 그래서 이제 우리는 여전히
total of that it's gonna be 60 okay so now you say okay we're still
10:38:31
같은 결과를 얻고 있어. 차이가 없어. 기다려봐.
getting the same results so there's no difference i'm gonna say wait for it it's
10:38:34
다음이 될 거야. 4월로 가면 여기서의 효과는
gonna be the next one so as we go to april the effect here
10:38:37
프레임이 4개월로 연장될 거라는 거야.
is that the frame gonna get extended to four months
10:38:40
항상 첫 달부터 현재까지 시작하니까.
because always we start from the first month until the current
10:38:43
어떤 멤버도 빠지지 않고, 이 총액은 65가 될 거야.
month without dropping any member outside so what is the total of this it's gonna be 65 sorry like this so now on the right side what's gonna happen we're gonna go and add a new member the april
10:38:55
하지만 우리는 창의 최대 크기에 있어. 이제 3개만 있어.
but we are at the maximum size of the window we have only three
10:38:58
그래서 두 개의 이전이 이동할 거야.
and that's because the two proceeding gonna shift as well
10:39:01
여기서 아래로, 경계는 2월부터 시작될 거야.
down over here so the boundary gonna be from february
10:39:04
4월까지, 그리고 우리는 1월을 제외할 거야.
until april and with that we are dropping off january
10:39:08
이제 효과를 볼 수 있을 거야. 슬라이딩되고 있어.
and now you're gonna see the effect it is sliding it
10:39:11
위에서 아래로 굴러가거나 이동하고 있어.
is rolling or shifting from top to bottom and that's
10:39:14
경계도 이동하고 있어서, 이제 롤링 총액의 효과를 볼 수 있어.
because the boundaries as well shifting so you can see now the effect of the rolling total the newest member gonna be added the oldest member gonna be
10:39:23
우리는 3개의 근육만 가질 수 있어.
out we are allowed only to have three muscles so
10:39:26
이 총액은 45가 될 거야. 이번에는
what is the total of this it's going to be 45 so this
10:39:29
이 값을 60과 함께 집계하지 않아.
time we are not aggregating this value the 60 together
10:39:32
5와 함께 창 안에서 값을 집계하고 있어.
with the five we are aggregating the values within
10:39:35
이제 계속 가보자. 우리는 6월에 있어.
the window so now let's keep going now we are at june
10:39:39
왼쪽에서 어떤 일이 일어날 수 있는지 프레임이 커질 것이고 그 결과로 135를 얻을 것입니다. 그래서 프레임이
what can happen on the left side the frame gonna get bigger and with that we will get the result of 135 so the frame is getting
10:39:47
정말 커지고 있지만 오른쪽은 고정된 상태가 될 것입니다.
really bigger but on the right side it's gonna have a fixed
10:39:50
프레임이므로 우리는 단순히 슬라이딩하고 이동하며 굴리고 있습니다. 그래서 우리는 새로운 멤버를 추가하고 다른 멤버는 나가고 가장 오래된 멤버는
frame so we are just sliding shifting and rolling so with that we are adding new member another member is leaving the oldest one and the total over here gonna be
10:40:00
105가 될 것입니다. 이제 마지막 행으로 가겠습니다.
105 and now we're gonna go to the last row we
10:40:03
링 총계를 위한 모든 것을 가질 것이고 전체 데이터
will have everything for the ring total so the whole data
10:40:06
세트는 집계될 것입니다. 그래서 이것이 우리가
set is gonna be aggregated so this is the maximum what we're
10:40:09
얻을 최대치입니다. 약 175가 될 것입니다. 하지만
gonna get it's gonna be around 175 but
10:40:13
오른쪽에서는 마지막 기록에 도달할 때까지 계속 이동할 것입니다. 창과 프레임도 이렇게 이동할 것입니다. 그래서 이 총계는 105가 될 것입니다.
on the right side it's just gonna keep shifting until we reach the last record the window the frame gonna be as well shifting like this so the total of this gonna be 105.
10:40:23
자, 여러분, 아주 간단합니다. 실행 총계는 항상 시작 위치에서 현재 행까지 모든 것을 고려합니다. 어떤 멤버도 빠지지 않습니다.
okay guys so you see it's very simple the running total is always considered everything from the starting position until the current row without dropping any member.
10:40:33
롤링 총계는 항상 가장 오래된 멤버를 삭제하여 새로운 것을 추가합니다. 그리고 창은 계속 이동합니다.
The rolling total, it's always drop the oldest member in order to add something new and the window is keep shifting.
10:40:40
그래서 실행 총계는 추적하는 데 매우 유용합니다. 예를 들어 예산 추적이나 현재 총 판매량을 목표와 비교하는 것과 같은 것입니다.
So the running total is very great in order to do tracking, like for example, budget tracking or we track, for example, the current total sales with a target or something like that.
10:40:51
그래서 우리는 항상 전체 데이터 세트를 고려하고 있습니다. 하지만 롤링 총계와 함께 우리는 항상 여기서 집중 분석을 합니다.
So always we are considering the whole data sets. But with the rolling total, we always do here focused analyzes.
10:40:58
우리는 항상 3개월의 윈도우에 관심이 있습니다.
are always interested with the window of three months so
10:41:01
그들은 매우 유사하게 들릴 수 있지만 완전히 다른 범위를 가지고 있습니다.
they might sound very similar but they have completely different scope
10:41:04
분석을 위해 하지만 둘 다 시간이 지남에 따라 집계를 수행합니다.
for analyzes but both of them are doing aggregations
10:41:07
그래서 그들은 시간이 지남에 따라 분석을 도와줄 수 있습니다.
over time so they can help us to do analyzes over
10:41:11
우리 비즈니스가 시간이 지남에 따라 성장하고 있는지 확인하는 것과 같은
time like checking whether our business is growing over time or
10:41:14
감소하고 있는지 확인하는 것입니다. 여러분, 보시다시피 매우 간단한 SQL을 사용하여
declining so guys as you can see using very simple sqls using
10:41:17
윈도우 함수를 사용하면 데이터에 대해 정말 훌륭한 분석을 할 수 있습니다. 그래서 이러한 것들은 데이터 분석이나 비즈니스 보고의 기본입니다.
the window functions we can do really great analyzes on our data so those stuff are really fundamental of data analyzes or doing reporting for our business.
10:41:27
그래서 윈도우 함수는 데이터 분석에 정말 강력합니다.
So window functions are really powerful for data analytics.
10:41:34
좋습니다. 이제 다음 작업이 있습니다. 판매의 이동 평균을 각 제품에 대해 계산하라고 합니다.
Okay, so now we have the following task and it says calculate the moving average of sales for each product over the time.
10:41:41
그래서 이제 우리는 이동 평균이라는 것이 있습니다. 이는 실행 총계와 매우 유사합니다.
So now we have here something called moving average. It is very similar to the running total.
10:41:46
실행 총계에서는 카운트와 합계를 사용했습니다.
In the running total we used count and sum and so on.
10:41:50
하지만 여기서는 평균 함수를 사용할 것입니다.
but here we're gonna go and use the function average and
10:41:53
실행 평균이라고 부르는 대신 이동 평균이라고 부릅니다.
instead of calling it running average we call it moving
10:41:56
평균이므로 작업을 해결해 봅시다. 항상 시작할 때는
average so let's go and solve the task let's start always by
10:42:00
일반적인 항목을 선택하여 주문 ID를 가져옵니다.
selecting the usual stuff so let's get the order id let's
10:42:03
제품 ID를 가져오고, 시간이 지났으므로 주문 날짜도 가져오겠습니다. 마지막으로 판매는 우리 테이블 판매 주문에서 가져옵니다.
get the product id and i would say since it's over the time i will get the order date as well and the last one the sales from our table sales orders
10:42:15
그게 다입니다. 이제 실행해 봅시다. 이제 우리는
so that's it let's go and execute it so now we
10:42:18
제품, 주문 날짜 및 판매가 포함된 10개의 주문을 얻었습니다.
got our 10 orders with the products order date and sales
10:42:21
단계별로 윈도우 함수를 구축해 봅시다.
let's start building our window functions step by step
10:42:24
어떤 함수가 필요할까요? 우리는 평균이 필요합니다. 이것은
so which function do we need we need the average this is
10:42:27
가장 쉬운 것입니다. 이동 평균이라고 합니다. 그래서 우리는
the easiest one it says moving average so that's it we
10:42:31
판매가 필요합니다. 판매의 평균이 될 것입니다. 이제
need the sales so it's going to be the average of sales let's
10:42:34
데이터를 나누어야 할까요? 예, 각
go and define the window so now do we have to divide the
10:42:37
제품에 대해 데이터 파티션을 나누어야 합니다. 즉, 우리는 파티션을 사용해야 합니다.
data partition the data well yes it says for each
10:42:41
제품 ID로 파티션을 나누는 조항을 사용해야 합니다. 이제
product that means we're going to go and use the partition by
10:42:44
첫 번째 단계는 평균을 구하는 것입니다.
clause by the product id so now i would
10:42:47
제품별로 실행해 봅시다.
say that's it for the first step so average by
10:42:50
그렇습니다. 결과를 확인하면 윈도우를 얻은 것을 볼 수 있습니다.
product so let's go and execute
10:42:53
제품 101에 대한 첫 번째 결과와
it so now if you check the result you can see that we got our windows
10:42:56
판매의 총 평균은 35가 될 것입니다.
so the first one for the product 101 and the
10:42:59
각 윈도우에 대해 집계된 하나의 값을 갖게 됩니다.
total average of the sales gonna be 35 so
10:43:03
다음 제품에 대해서도 같은 방식으로 진행됩니다.
we have like aggregated one value for each
10:43:06
다음과 같은 방식으로 진행되며, 시간에 따른 진행은 없습니다.
window the same thing for the next product and for the
10:43:09
또는 시간에 따른 이동 평균과 같은 것이 없습니다. 우리는
next and so on so we don't have any progress over time
10:43:12
각 윈도우에 대해 하나의 평균만 있습니다. 이제
or something like moving average over the time right we don't have this
10:43:15
이동 평균의 효과를 얻기 위해서는 실행
effect we have just one average for each window so now in
10:43:18
총계를 사용해야 합니다. 집계 함수를 함께 사용해야 합니다.
order to have the effect of the moving average it's going to be like the running
10:43:21
주문으로 정렬해야 하므로, 저는 그냥 만들겠습니다.
total we have to use the aggregate function together
10:43:25
집합 함수를 함께 사용해야 합니다.
with the order by so i'm just gonna make
10:43:28
새 열에 복사할 것입니다.
it in the new column i'm just gonna copy everything
10:43:31
여기서 이제 우리가 할 것은 정렬하는 것입니다.
like here and now what we're gonna do order by and since it's over the time we're We're going to go and use the order dates, order dates.
10:43:42
최소 날짜부터 최대 날짜까지 진행합니다.
And we're going to have it as sending because it's overtime overtime. Always like start with the earliest dates and up with the latest dates.
10:43:49
이렇게 두고 이동 평균이라고 부릅시다.
So from the lowest to the highest, we're going to leave it like this. So let's call it moving average.
10:43:55
이제 실행해 보겠습니다.
So now let's go and execute it. And we got here an extra comma because of the copy paste. So let's execute it again.
10:44:01
결과를 확인해 보겠습니다.
All right. So now let's check the results. Let's take the first window over here and you can see we have on the moving
10:44:08
진행 상황이 10으로 시작합니다.
average like a progress so it starts with 10
10:44:11
15, 14, 35가 있습니다.
15 14 35 so there is like
10:44:14
이동 평균은 하나의 고정된 숫자가 아닙니다.
moving average we don't have one solid number
10:44:17
평균을 구하는 방법은 간단합니다.
for the average we have different values so now how
10:44:20
첫 번째 행의 평균은 10입니다.
is ql gonna solve this it's really simple it's gonna start row
10:44:23
다음 행은 10과 20을 더한 후 2로 나눕니다.
by row so the first row what is the average of 10 it's
10:44:26
세 번째 행으로 이동하며 세 값을 요약합니다.
gonna be 10 then moving on to the next one it's gonna be 10 plus 20 divided by 2 you will get 15 so now
10:44:33
세 값의 합을 3으로 나누면 40이 됩니다.
moving to the third one all those three values going to be summarized
10:44:36
창의 마지막 행으로 가면 됩니다.
divided by three you will get 40 and now
10:44:39
네 값을 요약하여 4로 나눕니다.
to the last row in the window it's going to be
10:44:42
35가 나오고 이것이 정확히 같습니다.
summarizing all those four values divided by four
10:44:45
이전 열의 평균과 동일합니다.
and you will get 35 and this is exactly the
10:44:48
이전 열의 평균은 35입니다.
same value in the previous column you have here the average by
10:44:51
다음 값이 흥미롭습니다.
products we don't have order by you got as well 35 exactly like this last row and that's because we have the same calculation it is summarizing all those four values, dividing it by four.
10:45:02
제품 102의 평균은 15입니다.
But now it's interesting the next value. So as you can see, the next value, it comes from another window.
10:45:08
SQL은 이전 창의 오래된 값을 고려하지 않습니다.
So you see here we have 15 for the product 102, but the average is going to be as well 15.
10:45:14
이 창의 첫 번째 값은 15입니다.
So SQL is not considering the old values from the other window. So SQL is going to calculate each window separately.
10:45:22
그 값을 요약하여 나누면 됩니다.
So it's again here. This is the first value of this window 15 the average 15 then the same stuff, right?
10:45:28
그래서 그 값들을 두로 나누고 요약하자면.
So summarizing those values divided by two and so on.
10:45:31
그리고 데이터 분석에서 이 마지막 필드를 이동 평균이라고 부르며, 평균 함수와 함께 정렬하여 매우 간단하게 구현할 수 있습니다.
And this recall in data analysis this last field over here, we call it a moving average and you can implement it very simply using an average function together with the order by.
10:45:42
좋습니다, 다음 작업으로 넘어가고, 각 제품의 판매에 대한 이동 평균을 계산하라고 합니다.
All right, let's move to the next task and it says calculate the moving average of sales for each product over time, including only the next order.
10:45:51
보시다시피, 첫 번째 부분은 이미 올바르게 수행했습니다. 우리는 이동 평균을 가지고 있으며, 제품별로 파티션을 나누었습니다.
So as you can see, the first part we have already done is right. We have the moving average and divided by partition by for the products.
10:45:58
하지만 여기에는 더 많은 사양이 있습니다. 다음 주문만 포함하라고 합니다.
But here we have more specifications. It says including only the next order.
10:46:02
즉, 현재 주문과 다음 주문에 대해 이야기하고 있습니다.
That means we are talking about the current order and as well the next order.
10:46:07
여기서는 고정된 프레임 또는 고정된 윈도우가 필요합니다. 그래서 전체 평균이 필요하지 않습니다.
So here we have like a fixed frame or fixed window. So we don't need the whole average of the window.
10:46:12
각 계산에서 최대 두 개의 주문만 필요합니다. 그걸 어떻게 할까요?
We need only maximum two orders in each calculation. So how are we going to do that?
10:46:18
우리의 윈도우 함수 안에 사용자 정의 프레임 절을 가질 수 있습니다. 즉, 기본값으로 두지 않을 것입니다.
we can have our custom frame clause inside our window function. So that means we cannot leave it as a default.
10:46:25
우리는 그것을 지정해야 합니다. 그래서 가서 그렇게 하겠습니다. 이전 윈도우 정의를 복사할 것입니다.
We have to specify it. So let's go and do that. I will just copy the old definition of the window because we have the exact stuff.
10:46:33
그래서 우리는 제품 ID별로 파티션된 평균 판매량을 가지고 있으며, 날짜별로 정렬합니다.
So we have the average sales of our partition by product ID, order by date. So this is the first part.
10:46:39
이제 고정된 윈도우를 갖고 싶습니다. 그래서 이제 프레임 절을 정의하러 가겠습니다.
So now we would like to have this fixed window. So we're going to go now and define our frame clause.
10:46:45
조금 확대해 보겠습니다. 행 사이가 될 것입니다.
I'm just going to zoom out a little bit. it's going to be rows between
10:46:49
그래서 이제 프레임의 경계가 설정되었습니다.
so we have now the boundaries of the frame it says
10:46:52
다음 주문을 포함하므로, 다음을 사용하러 가겠습니다.
including the next order so we're going to go and use the following
10:46:55
첫 번째 경계는 현재 행이 될 것입니다.
so the first boundary going to be the current row and
10:46:59
다음 주문이므로, 하나가 뒤따를 것입니다.
since it's next order so it's going to be one following
10:47:02
그래서 그것이 우리의 프레임입니다. 다음 주문만 포함합니다.
so that is our frame including only the
10:47:05
다음 주문이므로, 하나가 뒤따를 것입니다.
next order and we have it like this one following
10:47:08
우리가 이동 평균이라고 부르겠습니다. 그래서 이제 실행해 보겠습니다.
let's call it yeah rolling average so that's it let's go and execute so now let's go and check the result you can see the moving
10:47:17
이동 평균은 완전히 다른 값을 가집니다.
average has completely different values as the rolling average
10:47:20
왜 그렇게 되는지 이해해 보겠습니다.
so let's go and understand why we can do it row by row let's
10:47:23
여기 첫 번째 행을 가져오겠습니다. 여기 판매량은 10입니다.
take the first row over here so the sales here is 10
10:47:26
그리고 이동 평균은 15입니다. 왜 그런가요?
and the rolling average is 15 so why is
10:47:30
계산에서 다음 값을 고려하고 있기 때문입니다.
that because in the calculation we are considering the
10:47:33
다음 값이므로 10 더하기 20 나누기
next value so 10 plus 20 divided
10:47:36
2를 하면 15가 나오므로
by 2 you will get 15 so that means the
10:47:39
SQL은 첫 번째 행에 대한 이 계산을 위해 두 행을 이렇게 정의했습니다. 이제 두 번째 행으로 넘어갑니다.
sql defined the frame like this those two rows for this calculation for the first row so now moving on to the second row
10:47:46
세 번째도 포함될 것입니다.
it's going to include as well the third one right
10:47:49
다음은 창이
the next one but since the window is
10:47:53
오직 두 개의 주문이므로 첫 번째 행을 삭제합니다.
only two orders it's going to go and drop the first row
10:47:56
다음 프레임은 이렇게 될 것이고
so the next frame going to be like this and
10:47:59
보시다시피 20 더하기 19 나누기 2가 될 것입니다.
as you can see it's going to be 20 plus 19 divided by 2
10:48:02
55가 나오므로 이제
you will get 55 so now we can see the effect of the
10:48:06
롤링 평균의 효과를 볼 수 있습니다. 다음은
rolling average right so now for the next one is
10:48:09
정확히 동일할 것이므로 우리는 세 번째 행에 있으며 다음을 포함할 것입니다. 같은 값이 나올 것입니다.
going to be exact same so we are at the third row it's going to go and include the next one and we're going to get the same value because 19 plus
10:48:16
19 더하기
20 divided by two you will get 55 now interesting
10:48:19
20 나누기 2를 하면 55가 나옵니다. 이제 흥미로운
to the last row in the window over here it will not
10:48:22
마지막 행은 여기에서 창에 있으므로
go and consider the next value because it is
10:48:25
다음 값을 고려하지 않을 것입니다. 창 밖에 있으므로 20이 될 것입니다.
outside of the window so it's gonna be 20 and
10:48:29
그것은 또한 20으로 유지될 것입니다. 그게 다입니다.
it's gonna stay as well 20 so that's it all right
10:48:32
여러분, 그래서 우리는 이동 평균에 대해 배웠습니다.
guys so with that we have learned about the moving average
10:48:35
롤링 평균과 이러한 놀라운 개념을 사용하여
the rolling average and those amazing concepts using
10:48:38
창 함수. 이제 집계 함수에서 다양한 사용 사례에 대한 간단한 개요를 볼 수 있습니다.
the window function all right now we can have a quick overview of the different use cases in the aggregate functions and how the definition of the window gonna change the whole use case.
10:48:48
창을 정의하지 않으면 비워두면 전체 총계를 찾는 첫 번째 사용 사례입니다.
So now the first use case is finding the overall total and here if you don't define anything in the window if you leave it empty what can happen you are doing here overall analyzes.
10:48:58
전체 데이터 세트를 집계하고 각 행에 대해 이 집계를 제공할 것입니다.
So you're gonna go and aggregate the whole data sets and then provide this aggregation for each row.
10:49:04
비워두면 이렇게 됩니다. 아무것도 정의하지 않으면 전체 데이터 세트를 집계합니다.
So this is what happens if you leave it empty you don't define anything you are aggregating the whole data sets.
10:49:10
이제 다음 단계로 넘어가서
Now moving to the next step we can do analyzes called
10:49:13
총 쌍 그룹을 분석할 수 있습니다. 우리가 할 것은
total pair groups so what we're gonna do we
10:49:17
창 정의에 파티션을 추가하는 것입니다.
will add partition by to the definition of the window so
10:49:20
예를 들어 여기서 제품별로 파티션을 추가함으로써
by adding for example here partition by products what
10:49:23
데이터가 두 가지 범주 또는 두 그룹으로 나뉘게 됩니다.
can happen the data is going to be split into two categories or
10:49:26
각 윈도우에 대해 집계가 수행됩니다.
two groups and the aggregation is going to be done for each window
10:49:29
따로따로 진행되며, 이는 물론 다양한 제품을 비교하는 데 유용합니다.
separately this is of course great analyzes in order to go
10:49:32
이렇게 하면 카테고리를 비교하는 데 도움이 됩니다. 파티션을 사용하면 총 쌍 그룹 분석을 수행할 수 있습니다.
and compare different products like here the caps and gloves so this is helpful in order to compare categories So you can do this analysis total pair groups if you use the partition by.
10:49:42
이제 정렬을 사용하면 세 번째 사용 사례에 도달하게 됩니다.
Now, if you go and use the order by, you're going to land in the third use case.
10:49:47
우리가 배운 대로, 우리는 누적 합계를 수행할 것입니다.
As we learned, we will be doing running total.
10:49:49
출력에서 볼 수 있듯이, 우리는 판매에 대한 누적 값을 구축하고 있습니다.
So as you can see in the output, we are building a cumulative value for the sales.
10:49:54
이것은 비즈니스 성과를 이해하기 위한 시간 분석의 진행에 도움이 될 수 있습니다.
And this can help us in order to do progress of our time analysis in order to understand the performance of our business.
10:50:01
이제 마지막 사용 사례로 넘어가겠습니다. 집계와 함께 윈도우 함수의 마지막 단계입니다.
And now moving on to the last use case, the final phase of the window function with the aggregation.
10:50:06
여기에서 집계 함수와 사용자 정의 고정 윈도우로 정렬이 함께 있습니다.
Here you have the aggregate function together with the order by with customized fixed window.
10:50:12
물론, 특정 고정 윈도우에서 시간 경과에 따른 진행 상황을 구축하는 데 도움이 될 수 있습니다.
And of course, we can use it in order to help us building progress over time in specific fixed window. And of course, you can use those use cases.
10:50:18
다른 함수, 즉 합계뿐만 아니라 다른 함수를 사용하면 동일한 효과를 얻을 수 있습니다.
You will get the same effect if you use the other functions, not only the sum.
10:50:23
평균, 개수, 최대, 최소 등 모든 집계 함수를 사용할 수 있습니다.
You can use average, count, max, min, so all aggregate functions.
10:50:26
여러분, 보시다시피, 스케일에서의 윈도우 함수는 데이터 분석을 수행하는 데 매우 중요합니다.
So guys, as you can see, the window function in scale is very important in order to do data analytics.
10:50:31
윈도우의 일부를 변경하는 것만으로도 데이터 분석을 위한 새로운 사용 사례를 생성하게 됩니다.
By just like changing the part of the window, you are generating a whole new use case for data analytics.
10:50:41
좋아요, 친구들. 이제 윈도우 집계 함수에 대한 간단한 요약을 해보겠습니다.
All right, friends. So now let's do a quick recap about the window aggregate functions.
10:50:45
그들이 하는 일은 값 집합을 집계하고 각 행에 대해 단일 집계 값을 반환하는 것입니다.
So what they do, they're going to go and aggregate a set of values and return a single aggregated value for each row.
10:50:52
그룹화와 매우 유사하지만, 여기서는 세부 정보를 잃지 않습니다.
So it's very similar to the group by, but here we don't lose details.
10:50:56
이제 다음 포인트로 넘어가겠습니다. 표현식에 대한 구문 규칙은 무엇인가요? 모두 표현식에서 숫자를 기대합니다.
Now to the next point, what are the rules for the syntax about the expressions? They all expect a number in the expression.
10:51:03
판매 또는 정수와 같은 숫자를 전달해야 하지만, 개수에 대해서는 어떤 데이터 유형도 사용할 수 있습니다.
So you have to pass a number like sales or any integer, but only for the count. You can go and use any data type.
10:51:09
집계 함수에 대한 사항은 매우 간단합니다. 모든 것은 오버 절 또는 윈도우 정의 내에서 선택 사항입니다.
And the things for the aggregate functions are very simple. Everything is optional inside the definition of the over clause or the definition of the window.
10:51:16
파티션, 정렬, 프레임을 사용할 수도 있고, 모든 것을 비워둘 수도 있습니다. 모든 것이 선택 사항입니다.
So you can go and use partition by order by frames or not, or just leave everything empty. So everything is optional.
10:51:22
우리가 배운 대로, 집계 함수에 대한 많은 사용 사례가 있으며, 이는 분석에 정말 놀랍습니다.
So now as we learned, we have a lot of use cases for the aggregate functions and they are really amazing for analytics.
10:51:27
첫 번째, 가장 간단한 것은 윈도우 함수를 비워두면 전체 분석을 수행할 수 있습니다.
So the first one, the simplest one you can do overall analyzes if you just leave the window function empty.
10:51:33
그래서 첫 번째, 가장 간단한 방법은 윈도우 함수를 비워두고 전체 분석을 하는 것입니다.
So you will get one big number about your business. And the next use case we can do total pair groups analyzes.
10:51:39
배운 것처럼, 우리는 파티션을 사용하여 서로 다른 카테고리를 비교할 수 있습니다. 이는 제품이나 고객을 비교하는 것과 같습니다.
As you learned, we can use partition by in order to compare categories with each other is like comparing the products or customers and so on.
10:51:45
다음으로 넘어가서, 우리는 부분에서 전체로 분석할 수 있습니다.
Moving on to the next one, we can do parts to whole analyzes.
10:51:49
각 데이터 포인트의 성능을 전체와 비교할 수 있습니다.
we can go and compare the performance of each data point with
10:51:52
예를 들어, 판매를 전체 판매와 비교할 수 있습니다.
the overall so you can for example compare the sales to
10:51:55
윈도우의 총 판매 또는 모든 데이터 세트와 비교할 수 있습니다.
the total sales in the window or to the all data sets
10:51:58
현재와 비교할 수 있는 많은 비교 분석이 있습니다.
and we have many comparison analyzes we can go and compare the current
10:52:01
현재 값을 평균과 비교하거나 극단적인 값과 비교할 수 있습니다.
value with the average or we can compare them to the extreme
10:52:05
최고 판매와 최저 판매를 비교할 수 있습니다.
to the highest sales to the lowest sales and so on and
10:52:08
데이터 품질 문제를 식별할 수 있는 또 다른 사용 사례입니다.
another use case we can go and identify data quality issues
10:52:11
예를 들어 중복을 식별할 수 있습니다.
in our data so we can go for example identify duplicates
10:52:14
카운트 함수를 사용하여 다음 사용 사례로 넘어갑니다.
using the count function moving on to the next use case we have
10:52:17
이상치 탐지를 통해 어떤 데이터 포인트가 평균 이상인지 이하인지 찾을 수 있습니다.
the outlier detection we can go and find out which data
10:52:21
다음으로, 우리는 누적 합계를 다룰 것입니다. 배운 것처럼, 이는 진행 상황을 추적하는 데 유용합니다.
points are above the average and below the average and so on then
10:52:24
진행 상황을 추적하거나 모니터링하는 도구입니다.
the next one we have the running total as we learned it is great
10:52:27
시간에 따라 우리의 비즈니스 성과를 모니터링하는 도구입니다.
tool in order to track the progress or to monitor
10:52:30
더 구체적으로 말하자면, 특정 윈도우를 사용하여 진행 상황을 추적할 수 있습니다.
the performance of our business over the time
10:52:34
특정 윈도우를 가지기 위해 롤링 총계를 사용할 수 있습니다.
or if you want to be more specific you can go and use the
10:52:37
이 윈도우를 세 달 정도만 추적할 수 있습니다.
rolling total in order to have like a specific window
10:52:40
마지막 사용 사례로 이동 평균을 계산할 수 있습니다.
and only track this window like three months or something like
10:52:43
우리 데이터의 이동 평균을 계산할 수 있습니다.
that and the last use case we can go and calculate the moving average of
10:52:47
정렬 및 집계 함수가 여러분에게 놀라운 기회를 열어줄 수 있습니다.
our data so it's really amazing how order by and aggregate functions
10:52:50
놀랍거나 고급 분석기를 위한 문을 열 수 있습니다.
can open for you a door for amazing or advanced
10:52:54
데이터 분석 세계에서 윈도우 집계 함수에 대한 많은 사용 사례가 있습니다.
analyzers so guys as you can see we have a lot of use cases for
10:52:57
윈도우 집계 함수를 다루었고, 다음 단계에서는 윈도우 함수를 사용하여 데이터를 순위 매기는 방법을 배울 것입니다.
the window aggregate functions in the world of data analytics all right so with that we have covered the aggregate window functions and in the next step it's going to be very important we will learn
10:53:06
데이터를 윈도우 함수로 순위 매기는 방법을 배워보겠습니다.
how to rank our data using window functions so let's go
10:53:13
이제 다음 데이터를 살펴보겠습니다. 제품과
all right so now let's say that we have the following data we have products and
10:53:17
그들의 판매량을 기준으로 제품의 순위를 매기고 싶다면
their sales if you want now to go and rank your products
10:53:20
먼저 데이터를 정렬해야 합니다. 예를 들어
first you have to sort the data based on something like for
10:53:23
판매량을 기준으로 제품을 순위 매기는 것입니다.
example ranking the products based on their sales so
10:53:27
즉, 가장 높은 판매량부터 가장 낮은 판매량까지 데이터를 정렬해야 합니다.
that means isquell first gonna go and start sorting your data from the highest to the lowest so sorting the data is always the first
10:53:34
정렬하는 것은 항상 순위를 매기기 전에 해야 할 첫 번째 작업입니다.
thing is scale has to do before ranking
10:53:37
이제 데이터를 순위 매기기 위해 두 가지 방법이 있습니다.
anything now in order to rank our data we have two methods the
10:53:41
첫 번째 방법은 정수 기반 순위 매기기입니다.
first method we call it the integer based ranking so
10:53:44
즉, 각 행에 대해 정수, 즉 전체 숫자를 할당하는 것입니다.
that means is going to go and assign for each row an
10:53:47
예를 들어 첫 번째 행은 판매량 70인 제품 E로, 순위는 1이 됩니다.
integer a whole number based on the position of the row so now by looking to the example the first row we have the product e with the sale 70 it's going to be ranked number one
10:53:58
그 다음 행은 판매량 30인 제품 B가 됩니다.
then the next row the product b with the 30 sales
10:54:01
순위는 2가 되고, 다음은 3, 4, 마지막은 5가 됩니다.
we will get the rank number two then the next one going
10:54:05
즉, SQL은 정렬된 목록에서 각 행에 대해 정수를 할당하고 있습니다.
to be three four and the last one going to be five so that means
10:54:08
이 방법은 정렬된 목록에서 각 행의 위치에 따라 정수를 할당합니다.
isql here is assigning an integer for each row based
10:54:11
이 방법을 정수 기반 순위 매기기라고 부릅니다.
on their position in the sorted list so this method
10:54:14
두 번째 방법은 비율 기반 순위 매기기입니다.
we call it integer based ranking now let's go
10:54:18
이 방법에서 SQL은 먼저 각 행의 상대적 위치를 계산합니다.
to the second method we have the percentage based ranking so in this method isql gonna go first and calculate the relative position of the row compared to all others
10:54:28
그리고 각 행에 대해 비율을 할당합니다. 출력에서는 SQL이 정수 대신 비율을 할당합니다.
and then assign a percentage for each row. So in the output, SQL gonna start assigning percentages instead of integer.
10:54:35
우리는 0에서 1까지의 비율을 가질 것입니다. 두 방법을 비교해보면, 정수 기반 순위에서 이산적인 값을 확인할 수 있습니다.
And we're gonna have a scale from zero to one. So now if you go and compare both of the methods, you can see that on the left side on the integer base ranking, we have discrete distinct values.
10:54:46
순위는 1부터 시작하여 2, 3, 그리고 이 예에서는 5로 끝납니다.
So it starts from one, then two, three, and end up in this example by five.
10:54:51
결과에 몇 개의 행이 있는지에 따라 다릅니다. 5개일 수도 있고, 500개, 500만 개일 수도 있습니다.
So it really depends on how many rows do we have in the results. So it could be five, it could be five hundred, five million and so on.
10:54:58
하지만 오른쪽에서는 항상 1에서 0까지 같은 비율을 가집니다.
But in the right side, we have always the same scale from one to zero.
10:55:03
0과 1 사이에는 무한한 데이터 포인트가 있습니다.
So between zero and one, we have infinite number of data points.
10:55:07
이 비율을 정규화된 비율 또는 연속 비율이라고 부릅니다.
And this scale, we call it a normalized scale or we call it continuous scale, continuous values.
10:55:13
이제 질문은 어떤 방법을 언제 사용해야 하는가입니다. 예를 들어, 백분율 기반 순위는 이러한 질문에 답하는 데 좋습니다.
So now the question is when to use which method. So for example, for the percentage based ranking, it is great to answer such questions.
10:55:21
판매를 기준으로 상위 20% 제품을 찾으세요.
Find the top 20% products based on their sales.
10:55:24
이 방법은 데이터 값이 전체 총계에 기여하는 바를 이해하는 데 훌륭한 방법입니다.
So this method is a great way in order to understand the contributions of data values to the overall total.
10:55:31
이러한 분석을 분포 분석이라고 부릅니다.
And we call this kind of analysis a distribution analysis.
10:55:34
반면 정수 기반 순위에서는 상위 세 개 제품을 찾는 것과 같은 질문에 답할 수 있습니다.
Where in the other hand, in the integer base ranking, we can answer questions like find the top three products.
10:55:40
이 질문에서는 각 제품이 전체 총계에 기여하는 것에 관심이 없습니다.
So with this question, we are not interested about the contributions of each product to the overall total.
10:55:46
우리는 단지 목록 내에서 값의 위치에 관심이 있습니다. 이 분석과 보고는 매우 일반적으로 사용됩니다.
We are just interested in the position of the value within a list. So this is as well very commonly used analysis and reporting.
10:55:54
우리는 이를 분석기에서 상위 버튼이라고 부릅니다. 이제 이 두 가지 방법을 기반으로 순위 함수를 그룹화해 보겠습니다.
we call it top button in analyzers. So now let's group up our ranking functions based on those two methods.
10:56:00
정수 기반 순위의 첫 번째 그룹에는 네 가지 함수가 있습니다: 행 번호, 순위, 밀집 순위 및 엔타일입니다.
For the first group in the integer based ranking we have four functions row number rank dense rank and entile.
10:56:07
반면 백분율 기반 순위를 생성하는 함수는 두 개뿐입니다: 누적 및 백분위수입니다.
But in the other hand we have only two functions that generate percentage based ranking we have the cumidest and as well the percentile.
10:56:15
이제 이것은 이러한 방법과 순위 함수를 그룹화하는 방법에 대한 소개 및 개요였습니다.
So now that was an introduction and overview of those methods and how we group up those ranking functions.
10:56:21
다음으로 순위 함수의 구문에 대해 배우겠습니다. 대부분은 동일한 규칙을 따릅니다.
Next we're going to go and learn about the syntax of the ranking functions. Most of them follow the same rules.
10:56:27
예를 들어, 우리는 항상 함수 이름으로 시작합니다. 여기서 우리는 순위를 가지고 있습니다. 하지만 보시다시피, 우리는 어떤 표현도 사용하지 않습니다.
So for example, we start always with the function name. So we have here the rank. But as you can see, we don't use any expressions.
10:56:33
따라서 그들은 내부에 어떤 인수도 사용하도록 허용하지 않습니다. 비워 두어야 합니다.
So they don't allow you to use any argument inside it. It must be empty.
10:56:39
이것이 순위 함수를 사용할 때의 첫 번째 규칙입니다. 다음은 윈도우의 정의에 대한 것입니다.
So this is the first rule using rank functions. Then about the definition of the window.
10:56:43
보통 파티션은 선택 사항입니다. 사용할 수도 있고 남겨둘 수도 있습니다. 이제 두 번째 부분으로 넘어가면, 정렬이 있습니다.
As usual, the partition by it is an optional thing. You can use it or leave it. And now to the second part, we have the order by.
10:56:50
정렬은 필수이므로 데이터를 정렬해야 합니다.
it is as well required so you must order
10:56:53
비워둘 수 없으므로 이는 정의를 위한 것입니다.
the data or sort your data in order to do ranking so
10:56:56
윈도우는 최소한 정렬이 있어야 합니다.
you cannot leave it empty so that means for the definition of
10:56:59
예를 들어, 여기서 판매 기준으로 정렬해야 하므로 비워둘 수 없습니다.
the window at least we should have an order
10:57:02
좋습니다. 두 가지 요구 사항은 어떤 표현도 사용할 수 없고,
by for example here sales so we cannot leave it
10:57:05
정렬을 사용해야 한다는 것입니다. 이제 모든 함수에 대한 개요를 살펴보겠습니다. 보시다시피 모든 함수는
empty all right so the two requirements you cannot use any expressions
10:57:09
순위 함수이며 거의 모든 함수는 내부에 어떤 표현도 사용할 수 없습니다.
for those functions and as well you have to sort your data using order by okay so now let's have an overview of all functions so as you can see all those functions
10:57:18
이 함수 외에 엔타일이 있으며, 내부에 숫자를 허용합니다.
are ranking functions and almost all of them don't allow to use any expressions inside them
10:57:24
즉, 비워둘 수 없다는 것입니다.
beside this function here we have the end tile it accepts
10:57:27
이 기능 옆에 끝 타일이 있습니다.
a number inside it so that means you cannot use it empty you
10:57:31
안에 숫자를 사용해야 하므로 비워둘 수 없습니다.
should use a number inside it all others must be
10:57:34
모두 선택 사항이므로 이제 파티션을 비워두어야 합니다.
empty so now for the partition by all of them are optional and
10:57:38
모두 필수이므로 정렬을 사용해야 합니다.
for the order by all of them are required so you must use order
10:57:41
프레임 절은 순위 함수에서 사용할 수 없으므로 창 함수 내부의 프레임 정의를 변경할 수 없습니다.
by and the frame clause they are not allowed to use in the ranking functions so you cannot change the definition of the frame inside the window function.
10:57:51
우리가 할 일은 평소와 같이 모든 함수에 대해 깊이 파고들어 언제 사용해야 하는지 이해하는 것입니다.
So now what we're going to do as usual, we're going to go and deep dive into all of those functions in order to understand when to use them and what are the use cases and as we'll practice in SQL.
10:58:01
첫 번째로 시작할 것입니다. 행 번호입니다.
So we're going to start with the first one, the row number. All right.
10:58:08
SQL에서 행 번호란 무엇인가요?
So what is a row number in SQL?
10:58:10
행 번호 함수는 각 행에 고유한 번호를 할당합니다.
The row number function going to go and assign for each row a unique number as a rank and
10:58:15
동점에 대해서는 전혀 신경 쓰지 않습니다.
it doesn't care at all about the ties that means
10:58:18
같은 값을 공유하는 두 행이 있을 경우
if you have two rows sharing the same value they will
10:58:22
같은 순위를 공유하지 않습니다. 간단한 예를 보겠습니다.
not share the same rank okay so now we have very simple example
10:58:25
모든 판매 목록이 있으며 다음 쿼리가 있습니다.
we have a list of all sales and we have the following query so it's going to start with the ranking function or row number it doesn't accept any argument inside it and the definition of the window going to be like this
10:58:37
판매 순으로 정렬하므로 가장 높은 값에서 낮은 값으로 데이터를 정렬합니다.
order by sales disk so that means we're going to go and sell the data descending from the highest
10:58:43
SQL은 가장 높은 값이 100, 가장 낮은 값이 20이 되도록 할 것입니다.
to the lowest so sql gonna go and do the following the highest gonna be the 100 the lowest gonna be the 20 and here we have twice the 80.
10:58:54
이제 SQL이 데이터를 정렬한 후 발생하는 일입니다.
so now once sql done sorting the data what's gonna happen it's
10:58:57
순위를 할당하기 시작할 것입니다.
gonna start assigning a rank so the row number gonna go and assign
10:59:00
각 행에 대해 고유한 번호를 할당합니다.
a unique number for each row so that means it's gonna start with the first one the 100 gonna be the rank number one
10:59:07
다음은 순위 번호 2가 될 것입니다.
the next one gonna be rank number two the 80 gonna
10:59:11
순위 번호 3이 될 것입니다.
be rank number three and the 54 and
10:59:14
마지막 번호는 5가 될 것입니다.
then the last one gonna be five and now if you check the output you can see that
10:59:17
모든 숫자는 고유하며 반복이 없습니다.
all those numbers are unique we don't have any repetitions
10:59:20
하나, 둘, 셋, 넷, 다섯, 반복이 없습니다.
so one two three four five there is no repetitions they
10:59:23
고유한 값이며 순위 건너뛰기가 없습니다.
are unique distinct value and as well there
10:59:26
우리 데이터에는 특별한 점이 있습니다.
are no skipping of ranking so that means we have here one two three there is no jumping to six seven or something there are clear sequence of distinct value and there are no gaps.
10:59:37
하지만 여전히 우리의 데이터에는 특별한 점이 있습니다. 우리는 판매에서 같은 값을 두 번 볼 수 있습니다.
But still there is something special in our data. We can see that in the sales we have the same value twice.
10:59:43
그래서 우리는 같은 판매를 가진 두 개의 행이 있습니다. 행 번호에서 볼 수 있듯이, 그들은 이 항목의 값을 얻을 것이므로 같은 순위를 공유하지 않을 것입니다.
So we have two rows with the same sales. As you can see in the row number, they will get this thing's value so they will not share the same ranking.
10:59:52
즉, 행 번호는 동점을 처리하지 않습니다.
So that means row number does not handle the ties.
10:59:55
여러 행이 같은 값을 공유하면, 그들은
If you have multiple rows sharing the same values, they will not
11:00:00
같은 순위를 공유하지 않고 고유한 순위를 가질 것입니다.
share the same rank they're gonna have a distinct rank
11:00:03
서로 다른 순위를 가지므로, 이것이 SQL에서 행 번호가 작동하는 방식입니다.
different ranks so this is how the row number works in sql it
11:00:06
각 행에 대해 고유한 순위를 생성하며, 동점을 처리하지 않습니다.
generates unique ranks for each row it does not handle
11:00:09
또한 어떤 간격도 남기지 않습니다.
the ties and as well it doesn't leave any gaps
11:00:12
그래서 순위의 건너뛰기가 없으며, 이제 SQL로 가보겠습니다.
so there is no skipping of ranking so now let's go to sql
11:00:16
몇 가지 예제와 사용 사례를 갖기 위해서입니다. 좋아요, 이제 우리는
in order to have few examples and use cases all right so now we have
11:00:19
다음 작업이 있습니다. 매우 간단합니다. 판매를 기준으로 주문을 순위 매깁니다.
a following task it's very simple rank the orders based on their sales from the highest to the lowest so now this is very easy we're gonna go
11:00:26
판매에서 가장 높은 것부터 가장 낮은 것까지. 이제 이것은 매우 쉽습니다. 우리는
and select first the data so order id product
11:00:30
먼저 데이터를 선택할 것입니다. 주문 ID, 제품
id let's take the sales as well and select the table so
11:00:33
ID를 가져오고 판매도 선택하여 테이블을 선택합니다.
it's going to be sales orders let's go and execute
11:00:37
판매 주문이 될 것입니다. 이제 실행해 보겠습니다.
it so with that we got all our orders what we're going to do now
11:00:40
이렇게 해서 우리는 모든 주문을 얻었습니다. 이제 우리가 할 일은
is to assign for each row a rank so that means we
11:00:43
각 행에 순위를 할당하는 것입니다. 즉, 우리는
need a column here that contains the rank for each
11:00:46
각 행에 대한 순위를 포함하는 열이 필요합니다.
row so in order to do that we're going to go and use the window function
11:00:49
그렇게 하려면, 우리는 윈도우 함수를 사용해야 합니다.
row number it doesn't accept any argument
11:00:52
행 번호는 어떤 인수도 받지 않습니다.
inside it so should be empty and then we have to define the window
11:00:55
안에는 비어 있어야 하며, 그런 다음 윈도우를 정의해야 합니다.
so as we learned in the ranking functions we cannot leave
11:00:59
우리가 순위 함수에서 배운 것처럼, 우리는 비워둘 수 없습니다.
it empty we have to sort the data using order by so order
11:01:02
데이터를 정렬해야 하므로, ORDER BY를 사용해야 합니다.
by is a must we don't have to use any partition by so
11:01:05
ORDER BY는 필수입니다. 우리는 PARTITION BY를 사용할 필요가 없습니다.
we're going to rank all the data that you have inside the table so how
11:01:08
우리는 테이블 안에 있는 모든 데이터를 순위 매길 것입니다. 그래서 어떻게
to solve the data it says it should be based on their sales from highest
11:01:11
데이터를 해결하기 위해서는 판매량을 기준으로 가장 높은 것부터 가장 낮은 것까지 정렬해야 합니다.
to lowest that means we order by sales since from highest to lowest we have to use the descending and now we're going to go and give it a name sales rank
11:01:21
행 번호를 사용하고 있다고 가정해 봅시다.
and let's say row since we are using the row number so
11:01:24
이제 결과를 살펴보겠습니다. 이전에 isql이 정렬한
that's it is very simple let's go and execute it so
11:01:27
데이터는 주문 ID에 따라 정렬되었습니다.
now let's have a look to the results before isql did sort the
11:01:30
현재 판매량에 따라 내림차순으로 정렬하고 있습니다.
data by the order id since we didn't define anything but
11:01:34
가장 높은 판매량부터 시작하여 데이터를 정렬했습니다.
since now we are order by sale descending isql went
11:01:37
가장 높은 주문은 주문 번호 8이며, 판매량은 90입니다.
and sorted the data by the sales from the highest to
11:01:40
가장 높은 판매량입니다. 보시다시피, 1부터 10까지 있습니다.
the lowest and start assigning a rank or let's say an integer unique integer for each row so now the highest order gonna be the order number eight we We have the sales of 90.
11:01:49
이제 결과를 확인해 보시면, 여기서 순위는 고유합니다. 중복이 없습니다.
This is the highest one. So as you can see, we have one, two, three, four, five until 10.
11:01:54
그리고 건너뛰거나 간격이 없습니다. 1부터 10까지 모든 것이 있습니다.
So now by checking the results, you can see that the ranking here is unique. So there is no duplicates over here.
11:02:00
데이터에 동일한 값을 가진 판매가 몇 개 있지만,
And as well, there is no skipping or gaps. So we have everything between one and 10.
11:02:05
두 주문 모두 판매량이 60이지만, 동일한 순위를 공유하지 않습니다.
Even though that we have in our data, a couple of sales that sharing the same value. So for example, we have those two orders.
11:02:11
여기서 9와 3도 동일한 값 20을 공유하지만, 동일한 순위를 공유하지 않습니다.
You can see both of them has the 60 at the sales, but they don't share the same ranking. Right.
11:02:17
이로써 우리는 작업을 해결했습니다. 판매량에 따라 순위를 매겼습니다.
So we have here as well the nine and three they share the same value 20 but they don't share the same ranking.
11:02:22
그렇다면 순위 함수란 무엇인가요?
So with that we have solved the task it's very simple we have now a rank based on the sales from highest to the lowest.
11:02:29
좋습니다. 랭크 함수란 무엇인가요?
All right so what is a rank function?
11:02:35
SQL에서 랭크 함수는 각 행에 숫자, 즉 랭크를 할당하고, 이번에는 동점을 처리합니다.
In SQL the rank function gonna go and assign for each row a number a rank and this time it's gonna go and handle the ties.
11:02:42
즉, 데이터에 동일한 값을 가진 두 행이 있다면
so that means if in your data you have two rows having the same values
11:02:45
그들은 동일한 랭킹을 공유하게 됩니다.
they're gonna share the same ranking one
11:02:49
랭킹 함수의 한 가지 특징은 간격을 남긴다는 것입니다.
thing about the ranking function is that it's gonna go and leave gaps
11:02:52
랭킹에서 건너뛰는 가능성이 있습니다.
in the ranking so there is possibility of skipping
11:02:55
랭크 함수가 어떻게 작동하는지 이해하기 위해
ranks in order to understand how the rank function works in
11:02:59
SQL에서 매우 간단한 예제를 살펴보겠습니다. 다시 말해,
sql we're gonna have a very simple example all right so again
11:03:02
같은 데이터지만 다른 함수로, 우리의 윈도우는 이렇게 보입니다. 함수 랭크는 어떤 인수도 받지 않습니다.
with the same data but with different function so our window looks like this it starts with the function rank doesn't accept any argument
11:03:08
그 안에 그러면 우리는 이렇게 정렬된 윈도우를 가집니다. 판매로 정렬합니다.
inside it then we have the window like this order by sales
11:03:12
가장 높은 것에서 가장 낮은 것으로 내림차순 정렬하고
descending from the highest to the lowest and our data
11:03:15
우리 데이터는 이미 그렇게 정렬되어 있으므로 이제 기술이 어떻게 순위를 부여할지
is already sorted like that so now how is skill gonna go and assign
11:03:18
첫 번째 행이 가장 높은 순위가 될 것이므로
the ranks the first row gonna be the highest rank so the
11:03:21
값 100은 1이 되고 두 번째는 2가 되지만
value 100 is gonna be one then the second one gonna be two but
11:03:25
세 번째 값에 대해 여기 두 개의 값이 있습니다
now for the third one as you can see we have here two values
11:03:28
같은 값이므로 동점이 발생하고 이번에는 기술이 가서 두 사람 모두 같은 순위를 공유하게 됩니다
that are the same so we have a tie and this time is skill gonna go and as well lead them to share the same rank so both of them
11:03:36
따라서 두 사람 모두 2위가 될 것입니다. 행 번호와는 다릅니다.
going to be the rank two so it's not like the row number where
11:03:40
여기 세 개가 있습니다. 이번에는 두 개가 있습니다.
we have over here three this time we have two because we
11:03:43
동점이므로 같은 값을 가지면 그들은
have a tie so having the same values means they're
11:03:46
같은 순위를 공유하게 될 것이며 이제 다음 값으로 이동합니다.
going to share the same rank and now moving to the next value going
11:03:49
다소 까다로운 상황이 될 것입니다. 여기서 확인하면
to be tricky one because if you check over here you can see that the
11:03:53
다음 순위는 3처럼 되어야 하므로 1, 2가 있습니다.
next rank should be like the three right so we have one two and
11:03:56
그런데 다음 값이 생성된 순위는 3이어야 하지만, 이 값의 위치는
then the next value that generated in the rank should be three but it's going to say you know what this value position
11:04:03
4번이 될 것입니다. 따라서 1, 2, 3, 4가 있습니다.
going to be number four so as you can see one two three four
11:04:06
따라서 실제로 여기서의 위치 번호는 4이고
so actually the position number here is four and
11:04:09
iscl이 4위로 부여할 것입니다.
iscl is going to go and give it the rank of four so
11:04:12
그로 인해 iscl은 순위에서 공백을 남기게 됩니다.
with that iscl is going to be leaving a gap in the ranking
11:04:15
우리는 3위 순위를 건너뛰고 있습니다.
you can see we are skipping the rank number three and
11:04:19
이것은 항상 동점이 있을 때 발생합니다. 다음은 쉽게 5번 행이 될 것입니다.
this always happens once you have a tie where you are sharing the same ranking so for the next one is going to be easy it's going to be the row number five so now by looking to the output of the rank function you can see that
11:04:30
여기서는 고유한 순위가 없고 공유된 순위가 있습니다.
we don't have a unique ranking here we have shared ranking
11:04:33
동점의 경우 순위를 처리합니다.
in case of the tie so it handles the ties
11:04:36
하지만 여기서는 순위에 공백이 있습니다.
but here we have gaps in the ranks so
11:04:39
순위를 건너뛰고 있습니다. 순위 함수에 대해 생각할 때
we are skipping ranks when i think about the rank function
11:04:42
올림픽에서 두 선수가 동점일 경우를 생각합니다.
i think about the olympics if two athletes tie
11:04:46
금메달을 위해 1위가 있을 것이고
for the gold medal the first place there will be
11:04:49
금메달을 위한 첫 번째 자리에는
no silver medal for the second place the next medal going
11:04:52
은메달이 없고 두 번째 자리의 다음 메달은
to be given to the bronze to the third place all right so now let's go in this guild in order to practice the rank function all
11:04:59
동메달을 위한 세 번째 자리에 주어질 것입니다. 자, 이제 이 길드에 가서
Now we're gonna go and solve the same task but using the rank function
11:05:02
순위를 매기는 기능을 연습해 보겠습니다.
so what we're gonna do we're gonna stay with the same example over here
11:05:05
자, 우리는 여기서 같은 예제를 유지할 것입니다.
and we're gonna rank the order base on their sales from highest to lowest
11:05:08
그리고 우리는 판매량을 기준으로 순서를 매길 것입니다.
but this time using the rank function so we
11:05:11
이번에는 순위 기능을 사용하여
use the rank and everything inside is gonna be empty and then our window gonna be exactly the same as before so over order by sales
11:05:21
순위를 매기고 모든 것이 비어 있을 것입니다.
and disk so let's give it the name sales rank
11:05:25
그리고 우리의 창은 이전과 정확히 동일할 것입니다.
yeah let's give it a rank so that's it as you can see the
11:05:28
판매량 기준으로 정렬합니다.
syntax is very simple and very similar to the raw number we
11:05:31
이제 결과를 확인하기 위해 실행해 보겠습니다.
just changed the function so now let's go and execute
11:05:34
새로운 순위를 보고 이전 순위와 비교해 보면
this in order to check the results so now let's go and check the results
11:05:37
우리가 일부 순위를 공유하고 있다는 것을 알 수 있습니다.
by looking to the new rank if you go and compare it with the old rank we can see that we are sharing some ranking right we have here the two twice so the rank number two we have it twice because we We have over here the same value.
11:05:49
6060이 두 번 나타납니다.
So 6060 we have it here two and two.
11:05:52
행 번호와 비교하면 동일한 순위를 공유하지 않는 것을 알 수 있습니다.
But if you compare it to the row number, you can see that it is not sharing the same ranking. So this is one difference.
11:05:58
여기서도 마찬가지입니다. 그들은 같은 값을 가지고 있습니다.
And as well here, the same thing. They have the same value. The sales is 20. So we have it twice. The rank number seven.
11:06:05
판매량이 20입니다. 그래서 우리는 두 번 나타납니다.
And here we have it as different values. And the next value, as you can see, we are skipping the rank. So there is gap.
11:06:11
여기서는 서로 다른 값이 있습니다.
There is no rank of eight. So you can see that this is the row number nine.
11:06:17
그래서 다음 값에서는 순위를 건너뛰고 있습니다.
why it gets the nine the same thing i believe over
11:06:20
여덟 번째 순위는 없습니다.
here so now if you check those two ranks the next one should be
11:06:23
그래서 이것이 아홉 번째 행이라는 것을 알 수 있습니다.
three but since it is in the row number four it's
11:06:26
왜 아홉 번째 순위를 얻는지
gonna get the rank four so by checking the results we can see that sharing
11:06:29
이제 이 두 순위를 확인하면 다음은
the same ranks and as well we have gaps so this is
11:06:32
세 번째가 되어야 합니다.
how the rank works all
11:06:37
하지만 네 번째 행에 있기 때문에
right so what is a dense rank it is very similar to the
11:06:40
랭킹 함수입니다. 각 행에 번호를 부여합니다.
ranking function it's it's going to go and assign for each row a number
11:06:44
순위와 동점 처리를 합니다.
a rank and it as well handles the ties so
11:06:47
이번에는 순위 함수처럼 간격을 두지 않습니다.
same values they're going to share the same ranking but
11:06:50
밀집 순위는 간격을 두지 않습니다.
this time it doesn't leave any gaps like the rank function
11:06:53
순위를 건너뛰지 않으므로 이를 이해하기 위해
so the dense rank it will not leave any gaps
11:06:57
매우 간단한 예를 들어보겠습니다. 같은 데이터지만 다른 함수를 사용합니다.
it will not skip any ranking so in order to understand this
11:07:00
판매량에 따라 내림차순으로 정렬됩니다.
we're going to have a very simple example so let's go all right so again the same data but with different function we have this time the rank function dense rank and the window
11:07:09
데이터가 이미 정렬되어 있습니다.
going to be the same order by sales descending from the highest
11:07:12
SQL이 어떻게 순위를 부여하는지 봅시다.
to the lowest so now the data is as well sorted already
11:07:15
첫 번째 행은 순위 1이 됩니다.
let's see how sql gonna go and assign the ranks as usual
11:07:18
두 번째는 마찬가지입니다.
the first row gonna be the rank number one the second as
11:07:22
동일한 값이 있으므로
well but again here we have the same values so we
11:07:25
두 값 모두 순위 2를 가집니다.
have same values and it's like the rank it's gonna go and share
11:07:28
밀집 순위가 왜 필요한지 말씀드리겠습니다.
the same rank so both of them gonna have the rank number two and now you might say well this is very similar to the rank function so why
11:07:36
다음 값에서 차이가 나타납니다.
we have dense rank i'm gonna say wait for it we're gonna have
11:07:39
이 값은 동점 이후에 정확히 위치합니다.
the difference in the next value so is going to come over
11:07:42
순위 번호를 가져갔습니다.
here this value is exactly after the tie and rank is
11:07:45
4번째 위치였습니다.
going to went and took the position number so the row number
11:07:49
밀집 순위는 간격을 두지 않습니다.
it was four right so one two three four but this time with
11:07:52
다음 순위를 건너뛰지 않으므로
the dense rank is scale will not leave gaps in
11:07:55
우리는 1, 2, 3을 가집니다. 간격이 없습니다.
ranking so there will be no skipping the next rank and the sequence gonna be three so that's why we're gonna have the rank three for this value so So as you can see, there is no gap.
11:08:06
마지막은 4가 됩니다.
We have one, we have two and three. So we are not skipping. We are not leaving any gaps. And the last one going to be four.
11:08:12
이것이 밀집 순위와 일반 순위의 차이입니다.
So this is exactly the difference between the dense rank and the rank.
11:08:16
밀집 순위의 출력을 확인하면 고유한 순위가 없습니다.
So now by checking the output of the dense rank, you can see that we don't have unique ranks.
11:08:22
공유된 순위가 있으며, 반복이 발생합니다.
We have here shared ranks. As you can see, we have here repetition. So it handles the ties.
11:08:27
그리고 또한, 어떤 간격도 남기지 않습니다. 순위에서 아무것도 пропуска하지 않습니다. 알겠죠, 그게 전부입니다.
And as well, it doesn't leave any gaps. It doesn't skip anything in the ranking. Okay, so that's it.
11:08:33
이제 SQL로 돌아가서 밀집 순위를 연습해 보겠습니다. 자, 이제
now let's go back to sql to practice the dense rank all right so now
11:08:36
우리는 같은 작업을 수행하여 주문을 판매량에 따라 가장 높은 것부터
we have the same task rank the orders based on their sales from highest
11:08:39
가장 낮은 것까지 순위를 매길 것입니다. 그래서 이번에는 같은 작업을 할 것입니다.
to lowest so we're gonna do the same stuff but this time using
11:08:43
밀집 순위 함수를 사용하여, 밀집 순위는
the function dense rank so dense rank
11:08:46
비어 있을 것이고, 그런 다음 다른 것들과 마찬가지로 정의할 것입니다.
is gonna be empty and then we're gonna define it like all others
11:08:49
판매량에 따라 정렬합니다.
over order by sales disk
11:08:52
그리고 나서 우리는 그것의 이름을 판매 순위 밀집으로 정할 것입니다.
and then we're gonna give it the name of sales rank dense and
11:08:56
그게 전부입니다. 보시다시피, 모든 함수가 정확한 구문을 가지고 있습니다. 자, 이제
that's it so as you can see all of those functions having the exact syntax right so let's
11:09:01
실행해 보겠습니다. 알겠죠, 이제 결과를 확인해 보겠습니다.
go and execute it okay so now let's go and check the results we
11:09:05
우리는 밀집을 사용하여 가장 최근의 순위를 얻었습니다. 단순히 확인해 보니
got our newest rank using the dense and by just checking
11:09:08
결과에서 동점을 처리하는 것을 볼 수 있습니다. 우리는 두 번
the results you can see that it handles the tie we have two
11:09:11
있습니다. 자, 예제를 확인해 보겠습니다.
twice right so let's check the example
11:09:14
여기에서 우리는 판매량 60이 두 번 있습니다. 그래서
over here we have the sales 60 twice that's
11:09:17
그들이 밀집 순위에서 같은 순위를 공유하는 이유입니다.
why they are sharing the same ranking in the dense and as
11:09:20
정상 순위에서도 마찬가지입니다. 그런데 지금 흥미로운 것은
well in the normal rank but now what is interesting is the
11:09:23
동점 이후의 값입니다. 보시다시피, 밀집 순위에서는 3이 있습니다. 그래서 우리는 어떤 순위도 пропуска하지 않았습니다.
value after the tie so as you can see over here with the dense rank we have three so we didn't skip any ranking we don't
11:09:30
간격이 없습니다. 1, 2, 그리고 3이 있습니다. 하지만
have any gap one two and then three but with
11:09:33
순위는 단지 위치 번호에만 집중합니다. 그래서
the rank it's just focus on the position number so
11:09:36
그것은 4번 행입니다. 그래서 4입니다.
it is the row number four that's why it's four with
11:09:39
우리는 간격이 있습니다. 보시다시피, 이제 우리는 어떤 간격도 없습니다.
us we have a gap so as you can see now we don't have any gaps
11:09:43
밀집 순위에서 우리는 3, 4, 5가 있습니다.
in the dense rank so we have three four five and
11:09:46
이제 우리는 여기에서 같은 두 값을 가지고 있습니다. 그래서
now we have over here the same two values so we
11:09:49
2020년의 판매량이 있으며, 그들은 6을 두 번 공유합니다.
have sales of 2020 and they share the six twice
11:09:52
보시다시피, 밀집 순위와 일반 순위 사이에 차이가 있습니다. 여기서는 7, 7이지만, 여기서는 6, 6입니다.
so as you can see there is difference now between the dense and the rank so here we have seven seven but here we are at the rank six six so
11:09:59
그래서 우리가 차이를 보이는 이유는 이전에 건너뛰었기 때문입니다.
that's why we have differences between them because we skipped before in
11:10:02
순위 번호 3을 건너뛰었기 때문에 다른 것들을 볼 수 있습니다.
the rank number three now the other stuff you can see we have seven and
11:10:05
여기서 우리는 7과 8을 가지고 있습니다.
eight so now if you compare those three ranking you can
11:10:08
이 세 가지 순위를 비교하면 모두 순위 번호 1로 시작하지만
see that they all start with the rank number one but
11:10:12
모두 같은 순위로 끝나지는 않았습니다.
they didn't all end with the same ranking so the row number and the rank they really focus on the position number or the row number of the orders
11:10:21
그래서 여기서 10번 행을 볼 수 있습니다.
So you can see over here, it is the row number 10. That's why we have here 10 and 10. So the scale is from 1 to 10.
11:10:28
그래서 우리는 여기서 10과 10을 가지고 있습니다.
And that is exactly the same for the row number from 1 to 10. But with the dens over here, we have it from 1 to 8.
11:10:35
그래서 스케일은 1에서 10까지입니다.
And that's because we shared the same ranking. And with that, we wasted, let's say, a few ranks.
11:10:41
하지만 여기서 밀도가 1에서 8까지입니다.
So the scale is different from the two others. And that's because we have ties twice. This is one tie.
11:10:47
그래서 우리는 같은 순위를 공유했기 때문에 몇 개의 순위를 낭비했습니다.
And as well, we have over here one tie. That's why we are missing over here two ranks. So this is how the dense ranks works.
11:10:54
그래서 스케일은 두 다른 것들과 다릅니다.
And you can go and compare now all three together in order to understand how those ranks are working.
11:11:03
그리고 우리는 두 번의 동점이 있습니다.
All right. So now let's quickly compare the three functions side by side. Let's start with the first point about the uniqueness of the rank.
11:11:09
이것이 하나의 동점입니다.
And if you compare those three, you can see that only the row number generates unique distinct rank. So this is going to be unique rank.
11:11:17
그리고 여기서도 하나의 동점이 있습니다.
and the two others we have duplicates or let's say shared
11:11:20
그래서 우리는 여기서 두 개의 순위를 놓치고 있습니다.
ranks okay so now the second point whether the function handles
11:11:23
그래서 이것이 밀집 순위가 작동하는 방식입니다.
the ties and the only one that doesn't handle the ties is
11:11:26
그래서 이제 세 가지를 모두 비교할 수 있습니다.
the row number so this one doesn't handle the
11:11:29
이 순위가 어떻게 작동하는지 이해하기 위해서입니다.
ties and the two others handles the ties since
11:11:33
좋습니다. 이제 세 가지 기능을 나란히 비교해 보겠습니다.
they offer the shared rank and now we have the last point about
11:11:36
순위의 독특성에 대한 첫 번째 포인트부터 시작하겠습니다.
leaving gaps or skipping ranking so now
11:11:39
세 가지를 비교하면 오직 행 번호만 고유한 순위를 생성합니다.
if you check the row number and the dense rank you can see there will be no skipping so there is no gaps for the
11:11:45
그래서 이것이 고유한 순위가 될 것입니다.
row number and as well for the dense rank only
11:11:49
그리고 나머지 두 개는 중복되거나 공유됩니다.
for the rank function the middle one we are skipping ranks
11:11:52
좋습니다. 이제 두 번째 포인트로 넘어가겠습니다.
and we are leaving gaps so that's it guys this is the differences between those three functions i tend usually to work with the row number more often than the two others
11:12:05
함수가 동점을 처리하는지 여부입니다.
all right guys so now i had to look to those three functions and i checked my projects
11:12:10
실제 프로젝트에서 많은
real projects and i found out that there are many
11:12:13
함수 행 번호에 대한 사용 사례가 있습니다
use cases for the function row number compared to
11:12:16
다른 함수인 밀집 순위와 순위에 비해
the other functions dense rank and rank so now what we're
11:12:19
우리가 할 일은 순위 번호에 대한 몇 가지 사용 사례를 보여주는 것입니다
gonna do i'm gonna show you a few use cases for the rank number that
11:12:23
내 실제 프로젝트에서 일반적으로 사용하는 것입니다
i usually use in my real projects in order for you to
11:12:26
원시 번호 함수의 중요성을 이해하기 위해
understand how important is the raw number function so
11:12:29
SQL로 가보겠습니다. 자, 이제 첫 번째 사용 사례를 시작하겠습니다. 각 제품에 대한 최고 판매량을 찾는 작업이 있습니다.
let's go to sql all right so now let's start with the first use case and we have the task of find the top highest sales for each product so this is very
11:12:37
보고서나 데이터 분석에서 매우 전형적입니다.
classic in reporting or data analysis we
11:12:40
우리는 이를 상위 분석이라고 부릅니다.
call this top end analysis so here the
11:12:43
여기서 관리자나 의사 결정자는
managers or decision makers they would like to have the
11:12:46
우리 데이터에서 최고의 성과나 성공을 원합니다.
best performance or the best success in our data so
11:12:49
예를 들어, 상위 다섯 고객이나
for example the top highest five customers or
11:12:52
상위 다섯 제품 또는 카테고리 등을 포함합니다.
the top five products or categories and so on so
11:12:56
이는 최고의 제품이나 가장 중요한 고객에 집중하기 위한 매우 중요한 분석입니다.
this is very important analysis in order to focus on the best products or on to the most important customers
11:13:02
이는 매우 전형적이며
and so on and this is as i said very classic and very
11:13:05
비즈니스에서 결정을 내리기 위해 중요합니다.
important in order to make decisions in the business so
11:13:09
이 문제를 해결하는 방법을 살펴보겠습니다.
now let's see how we can solve this so we're gonna start with the usual stuff let's first select the data so select order id let's take as well the product id and the sales
11:13:18
판매 주문에서
from sales orders so
11:13:21
이제 실행해 봅시다. 각 제품에 대해 알고 있는 것처럼
let's go and execute this and now as we know that for each product
11:13:24
우리는 여러 주문과 여러 판매가 있지만
we have multiple orders and we have multiple sales but we are
11:13:27
각 제품의 최고 판매량에만 관심이 있습니다. 그래서 우리는
interested only in the highest sales for each product so we
11:13:30
순위를 만들어야 합니다. 그렇게 하려면
have to go and create a rank in order to do that we can use the
11:13:34
행 함수인 행 번호를 사용할 수 있습니다.
row function row number and we have
11:13:37
이제 창을 정의해야 합니다. 그래서 파티션이 필요합니까?
to define the window now so do we need partition by check
11:13:40
쿼리를 확인하세요. 각 제품에 대해 이렇게 말합니다.
the query so it says for each product that
11:13:43
즉, 우리는 데이터를 제품 ID로 나누어야 합니다.
means we have to divide the data by the product id so
11:13:46
제품 ID로 파티션을 사용하고 이제 정렬을 사용해야 합니다.
let's go and use the partition by products id and now we must use the order by so order by and now how to sell the data
11:13:56
판매 권리를 구매하며, 이는 최고에서 최저로입니다.
buys a sales right and it is from the highest to the lowest
11:13:59
판매를 진행합시다.
so let's go sales and we have
11:14:02
여기서 내림차순으로 최고에서 최저로 진행합시다.
here descending so from highest to lowest let's go and give
11:14:05
이름을 지정합시다. 제품별로 순위가 매겨질 것입니다.
it a name so you're going to be ranked by products
11:14:08
이제 실행합시다.
so let's go and execute this
11:14:11
결과를 보면 기술이 데이터를 제품 ID로 나누었다는 것을 알 수 있습니다.
and now by looking to the results you can see that is skill did divide
11:14:14
여기서 약 네 개의 창이 있습니다. 첫 번째 창에서 볼 수 있습니다.
the data by the product id so we have here like
11:14:17
순위는 1부터 시작하며, 4로 되어 있습니다.
around four windows the first one over here you can see that the
11:14:20
순위는 8번 주문으로, 판매량은
rank starts from one it's with four so the highest
11:14:24
90이며, 이제 4로 넘어갑니다.
rank can be the order number eight with the sales of
11:14:27
두 번째 창에서 새로운 순위를 볼 수 있습니다.
90 and then it goes to the four now
11:14:30
첫 번째가 리셋되고 순서가 됩니다.
as you can see that the second window we have a new ranking so
11:14:33
10번과 마지막은 2번 주문이 될 것입니다.
it resets the first gonna be the order
11:14:37
각 창마다 고유한 순위가 있습니다.
number 10 and the last one gonna be order number two so as
11:14:40
마지막 창은 단 한 줄만 있습니다.
you can see each window has its own ranking and
11:14:43
이제 물론, 작업에서 가장 높은 것을 반환해야 하므로 다른 것에는 관심이 없습니다.
as well the last one we have it only as one row so
11:14:46
모든 것을 반환해야 합니다.
now of course in the task we have to return the highest so we are not interested in the others we have to return this row this row as well and this one
11:14:54
순위가 1인 것만 반환해야 하며, 순위 2에는 관심이 없습니다.
and this one so as you can see we have to return everything
11:14:57
3, 4 등등이 있으며, 가장 높은 것을 원합니다.
that has the rank one we are not interested in the rank two
11:15:00
데이터를 필터링하기 위해 할 일은
three four and so on so we would like to have the highest so
11:15:04
서브 쿼리를 사용하여 선택합니다.
now in order to filter the data what we're going to do we're going to go and
11:15:07
다음 조건을 가질 것입니다.
use sub queries so select star from
11:15:11
제품별로 순위를 매깁니다.
and then we're going to have the following condition so where
11:15:14
제품별로 순위를 매기겠습니다.
and we're going to say rank by products
11:15:18
1위에 해당하는 제품만 관심이 있으므로 실행해 보겠습니다. 데이터에 4개의 제품이 있으므로 4개의 행만 나오고, 가장 높은 판매량을 가지게 됩니다.
equals to one so we are interested only on the rank number one so let's go and execute it And with that, since we have four products in our data, we're going to have only four rows and we have the highest sales.
11:15:30
보시다시피, 여기 1위만 있고 각 제품의 판매량이 가장 높습니다.
So as you can see, we have only number one over here and those sales are the highest for each product.
11:15:35
이제 우리는 최상위 분석가를 찾아 작업을 해결했습니다.
And with that, we have solved the tasks by finding the top end analyzers.
11:15:44
다음 사용 사례로 넘어가겠습니다. 다음 작업은 총 판매량을 기준으로 가장 낮은 두 고객을 찾는 것입니다.
OK, moving on to the next use case, we have the following task and it says find the lowest two customers based on their total sales.
11:15:50
이제 우리는 정반대의 사용 사례를 가지고 있습니다.
So now we have the exact opposite use case.
11:15:54
우리는 분석에서 버튼이라고 부릅니다.
we call it button in analysis so
11:15:57
이 예제에서 비즈니스의 의사 결정자들은
now in this example in the business the decision makers want
11:16:00
비용을 최적화하고 비용을 절감하려고 합니다.
to optimize the costs want to cut costs and
11:16:03
그들은 최저 성과자들을 분석해야 합니다.
with that they have to analyze the lowest performers in
11:16:07
제품 또는 직원 중 가장 낮은 성과
the products or the lowest performance in the employees in
11:16:10
비용을 절감하기 위해 이제 이 분석으로 의사 결정자들은 가장 성공적인 것에 집중하지 않고 가장 낮은 성과에 집중하고 있습니다. 이제 이 작업을 해결해 봅시다. 질문을 확인해 보세요.
order to cut costs so now with this analysis the decision makers are not focusing on the best successful stuff we are focusing on the lowest stuff the lowest performers so now let's solve these tasks so if you check the question
11:16:23
우리는 여러 가지가 있습니다. 총 판매와
we have multiple stuff right we have the total sales and
11:16:26
가장 낮은 두 고객을 찾아야 합니다. 그래서 우리는
as well we have to find the lowest two customers so we have
11:16:29
순위와 집계를 기억해야 합니다. 우리는 할 수 있습니다.
ranking and as well aggregations remember we can do
11:16:32
그룹과 함께 작업을 수행합니다. 이제 단계별로 진행해 봅시다.
stuff together with a group i so now let's do it step by step
11:16:35
먼저 데이터를 선택합시다. 필요한 것은 주문 ID, 고객
first let's select the data right so what do we need order id customer
11:16:39
ID와 판매량입니다.
id and we need the sales from
11:16:42
판매 주문에서. 이제 실행해 봅시다. 고객을 확인해 보면 약 네 명의 고객이 있으며 여러 번의 판매가 있습니다.
sales orders so let's go and execute this so now if you check the customers over here we have around four customers and they have multiple sales
11:16:52
이제 가장 낮은 두 고객을 찾기 위해 각 고객의 총 판매량을 원합니다. 먼저 집계부터 시작합시다.
now we would like to have the total sales for each customers in order to find the lowest two so let's start first with the aggregations so what we're gonna do we're gonna go and aggregate
11:17:01
판매를 집계합니다. 판매의 합계를
the sales so the sum of sales let's
11:17:04
총 판매라고 부릅시다. 이제
call it total sales and now in order to do the
11:17:07
그룹화를 하려면 고객만 있어야 합니다.
group by we have to have only the customer so
11:17:11
그룹화하고 고객 ID가 있습니다.
group by and we have the customer id so
11:17:14
매우 간단한 그룹화 문장입니다. 진행해 봅시다.
it is very simple group by statements let's go and
11:17:17
실행해 보겠습니다. 결과를 확인해 보면 SQL이 집계한 것을 볼 수 있습니다.
execute this so now by checking the result we can see that sql did aggregate
11:17:20
데이터가 네 개의 행으로 나타나며, 이는 고객이 네 명 있기 때문입니다.
the data we have four rows and that's because we have four customers
11:17:24
그리고 우리는 그들의 총 매출을 가지고 있으므로, 첫 번째 작업을 해결했습니다.
and we have their total sales so we have solved the
11:17:27
각 고객의 총 매출을 가지고 있습니다. 이제 두 번째 부분으로 넘어갑니다.
first part of the task we have the total sales for each
11:17:30
최저 두 고객을 찾으라는 것입니다. 즉, 우리는
customers now let's move to the second part it says
11:17:33
랭킹 함수를 사용하여 그 고객들을 순위 매겨야 합니다.
lowest two customers that means we have to use the
11:17:36
모든 고객에 관심이 있는 것이 아니라 최저 두 고객만 관심이 있습니다. 그래서 이를 위해
ranking functions in order to rank those customers so
11:17:40
윈도우 함수를 사용할 것입니다. 그래서
we are not interested in all customers we are interested only in the lowest two so in order to do that now we're going to go and use the window
11:17:47
행 번호를 사용하고, 그리고
function row number so and then
11:17:50
이제 데이터를 파티션해야 할까요?
over now do we have to partition the data
11:17:53
아니요, 우리는 그렇게 할 필요가 없습니다. 이제
well no we don't have to do that we have now to
11:17:56
데이터를 정렬해야 합니다. 그래서 이번에는
sort the data so order by so this time
11:17:59
집계를 사용하여 정렬할 것입니다. 그래서
we're going to go and use the aggregations in the order by so the
11:18:02
매출의 합계를 가지고 있으며, 이를 최저에서 최고로 정렬하고 싶습니다.
sum of sales and we want to have it sorted from the
11:18:05
그래서 기본값을 사용하겠습니다. 오름차순으로 정렬하겠습니다. 이제
lowest to the highest so i'm just going to go and use the defaults so it is ascending now let's call it
11:18:12
고객의 순위를 매기겠습니다. 다시 한 번
rank customers so that's it again
11:18:15
여기서 규칙은 윈도우 함수를 그룹화 함수와 함께 사용할 때
here the rule is that if you are using a window function together with
11:18:19
그룹화에 사용된 열만 사용해야 한다는 것입니다. 그래서 이 작업이 잘 될 것입니다.
the group by function you have to use only columns that
11:18:22
이제 결과를 실행해 보겠습니다. 결과에서 추가 열을 얻었습니다.
is used in the group by so this should be working let's go and
11:18:26
순위에 대한 것입니다. 이제 최저 고객은 고객 번호 2가 될 것이고, 두 번째는 90의 총 매출을 가진 4가 될 것입니다.
execute it so now as you can see in the results we got an extra column for
11:18:29
가장 높은 고객은 마지막 고객이 될 것입니다. 125 고객 번호 3입니다. 이제 우리는
the rank so now the lowest customer gonna be the customer number two the second one gonna be four with the 90 total sales and the highest customer with the sales gonna be the last one
11:18:39
거의 모든 것을 갖추었지만, 목록에는 마지막 두 개만 포함되어야 합니다.
the 125 customer number three so now we
11:18:43
그래서 이를 위해 데이터를 필터링해야 합니다. 우리는
have almost everything but the list should contain only the last
11:18:46
서브 쿼리를 사용할 것입니다. 그래서 스타를 선택합니다.
two so in order to do that to filter the data we're gonna go
11:18:49
그리고 조건을 정의해야 합니다.
and use sub query so select star from
11:18:53
그런 다음 조건을 정의해야 합니다.
and then we have to define the condition where
11:18:56
고객 순위는 작아야 합니다.
rank customers it should be smaller
11:19:00
또는 두 개와 같아야 합니다. 그러면 처음 두 개를 얻을 수 있습니다. 이제 실행해 보겠습니다. 그렇게 해서 총 판매량에 따라 가장 낮은 두 고객을 얻었습니다.
or equal to two right so with that we will get the first two so let's go and execute this and with that we we got the lowest two customers based on their total sales.
11:19:09
고객 번호 ID 2와 4입니다. 이제 우리는 이 작업을 해결했습니다. 분석 버튼을 완료했습니다.
So customer number ID two and the four. So that's it. We have solved the task and now we have done button in analysis.
11:19:20
이제 다음 사용 사례로 넘어갑니다. 다음 작업이 있습니다.
Okay, let's keep moving to the next use case and we have the following task.
11:19:23
주문 아카이브 테이블의 행에 고유 ID를 할당하라고 합니다.
It says assign unique IDs to the rows of the table orders archive.
11:19:29
이제 여러분은 기본 키가 없는 테이블이 있을 수 있으며 각 행에 대한 ID를 생성하고 싶을 것입니다.
So now guys, we might be in a situation where you have a table without any primary key and you would like to create an ID for each row.
11:19:36
이를 위해 row number 함수를 사용하여 테이블 내 각 행에 대한 고유 식별자 ID를 생성할 수 있습니다.
So in order to do that, we can use the function row number in order to generate unique identifier IDs for each row inside our table if we don't have one.
11:19:46
각 행에 대한 ID를 생성하는 것은 데이터 가져오기, 내보내기, 테이블 조인 및 쿼리 성능 최적화와 같은 작업을 수행하는 데 매우 중요합니다.
And generating such ID for each row, it's very important to do stuff like importing data, exporting data, maybe joining tables as well using this ID, or let's say optimizing the performance of query using the ID.
11:19:57
이제 그것을 생성하는 방법을 살펴보겠습니다.
So now let's see how we can generate that.
11:20:00
row number를 사용하여 먼저 선택해 보겠습니다.
using row number okay so now let's first select the
11:20:03
주문 아카이브 테이블의 내용을 이해하기 위해 선택합니다.
table order archives in order to understand the content so
11:20:06
판매 주문 아카이브에서 모든 항목을 선택합니다.
select star from sales orders archive
11:20:10
이제 실행해 보겠습니다. 결과를 확인하면 10개의 주문이 있습니다.
so let's go and execute so now by
11:20:13
주문 ID에 반복이 있으므로 기본 키가 아닙니다.
checking the results you can see that we have 10 orders and
11:20:16
여기에서 두 번 나타나는 것을 볼 수 있습니다.
we have repetitions in the order id over here so it is not
11:20:19
여기에서 ID4가 두 번, ID6이 세 번 나타납니다.
really a primary key as you can see over here we have twice
11:20:22
이제 고유 식별자를 생성할 것입니다.
the id4 and here we have three times the id6
11:20:25
각 행에 대해 생성할 것입니다. 이를 위해 할 작업은
so now what we're gonna do we're gonna go and generate unique identifier for
11:20:29
여기에서 row number를 사용하겠습니다.
each row so in order to do that what you're gonna do I'm
11:20:33
그런 다음 윈도우 함수를 정의할 것입니다. 데이터를 파티셔닝하지 않습니다.
gonna go over here and say row number and
11:20:36
데이터를 전혀 파티셔닝하지 않지만 데이터를 정렬해야 합니다.
then we're gonna define the window function we don't partition
11:20:39
주문 ID로 정렬합니다.
the data at all but we have to sort the data by the
11:20:42
주문 ID로 정렬합니다.
order ID so order by order
11:20:46
ID 또는 주문 날짜를 사용할 수 있습니다. 상관없습니다. 주문 날짜도 추가해 보겠습니다.
ID or you can use something else as well using the order date or something doesn't matter so let's add to its order date as well let's call it
11:20:56
고유 ID를 실행해 보겠습니다.
unique ID let's go and execute this
11:21:00
이제 데이터를 확인하면 새로운 ID가 생겼음을 알 수 있습니다.
now by checking the data you can see that we have a new ID
11:21:03
여기서 행 번호에서 가져온 것입니다.
over here that comes from the row number and
11:21:06
고유 식별자가 있으며, 우리는 열이 10개 있습니다.
we have like a unique identifier as you can see we have ten
11:21:09
행이 있으며, 우리는 10개의 서로 다른 고유 ID가 있습니다.
rows and with that we have as well ten different distinct
11:21:13
이로써 작업을 해결했습니다.
unique IDs so with this as you can see we have solved the task
11:21:16
이제 고유 식별자, 즉 주문 테이블 아카이브의 ID가 생겼습니다. 이 ID를 사용하여 여러 작업을 수행할 수 있습니다.
and we have now a unique identifier an ID for the table orders archive so now having this ID we can do many stuff like joining tables or doing
11:21:24
특별하고 중요한 작업인 페이지 매김을 할 수 있습니다. 상상해 보세요.
something special and important called paginating imagine
11:21:28
우리는 거대한 테이블이 있으며, 데이터를 검색하고 싶습니다.
we have like a huge table and we would like to retrieve
11:21:31
모든 데이터를 한 번에 가져오지 않기 위해 데이터를 기본으로 나눌 수 있습니다.
the data so now in order to not have all the
11:21:34
ID 또는 고유 식별자로 데이터를 나눌 수 있습니다.
data in one go we can go and divide the data by the primary
11:21:37
1부터 100,000까지의 페이지를 만들 수 있으며, 두 번째 페이지는 100k에서 200k까지 시작합니다.
id or by unique identifier for example we can make a
11:21:40
데이터를 나누면 데이터 내보내기 또는 가져오기를 개선할 수 있습니다.
page from one until 100 000 and then the second page starts from 100k to 200ks so now by dividing the data we can maybe
11:21:49
사용자에게 더 빠른 검색을 제공할 수 있습니다.
improve exporting or importing data or
11:21:52
모든 데이터를 한 번에 가져오고 싶지 않기 때문에 많은 이점이 있습니다.
we can have faster retrieval for the users we don't want to have the
11:21:55
페이지 매김을 사용하면 많은 이점이 있으며, 우리는 그것을 할 수 있습니다.
whole data in one go in one page so it has a lot of
11:21:58
이런 좋은 아이디어가 있다면 가능합니다.
benefits using paginating and we can do that only
11:22:01
이런 멋진 아이디어가 있다면
if we have a nice idea like this all
11:22:07
좋아요, 이제 제가 실제 프로젝트에서 주로 사용하는 함수인 행 번호의 마지막 사용 사례를 보여드리겠습니다. 가끔 데이터 분석을 할 때
right so i'm going to show you the last use case for the function row number that i usually use in my real projects so sometimes if you are doing
11:22:14
데이터 품질 문제를 발견하게 될 것입니다.
data analysis you're going to find out that there are data quality issues
11:22:17
특히 중복 데이터와 관련하여, 제가 주로 사용하는 것은
especially with the duplicates so what i usually use
11:22:21
중복을 식별하기 위해 행 번호를 사용합니다.
i use the row number in order to identify the duplicates
11:22:24
그뿐만 아니라, 중복을 삭제하는 데도 사용할 수 있습니다.
not only that i can use it in order to delete the
11:22:27
따라서 데이터 정리를 위해 사용할 수 있습니다.
duplicates so we can use it in order to do data cleansing
11:22:30
이것은 모든 데이터 엔지니어에게 필수적인 작업입니다.
and this is essential task for each data engineer
11:22:33
데이터 분석을 하기 전에 데이터를 준비하고 정리하기 위해 데이터 분석가뿐만 아니라
not only data analysts in order to prepare and clean up the data before doing data analysis so let's have the following task identify duplicate
11:22:42
주문 아카이브 테이블에서 중복된 행을 식별하고
rows in the table orders archive and return a
11:22:45
중복 없이 깨끗한 결과를 반환해야 합니다. 따라서 우리는
clean result without any duplicates so not only we have to
11:22:48
중복을 식별해야 하며 중복이 없는 결과를 반환해야 합니다.
identify the duplicates we have to return no duplicates
11:22:52
우리의 결과에서 이를 수행하는 방법을 살펴보겠습니다. 먼저
in our results so let's see how we can do this let's first select
11:22:55
데이터를 선택합니다. 따라서 sales orders에서 star를 선택하세요.
the data so select star from sales orders
11:22:58
아카이브를 실행해 보겠습니다.
archive so let's go and execute so
11:23:02
지금 데이터를 보면 중복이 있다는 것을 알 수 있습니다. 문제가 있습니다.
now by looking to the data you can see that we have duplicates we have an issue so
11:23:05
다른 ID 번호 4가 데이터베이스에 두 번 있습니다. 말이 되지 않죠? 하나만 있어야 합니다.
the other id number four is twice in our database it doesn't
11:23:08
어떤 것이 올바른 것인지 확인해 보면
make sense right it should should be only one so which one is the correct one if you check the data over here you can see that
11:23:14
이 주문은 배송되고 배달되었습니다.
this order is shipped and then delivered so it
11:23:17
마지막 것이 올바른 것 같습니다.
looks like the last one is the correct one so
11:23:20
그것을 어떻게 할 수 있을까요? 오른쪽으로 스크롤하면
how we can do that if you just scroll to the right you can see
11:23:23
생성 시간이 있다는 것을 볼 수 있습니다. 우리는 보통
that we have a creation time and we usually use
11:23:26
이런 타임스탬프를 사용하여 마지막 유효한 주문을 식별합니다.
such a timestamp in order to identify what was
11:23:30
여기서 우리는 이 주문 시간이 이전 것보다 높다는 것을 즉시 알 수 있습니다.
the last valid like order and here we can see immediately that this order time is higher than the previous one which means this
11:23:38
더 최신의 것이라는 것을 의미합니다. 따라서
is the more up to date right the more current so
11:23:41
우리가 할 것은 각 주문 ID에 대해 데이터를 정렬하는 것입니다.
what we're gonna do we're gonna go and rank our data for each
11:23:44
생성 시간에 따라 데이터를 정렬합니다.
order id and sort the data by the creation time
11:23:47
마지막으로 삽입되거나 생성된 행을 찾기 위해
in order to find the last inserted or created
11:23:51
여기서 행 번호를 설정하고, 파티션을 나누겠습니다.
row for this order so let's see how we can do that what we're gonna do we're gonna go over here and say let's have a row number and then over and what we're gonna do we're gonna partition by
11:24:03
기본 키로, 따라서 주문 ID로 파티션을 나누고
the primary key so partition by order id and as we said we have to order the data by
11:24:09
생성 시간에 따라 정렬합니다.
this times tab at the ends so partition by or
11:24:12
내림차순으로 정렬합니다.
order by creation time and
11:24:15
그게 전부입니다. rn이라고 부르고 실행합시다.
descending so we want the highest then the lowest so
11:24:18
그게 다야, 지금 부르자 그리고 실행하자
that's it let's call it rn and execute
11:24:21
쿼리, 그래서 이제 데이터를 확인해보면 모든 것이 깨끗하고 중복이 없다면 모든 것이 하나여야 해
the query so now by checking the data if everything is clean and we don't have duplicates everything should be one because
11:24:28
각 기본 키에 대해 최대 하나의 행이 있어야 해
maximum for each primary key we should have one row
11:24:31
그래서 여기서 두 개가 있고 여기서 세 개가 있다는 것을 볼 수 있어
so but you can see over here we have here two and we have here three two
11:24:35
그래서 이것은 우리가 중복이 있다는 지표라는 것을 의미해
so that means this is indicator that we have duplicates
11:24:38
우리 데이터 안에서 이제 하나씩 확인해보면 순서를 볼 수 있어
inside our data so now by checking one by one as you can see the order
11:24:41
id는 하나뿐이어서 우리는 1위와 두 번째를 가지고 있어
id is only one so we have the rank one the second
11:24:44
하나도 마찬가지로 1위를 가지고 있지만 여기서는
one as well we have the rank one but here we have the
11:24:47
문제가 있어, 그래서 이제 주문 id 4에 대해 두 개의 순위가 있다는 것을 볼 수 있어, 그래서 어떤 것이 올바른지
issue so as you can see we have now two ranks for the order id four so now which one is the correct in our logic we said it is the last row that is inserted inside our data.
11:24:58
그리고 이것이 1위야. 오른쪽으로 스크롤하면 여기 생성 시간이 두 번째보다 더 높다는 것을 볼 수 있어
And this is rank number one. So if you scroll to the right side, you can see that the creation time here is higher than the second one.
11:25:05
그래서 우리는 원하는 것을 확인했어. 각 ID에 대해 마지막으로 삽입된 행을 원해
So with that, we have identified what we want. We want the last inserted row for each ID.
11:25:12
이제 여기서 확인해보자. 여기 세 번 나타나, 그래서 첫 번째가 가장 높은 생성 날짜라고 해
And now let's check this over here. So here we have it three times. So it says the first one is the highest creation date.
11:25:19
오른쪽으로 가면 이제 그 타임스탬프를 비교해보면 이 기록을 볼 수 있어
So if you go to the right side and now by comparing those timestamps, you can see that this records.
11:25:25
첫 번째는 우리 데이터 안에 삽입된 최신 것이야
The first one is the latest one that is inserted inside our data.
11:25:29
그래서 이 하나가 우리가 필요한 것이야. 나머지 두 개는 오래된 정보라 필요 없어
So as you can see, this one is the one that we need. The other two, we don't need it because it is old information.
11:25:36
이제 1위가 아닌 모든 것은 유효하지 않아. 오래된 것이고 실제로 데이터 품질이 나빠
So now everything that doesn't has the rank number one is not valid. It's something old and it's actually bad data quality.
11:25:43
그래서 우리는 그것을 제거하거나 선택하지 않으려 해. 깨끗한 데이터를 위해서, 우리는 다음을 서브 선택할 거야
So we want to remove it or not to select it. So in order to have a clean data, what we're going to do, we're going to go and select the following as subselect.
11:25:51
그래서 테이블에서 모든 것을 선택해. 그리고
So select star from the table. and
11:25:54
이제 우리는 1위만 관심이 있어
now we are interested only with the rank
11:25:57
우리는 다른 것이 필요 없어, 그러니까 가서 실행하자
number one we don't need anything else so let's go and execute
11:26:01
결과를 확인하면 여기서 주문 id를 확인할 수 있어
and if you check the results you can check the order id over here it
11:26:04
고유하고 중복이 없어, 하나, 둘, 셋, 넷
is unique we don't have any duplicates right one two three four
11:26:07
다섯, 여섯, 일곱, 전혀 중복이 없어
five six seven there is no duplicates at all and
11:26:10
우리는 이제 최신으로 삽입된 데이터만 가지고 있어
we have now only the latest inserted data inside the
11:26:13
주문들 안에서 중복이나 데이터 품질 문제도 없어, 그래서 이제 이 결과로 더 진행할 수 있어
orders and we don't have any duplicates or data quality issue so now of course now we can go with this result in order to do further
11:26:20
분석하고 이것이 데이터 엔지니어들이 보통 하는 일입니다
analyzes and this is exactly what data engineers usually do
11:26:23
데이터를 정리하고 데이터를 준비하기 전에
clean up the data and prepare the data before doing
11:26:26
어떤 데이터 분석을 하고 싶다면
any data analyzes and of course if you want to communicate
11:26:29
그 데이터 품질 문제를 데이터 출처에 전달해야 합니다
those data quality issues to the source of the data let's say you
11:26:32
그 정보의 소유자가 아니라면
are not the owner of those informations you can generate a
11:26:35
모든 나쁜 데이터 품질 문제의 목록을 생성할 수 있습니다
list of all bad data quality issues and you can send it
11:26:38
원본 시스템에 보내고 그들이 출처에서 정리하도록 요청합니다
to the source system and tell them to clean it up from the sources so now in order to select the bad data what we're going to do is we can just
11:26:45
여기서 조건을 변경하고 그것이 더 높다면
change here the condition and say if it is higher than
11:26:48
하나라면 당신은 나쁜 데이터입니다
one then you are like bad data so
11:26:51
이것을 실행해 보겠습니다. 이제 결과가 있습니다
let's go and execute this and now with this we have in the results
11:26:55
데이터에 존재하지 않아야 하는 모든 기록입니다
all records that shouldn't exist in the data in the
11:26:58
우리는 그것을 내보내고 소통할 수 있습니다
first place so we can go and export it and communicate it to
11:27:01
여기에서 당신의 시스템에 문제가 있습니다
the source and tell them check here you have something wrong in your system and those informations should not be inserted in the data so everyone it is very strong right it is very powerful i use it a lot in my projects
11:27:12
SQL의 행 번호 함수에 대한 많은 사용 사례가 있습니다
there are many use cases for the row number function in sql
11:27:15
상위 분석을 찾기 위해 할 수 있습니다
we can do it in order to find the top end analyzes
11:27:18
하위 분석, 최고의 성과와 최악의 성과
the bottom end analyzes the best performance worst performance
11:27:21
고유 ID를 할당하여 페이지 매김을 할 수 있습니다
and as well we can assign unique ids to do paginating
11:27:24
데이터 품질 문제를 발견하기 위해 사용할 수 있습니다
or we can use it in order to discover data quality
11:27:28
SQL에서 매우 간단한 기능입니다
issues to clean up our data so it is amazing function in sql and you're going to use it a lot so that's it for the three functions row number rank dense rank now we're going to talk about the n tile
11:27:41
행을 나누고 데이터를 거의 같은 그룹으로 나눕니다
Okay, so what is entile? Entile in SQL is very simple.
11:27:45
이것을 이해하기 위해 간단한 예제를 살펴보겠습니다
It's going to go and divide your rows, your data into a specific number of almost equal groups, or sometimes we call them packets.
11:27:53
판매를 위한 네 개의 행이 있습니다
So now in order to understand this and how SQL works with this function, we're going to have a very simple example. So let's go.
11:27:59
두 그룹 또는 두 패킷으로 나누고 싶습니다
Okay, we have the following setup. We have four rows for sales, and we would like to divide it into two groups or into two packets.
11:28:06
전체 함수를 사용할 수 있습니다
So in order to do that, we can use the entire function
11:28:09
다른 순위 함수와는 다른 구문을 가지고 있습니다
it has different syntax than the other ranking functions
11:28:12
그래서 전체로 시작한 다음
so it starts with entire then we
11:28:15
숫자를 정의해야 하므로 비워둘 수 없습니다
must define a number so we cannot leave it empty like
11:28:18
다른 순위와 여기 두 개의 버킷이 있습니다
the other ranking so here we have two buckets then
11:28:22
이 데이터를 다시 정렬해야 하므로
over and here again we have to sort the data so it is
11:28:25
판매량에 따라 내림차순으로 정렬해야 합니다
must order by sales descending from the highest
11:28:28
최고에서 최저까지 그래서 이제는
to the lowest so now as usual is going to go and sort the data we have it already sorted in this example then it can start assigning each of those
11:28:35
패킷으로 행을 나누지만 SQL은 먼저
rows into packets but sql first has
11:28:38
패킷 크기를 계산해야 하므로 몇 개의 행을
to calculate the pocket size so how many rows
11:28:42
각 패킷 안에 삽입할 수 있는지
we can like insert inside each packet so
11:28:45
계산은 매우 간단합니다. 패킷 크기는
the calculation is very simple it says the packet size
11:28:48
행 수를 패킷 수로 나눈 값과 같습니다.
equals to the number of rows divided
11:28:51
여기서 행 수는 얼마입니까? 우리는 네 개의 행이 있습니다.
by the number of packets so what is the number of
11:28:54
여기 네 개가 있으니 패킷 수는 우리가 정의합니다.
rows here we have four rows right so we have
11:28:57
쿼리의 구문에서, 여기서 우리는 두 개의 버킷을 정의했습니다.
four over here then the number of packets we define it
11:29:00
두 그룹이 필요하므로 이는 네 개를
in the syntax of the query so here we defined two buckets
11:29:04
둘로 나눈다는 의미입니다. 따라서 버킷의 크기는 두 개가 됩니다.
we need two groups so that means we are dividing four
11:29:07
이제 이 SQL이 준비되었습니다. 각 행을
by two and the size of the bucket is going to be two so
11:29:10
패킷에 할당하기 시작할 것입니다. 위쪽에서 시작하여 첫 번째는 버킷
now with this sql is ready i'm going to start assigning each row to a
11:29:13
번호 1에 들어가고 다음으로 넘어가면 괜찮다고 말할 것입니다.
packet so it's going to start on the top the first one going to be in the bucket
11:29:17
여전히 패킷에 충분한 공간이 있으니
number one then go to the next one it's going to say okay
11:29:20
또한 하나에 할당할 것입니다. 하지만 이렇게 하면 최대
we still have enough space in the packet right so
11:29:23
각 버킷 내의 행 수에 도달합니다.
it's going to sign it as well to one but with this we reach the maximum
11:29:26
다음 행은 다른 버킷에 할당될 것이므로
number of rows within each bucket so the
11:29:30
두 번째 버킷에 할당될 것입니다. 마지막 행도 두 개가 될 것입니다.
next row gonna be assigned to another bucket so it's gonna be
11:29:33
따라서 이렇게 됩니다.
two and the last one gonna be as well two so as
11:29:36
보시다시피 매우 간단합니다. 우리는 단순히 판매를 기반으로 할당했습니다.
you can see it's very simple we have just assigned our sales based
11:29:39
물론 정렬에 따라 두 개의 버킷으로 나누었습니다. 이 두 판매는
on the sorting of course into two buckets these two sales
11:29:42
버킷 번호 1에 속하고 나머지 두 개는
belongs to the bucket number one and the other two belongs to the
11:29:45
버킷 번호 2에 속합니다. 매우 쉽습니다. 그래서 매우 직관적입니다. 왜냐하면 우리는 짝수로 나누고 완벽한 크기의 버킷을 얻었기 때문입니다. 하지만 만약 우리가 홀수 개가 있다면 어떻게 될까요?
bucket number two very easy so that's why it's very straightforward because we are dividing even numbers and we got perfectly sized buckets But now what can happen if we have an odd number?
11:29:55
여기 5가 있습니다. 4 대신에.
So we have here 5 instead of 4.
11:29:58
그래서 버킷 크기는 5를 나누는 것입니다.
So the bucket side is going to be dividing five by
11:30:01
2로 나누면 2.5가 되고, 이제 물론 SQL은
two we're going to get 2.5 and now of course sql will not
11:30:04
각 버킷에 대해 두 개의 반으로 나누지 않을 것입니다. 그래서 우리는
go and divide like two half for each bucket then we
11:30:07
이것을 두 개의 패킷으로 나누고 있습니다. 물론 이것은 작동하지 않을 것입니다.
are splitting this into two packets of course this will not be working
11:30:10
이제 하나의 버킷에는 3이 있고 다른 하나에는
we should have now a bucket with three and another
11:30:13
2가 있어야 합니다. 그래서 이제 SQL의 규칙은 매우 명확합니다. 더 큰 그룹이 먼저 오고, 그 다음에 더 작은 그룹이 옵니다. 즉, 우리가 여기서 짝수 개를 가진다면
bucket with two so now the rule in sql make it very clear it says larger groups comes first then smaller so that means if we have here an even number like this
11:30:24
더 큰 그룹이 첫 번째 그룹이 될 것입니다. 그래서
the larger group going to be the first group so that's
11:30:27
이것은 이렇게 보일 것입니다. 모든 것을 초기화하는 것처럼 될 것입니다.
going to look like this it's going to like reset everything
11:30:30
자, 이제 첫 번째가 어떻게 될지 봅시다.
so let's see what's going to happen the first
11:30:33
첫 번째는 1이 될 것이고, 두 번째는 1이 될 것입니다.
one going to be one the second one has build one the
11:30:36
세 번째도 1이 될 것이므로, 두 번째보다 더 큰 패키지를 가지고 있습니다.
third one going to be as well one so it kind
11:30:39
나머지는 2가 될 것입니다. 그래서 보시다시피 더 큰
of has a larger package than the second one then
11:30:43
그룹이 먼저 오고, 그 다음에 더 작은 그룹이 옵니다. 이것이 홀수가 있을 때 스케일이 작동하는 방식입니다. 따라서
the rest going to be two so as you can see the larger
11:30:46
여기 완벽한 크기의 버킷이 없습니다. 대략적으로 또는
group comes first then the smaller and this is how a scale going to work if you have odd numbers so you don't have
11:30:52
거의 같은 크기의 버킷이 있습니다. 그래서 이것이 전체
here perfectly sized buckets you have approximately or
11:30:56
작동하는 방식입니다. 이제 이 기능을 연습하기 위해 스케일로 돌아가 보겠습니다.
roughly equally sized buckets so this is how the entire
11:30:59
좋습니다. 이제 이 기능으로 재미있게 놀아보겠습니다.
works now let's go back to scale in order to practice this function
11:31:02
우리는 단순히 주문 ID와 판매를 선택할 것입니다.
okay so now let's have some fun working with this function so
11:31:05
판매 주문에서. 그래서 가서 실행해 보겠습니다. 그렇게 하면 10개의 행을 얻습니다. 이제
we're just gonna select something like order id sales from
11:31:10
데이터에서 단 하나의 버킷만 만들고 싶다고 가정해 보겠습니다.
sales orders so let's go and execute it and with that we get our 10 rows now let's say that
11:31:17
데이터에서 하나의 버킷만 만들고 싶습니다.
would like to create only one bucket from the data so
11:31:21
전체와 단 하나의 패킷을 넘어서
entire and only one packets over
11:31:24
파티션을 만들지 말고
partition let's say not partition by let's
11:31:27
판매를 기준으로 내림차순 정렬합니다.
take order by sales descending so
11:31:30
그게 다입니다. 하나의 버킷이라고 부를 것입니다.
that's it i'm gonna call it one bucket
11:31:34
그러니 평소처럼 실행해 봅시다. 데이터 정렬 후
so let's go and execute it as usual it's gonna go
11:31:37
패킷을 계산할 것입니다. 10이 될 것입니다.
and sort the data and then calculate the packet it's gonna be 10
11:31:40
행을 하나로 나누면 버킷의 크기는 10이 됩니다. 그래서 여기서 모든 행이 하나의 버킷에 들어갈 수 있습니다.
rows divided by one so the size of the bucket gonna be 10 so that's That's why you can see everywhere here as one because all those rows can fit into one bucket.
11:31:50
이것은 매우 간단합니다. 우리는 하나의 버킷만 있습니다. 이제 두 개의 버킷을 만들어 봅시다.
So this is very simple. We have only one bucket. Let's go and now have two buckets. So I'm just going to copy and paste.
11:31:57
하나 대신 두 개를 만들 것입니다. 두 개의 버킷이라고 부릅시다.
And instead of one, we're going to have two. And let's call it two buckets. So let's go and execute this.
11:32:04
이제 다시 버킷의 크기는 무엇인가요? 10을 2로 나누면 됩니다.
So now again, what is the size of the buckets? It is 10 divided by two. So we will get perfectly grouped buckets.
11:32:12
첫 번째 버킷은 5개의 행이 되고 두 번째는 다음 5개의 행이 됩니다.
So the first bucket is going to be five rows and the second one is going to be the next five rows. So it is very perfect.
11:32:18
다음으로 넘어갑시다. 세 개의 버킷을 만들어 봅시다.
Let's go to the next one. Let's have three buckets. So three. So let's go and execute.
11:32:25
이제 무슨 일이 일어날까요? 10을 3으로 나누어 버킷의 크기를 구할 것입니다.
So now what can happen? It's going to go and divide 10 by three in order to get the size of the bucket. And it's going to be 3.3.
11:32:32
소수점이 나올 것이고 완벽한 크기의 버킷을 얻지 못할 것입니다.
So it is decimal and we will not get perfectly sized buckets.
11:32:37
그래서 다시 큰 그룹이 먼저 오고 그 다음 작은 그룹이 옵니다.
So again, the larger group comes first and then the smaller.
11:32:40
보시다시피 첫 번째 그룹에 네 개를 맞춰야 합니다.
so as you can see we have to fit then in the first group four
11:32:43
다른 그룹을 세 개로 맞추기 위해서입니다.
in order to get the others with three so that's
11:32:46
첫 번째 버킷에는 네 개의 행이 들어가고 두 번째에는 세 개의 행이 들어갑니다.
why the first bucket is going to be the biggest one so four rows
11:32:49
첫 번째 버킷에는 네 개의 행이 들어가고 두 번째에는 세 개의 행이 들어갑니다.
into the first bucket then the second three rows
11:32:53
두 번째 버킷에는 들어가고 마지막 하나도 들어갑니다.
going to be in the bucket two and as well the last one going to be
11:32:56
세 번째 버킷이 될 것이고, 큰 그룹이 먼저 옵니다.
bucket three so as you can see the larger group is going
11:32:59
첫 번째 버킷이 될 것이니 이제 데이터를 가지고 놀아봅시다.
to be the first bucket so now let's keep playing with the data let's go and take now four we would like to have four buckets now things
11:33:07
이제 네 개의 버킷을 만들고 싶습니다. 이제 흥미로워질 것입니다.
gonna get interesting so now by checking the results gonna be interesting
11:33:10
10을 4로 나누면 2.5가 될 것입니다.
is going to divide 10 by 4 and we will get something like
11:33:14
2.5 그래서 다시 우리는 완벽한 크기의
2.5 so again we will not get perfectly sized
11:33:17
그룹을 얻지 못할 것이므로 isql은 이제 10개의 행을
groups so isql has to fit now 10 rows
11:33:20
네 개의 그룹으로 나누어야 하며 첫 번째 세 개의
into four groups so the first three
11:33:23
행은 첫 번째 버킷에 맞춰질 것이고
rows gonna be fit in the bucket number one and
11:33:26
두 번째 세 개의 행도 이렇게 두 번째 패킷에
as well the second three rows like this gonna be
11:33:29
맞춰질 것이며 여기서 우리는 크기가 두인 두 개의 버킷이 있고 이를 통해 10개를 맞출 수 있습니다.
in the packet number two and then you can see over here we have two buckets with the size of two and with that we can fit 10 into
11:33:37
네 개의 그룹으로 나누어야 하며 다시 더 큰 그룹이
four groups and again you can see the larger groups
11:33:40
먼저 오고 이렇게 하나가 오고 두 번째가
comes first like this one and then the second and
11:33:43
작은 그룹은 나중에 옵니다. 알겠죠? 이게 인텔의
the smallers comes later okay so this is how the intel
11:33:46
작은 그룹은 나중에 옵니다. 알겠죠? 이게 인텔의
works in sql and now you might say you know what why do
11:33:49
SQL에서 작동하는 방식입니다. 이제 당신은 이렇게 말할 수 있습니다. 왜
i need buckets in the first place so what is the use case there
11:33:56
처음에 버킷이 필요합니까? 그래서 그 사용 사례는 무엇입니까?
is two use cases for the entire function in my projects in
11:34:00
내 프로젝트에서 전체 기능에 대한 두 가지 사용 사례가 있습니다.
one hand if i am data analyst i'm going to use the intel function in order to segment my data in the other hand if i'm data
11:34:06
한편으로 내가 데이터 분석가라면, 나는 내 데이터를 세분화하기 위해 인텔 기능을 사용할 것입니다. 다른 한편으로 내가 데이터
engineer, I'm going to use the entire function in order to do ETL processing and as well to do load balancing.
11:34:13
엔지니어라면, ETL 처리와 로드 밸런싱을 수행하기 위해 전체 기능을 사용할 것입니다.
So now let's start with the first use case as a data analyst where you want to do segmentations with the entire function.
11:34:19
이제 데이터 분석가로서 첫 번째 사용 사례를 시작해 보겠습니다. 전체 기능으로 세분화를 수행하고자 합니다.
Segmentations is very nice way in order to understand your data.
11:34:23
세분화는 데이터를 이해하는 데 매우 좋은 방법입니다.
So you can go and segment your data into different buckets or groups like for example, doing segmentations for the customers.
11:34:30
그래서 당신은 고객을 예를 들어 세분화하여
So you can go and group up your customers depend on their
11:34:33
행동에 따라 고객을 그룹화할 수 있습니다. 총 판매량이나 총 주문 수와 같은
behavior like the total sales or the total number
11:34:36
주문 수에 따라 예를 들어
of orders so with that you can make like for example the
11:34:39
IB 섹션을 만들고 중간 및 낮은
ib section and then the medium and then the low
11:34:43
이제 세분화 사용 사례를 이해하기 위해 다음 작업을 해보겠습니다. 작업은 모든 주문을 세 가지 범주로 나누는 것입니다. 높은, 중간, 낮은 판매로
so now in order to understand the segmentation use case let's have
11:34:46
해결하기 위해 기본적인 작업을 수행합시다.
the following task okay the task says segment all orders into three categories high medium and low sales so in order to solve this let's do the basic stuff right
11:34:57
주문 ID를 선택하십시오. 판매량을 가져옵니다.
So select order ID. Let's take the sales from
11:35:00
우리의 테이블 판매 주문에서 가져오고
our table sales orders and let's
11:35:03
가서 실행합시다. 평소처럼 우리는
go and execute it so as usual we got our
11:35:06
10개의 판매를 했습니다. 이제 작업을 확인하면
10 sales so now if you check the task it says we
11:35:09
세 가지 범주가 필요하다고 합니다. 즉, 세 개의 패킷이 필요합니다.
need three categories so that means we need three packets
11:35:13
맞습니다. 높은, 중간, 낮은 판매로 나누어야 하므로
right and it says high medium and low sales so that means we are dividing by the sales so let's go and do it step by step so
11:35:21
데이터를 세 가지로 나누기 위해 인타일을 사용할 것입니다.
we're going to use intiles since we need to segment the data three
11:35:25
범주란 세 개의 버킷을 의미하며, 이제 정의합시다.
categories means three buckets and then let's define
11:35:28
우리는 데이터를 나눌 필요 없이 정렬만 하면 됩니다.
the window over we don't have to divide the data by
11:35:31
셀로 정렬할 것이므로 셀별로 진행합시다.
partition by we just need to sort it first by
11:35:34
이산적으로 정렬할 것이므로 가장 높은 것부터 낮은 것까지 정렬하겠습니다.
the cells so it's going to be by cells and let's take
11:35:38
그게 전부입니다. 당신이 우리의 버킷이라고 가정해 봅시다.
discrete since we want to sort it from the highest to the lowest
11:35:41
세 개의 패킷으로 나누어질 것입니다. 첫 번째 패킷에는 모든
so that's it let's say you are our buckets so let's go and execute this so now if you check the data you can see that they are segmented into
11:35:51
높은 판매의 주문이 포함될 것입니다. 그 다음은
three packets so the first packet is going to contain all
11:35:54
중간 판매의 모든 주문이 포함될 것입니다.
orders with the high sales then the second one
11:35:57
마지막 패킷에는 낮은 판매의 모든 주문이 포함될 것입니다.
going to be all sales with the medium and then the
11:36:00
보시다시피, 우리는 이미 데이터를 세 가지로 분류했습니다.
last one going to be all sales with the low sales so
11:36:03
보시다시피, 우리는 숫자가 있으며
as you can see we have already categorized our data into three
11:36:06
사용자가 높은, 중간, 낮은 텍스트를 기대할 수 있습니다.
groups but now as you can see we have numbers and
11:36:10
따라서 이제 숫자를 텍스트로 변환할 것입니다.
maybe the user is expecting to have those texts high medium low so that means what we're going to do now we're going to go and translate those numbers into text
11:36:17
두 단어로, 물론 우리는 창 안에서 그렇게 할 수 없습니다.
in two words and of course we cannot do that inside the window
11:36:20
함수를 사용하여 데이터 변환을 진행할 것입니다.
function we're going to use data transformation using the
11:36:23
case when 문을 사용할 것입니다. 걱정하지 마세요.
case when statements don't worry about it we're going to have complete dedicated
11:36:27
case when에 대한 설명 섹션이 있을 것입니다.
section explaining the case when so for now
11:36:30
따라서 지금은 저를 따라오세요.
just follow me in order to see how this works we're
11:36:33
서브쿼리를 사용할 것이므로 선택할 것입니다.
going to go and use subquery so it's going to be select and
11:36:37
모든 것을 위해 별표를 사용하고 다음 논리를 가집시다.
let's take the star for everything and then let's have the following logic
11:36:40
패킷이 하나일 때
case when packets equal to one
11:36:43
그럼 매출이 높고
then it is high the sales is high so
11:36:47
우리는 숫자를 텍스트로 매핑하고 있습니다
we are just mapping the numbers into text so otherwise
11:36:51
버킷이 두 개인 경우 중간을 목표로 하고 마지막 그룹은 패킷이 세 개인 경우입니다
case when the buckets equal to two then we are targeting the medium medium and then the last group packets equal to three
11:37:01
그럼 매출이 낮으니 종료하고 세분화라고 부릅시다
then those sales are low so let's call it ended and let's call it sales segmentations
11:37:09
그럼 이게 다입니다. 조금 더 작게 만들어서 보이게 할게요
so that's it let me just make it a little bit smaller in order for you to see it and all right
11:37:15
그럼 여기서 우리는 서브 쿼리를 갖습니다
so from and then we have our sub query
11:37:18
이렇게 보시면
like this so as you can see we
11:37:21
숫자를 텍스트로 매핑했습니다
just mapped the numbers into text we are just doing
11:37:24
번역을 실행해 보겠습니다
translations so let's go and execute it and
11:37:27
결과를 확인해 보니 세 가지 카테고리가 있습니다
now by checking the results we got our three categories for
11:37:31
사용자에 대한 첫 번째 카테고리는 가장 높은 매출입니다
the users so the first category is going to be the highest sales the
11:37:34
두 번째는 중간 매출, 세 번째는 낮은 매출입니다
second one going to be the medium sales and the third one going to be the low sales so guys you see intel is very powerful in order to segment our data so now you can go and segment stuff like
11:37:45
고객을 총 매출로, 제품을 가격으로, 직원은 급여로 세분화할 수 있습니다
the customers by their total sales or the products by prices employees by their salaries and so on
11:37:55
좋습니다. 이것이 데이터 분석가로서 인텔 함수의 첫 번째 사용 사례입니다
all right so this is the first use case for the intel function as a data analyst
11:37:58
데이터를 세분화하여 이해하는 것입니다
where you go and segment your data in order to understand the
11:38:01
데이터 엔지니어라면
behavior now in the other hand if you are data engineer
11:38:04
ETL에서 로드 밸런싱을 하기 위해 인텔 함수를 사용할 수 있습니다
you can use entire function in order to do load balancing in your etl so now i'm just going to explain it in very simple sketch all right so now we have the following scenario where
11:38:13
우리는 두 개의 데이터베이스가 있고 큰 테이블을 A에서 B로 이동하려고 합니다
we have two databases and we would like to move one big table from the database A to database B.
11:38:20
이 경우 전체 로드를 수행하고 있습니다
So in this case, I'm doing something called full load. That means I'm loading all the rows from one database to another.
11:38:26
한 번에 수행하면 오랜 시간이 걸릴 수 있습니다
So if you do it in one go, what could happen if that's, it could take a long time. So it could take hours or even sometimes days.
11:38:34
네트워크 오류가 발생할 수 있습니다
And maybe at the end, you will get maybe some network errors because you have stressed the networks between those two databases and everything
11:38:41
데이터를 잃고 다시 시작해야 합니다
gonna break and you're gonna lose the data and you have to start again
11:38:44
한 번에 테이블을 로드하는 대신
so now instead of loading this table in one go what we can
11:38:47
부분으로 나눌 수 있습니다
do we can go and split it into fractions or let's say packets
11:38:50
예를 들어 이 표를 네 개로 나눌 수 있습니다.
so we can split this table for example into four
11:38:53
작은 테이블로 나누는 함수 사용
small tables using the function entile
11:38:56
이 큰 테이블을 작은 테이블로 나눈 후
so now after we split this big table into small tables we
11:39:00
작은 테이블을 하나씩 이동할 수 있습니다.
can go and start moving those small tables one after another
11:39:03
네트워크에 부담을 주지 않게 됩니다.
and with that we are not stressing the networks and
11:39:06
모든 것을 로드한 후
it's gonna succeed so now after loading everything at the end in the
11:39:09
목표 데이터베이스에 작은 테이블이 생깁니다.
target database we're gonna have those small tables and of course we
11:39:13
그들을 합치기 위해 유니온을 사용할 수 있습니다.
can go and use the union in order to merge them in
11:39:16
원래 데이터베이스에서 큰 테이블을 다시 만들기 위해
order to have again the big table that we have it in
11:39:19
데이터를 추출하는 작업의 부하를 나누고 균형을 맞추기 위해
the original database so this is very common use case for the
11:39:22
데이터를 내보내기 위해 주문을 두 그룹으로 나누라고 합니다.
end tile in order to split the load and to balance the processing of extracting data all right so now we have the following sql task it says in order to export the data divide the orders into two groups
11:39:34
그럼 시작해봅시다. 먼저 테이블에서 모든 것을 선택하여
So let's go and do that. First, we can select everything from the table just in order to see the data sales orders.
11:39:42
주문 데이터를 확인할 수 있습니다.
So let's go and execute it. So now we got our 10 orders. And what we have to do is to go and split it into two groups.
11:39:49
그럼 실행해봅시다. 이제 10개의 주문을 받았습니다.
In order to do that, we can use the entire function. Two groups means two buckets.
11:39:55
두 그룹으로 나누어야 합니다.
So let's define the window. So here we don't have to partition the data using partition by.
11:40:00
그렇게 하려면 전체 함수를 사용할 수 있습니다.
we have to specify the order by so now which column
11:40:03
두 그룹은 두 개의 버킷을 의미합니다.
we're gonna use in order to sort the data of course here there is
11:40:06
여기서 데이터를 파티션으로 나누지 않아도 됩니다.
no rule like you can go and split the data by sales or
11:40:09
정렬할 열을 지정해야 합니다.
by the order status by date by anything you want but
11:40:12
어떤 열을 사용할지 결정해야 합니다.
we usually go and use the primary key it's just systematic
11:40:16
데이터를 정렬하기 위해
better and more clean especially if you have a sequence of
11:40:19
판매 또는 주문 상태에 따라 나눌 수 있습니다.
numbers in the order id so you can export the first range of the orders then you can go to the next group and so on so let's go with the order id
11:40:28
주문 ID의 기본 키를 사용하는 것이 일반적입니다.
and let's give it a name packets so that's
11:40:31
더 깔끔하고 체계적입니다.
it let's go and hit execute now as you can see it's very simple
11:40:34
주문 ID의 첫 번째 범위를 내보낼 수 있습니다.
we got our two groups so this is the first patch of
11:40:38
데이터의 첫 번째 배치이고 두 번째 배치입니다
of the data and this is the second batch
11:40:41
데이터이므로 이제 첫 번째 배치를 선택하고 내보낼 수 있습니다
of data so now we can go and select the first patch and export
11:40:44
그것을 다음 시스템에 가져오고 그 후에 두 번째 배치로 진행합니다
it import it in the next system and then after that we go with
11:40:47
그 패킷의 크기로 여전히 고통받고 있다면 더 작은 크기로 나눌 수 있습니다
the second batch and of course if you still suffer from the size of
11:40:50
그 패킷을 더 작은 크기로 나눌 수 있습니다
those packets you can go and split it to more smaller size
11:40:53
여기에서 더 작은 버킷을 만들 수 있습니다
so you can go over here and make it for so
11:40:57
이로 인해 더 작은 버킷을 얻을 수 있고
with that we're gonna get smaller buckets and it might be easier to
11:41:00
데이터를 내보내는 것이 더 쉬울 수 있습니다
export the data so this is really great use case for the entire
11:41:03
모든 기능에 대한 두 가지 사용 사례를 배웠습니다
function all right everyone so with this you have learned the two use
11:41:06
프로젝트에서 일반적으로 따르는 전체 기능에 대한 두 가지 사용 사례입니다
cases for the entire function that i usually follow in my projects
11:41:09
데이터 분석가로서 세분화를 수행하는 데 사용할 수 있습니다
so as a data analyst you can use it in order to do segmentations
11:41:13
데이터 엔지니어로서 로드를 수행하는 데 사용할 수 있습니다
and as a data engineer you can use it in order to do load
11:41:16
ETL의 균형을 맞추는 것입니다
balancing of the etl okay
11:41:21
모든 것을 다루었습니다
everyone so with that we have covered everything about the integer based
11:41:24
우리는 백분율 기반 랭킹 함수가 있습니다
ranking functions now we're going to talk about the second methods
11:41:28
여기에는 큐브 거리와 백분위수 두 가지 함수가 있습니다
we have the percentage based ranking functions and
11:41:31
백분율 기반 랭킹에 대한 간단한 요약을 해보겠습니다
here we have two functions the cube dist and as well the percentile
11:41:35
상대적 위치를 계산할 것입니다
so now let's have a quick recap so with the percentage based
11:41:38
각 행에 대해 백분율로 할당하고
ranking is we're gonna go and calculate a relative position
11:41:41
연속적으로 정규화된 스케일을 생성하는 것입니다
as a percentage and assign it for each row so the output gonna be a continuous normalized scale from zero to one and this is really amazing in order to do
11:41:52
분포 분석을 수행할 수 있습니다
distribution analyzes so those functions can consider
11:41:55
전체 데이터 세트의 크기를 고려할 수 있습니다
in their calculation the overall total the whole
11:41:59
각 값의 기여도를 찾는 데 도움이 됩니다
size of the data sets which can help us in order to find
11:42:02
전체 합계에 대한 기여도를 찾는 것입니다
out the contribution of each value to the overall
11:42:05
백분율을 생성하기 위해 두 가지 다른 공식을 사용합니다
total and now in sql in order to generate the percentage
11:42:09
우리는 두 가지 다른 공식을 가지고 있습니다.
we have two different formulas so in one hand
11:42:12
우리는 qm dist 함수를 가지고 있고 다른 한편으로는
we have the function qm dist and in the other hand we have
11:42:15
퍼센트 순위를 가지고 있습니다. 즉, 서로 다른 공식을 가진 두 가지 다른 함수가 있습니다.
the percent rank so that means we have two different functions with different formulas in order to generate and calculate the percentage so now let's start with the first function the QMDIST
11:42:29
좋습니다, 이제 첫 번째 함수인 QMDIST를 시작하겠습니다.
all right everyone so now let's start with the first function we have the QMDIST and
11:42:33
누적 분포를 의미합니다.
it stands for cumulative distribution it's
11:42:36
데이터 포인트의 분포를 계산하는 데 집중할 것입니다.
gonna go and focus or calculate the distribution of your data points
11:42:39
창 내에서, 이는 이해하기 위해 매우 간단한 예를 가질 것입니다.
within a window so what this means in order to
11:42:42
SQL이 이 함수와 어떻게 작동하는지 알아보겠습니다.
understand it we're gonna go and have very simple example to understand
11:42:46
매출의 매우 간단한 예를 가지고 있습니다.
how SQL works with this function so let's go all right again
11:42:49
다음 쿼리가 있습니다. qm dist, 그러면
we have our very simple example of the sales and we
11:42:52
그 안에 인수를 주지 않으므로 비어 있게 됩니다.
have the following query so qm dist then we
11:42:55
창은 일반적으로 매출 내림차순으로 정렬됩니다.
don't give any argument inside it so it's going to be empty and the
11:42:58
가장 높은 것부터 가장 낮은 것까지입니다.
window going to be like usual order by sales descending
11:43:01
첫 번째 단계는 데이터를 정렬하는 것입니다.
from the highest to the lowest and the order by is must so
11:43:04
큐브 분포는 값의 위치 번호를 행의 수로 나눈 것과 같습니다.
the first step is going to go and sort the data we have it already sorted from the highest to the lowest so now the next step is that is going to go and start calculating the percentage for each row and we And we have a very simple formula.
11:43:16
이제 다음 단계는 각 행의 비율을 계산하는 것입니다.
It says the cube dist equals to the position number of the value divided by the number of rows.
11:43:23
큐브 분포는 값의 위치 번호를 행의 수로 나눈 것과 같습니다.
So now the next step is going to go and start calculate the percentage for each row. And we have this very simple formula.
11:43:29
매우 간단합니다. 단계별로 진행해 보겠습니다.
It says the cube dist equals to the position number of the value divided by the number of rows.
11:43:36
우리 목록의 첫 번째 값의 위치 번호는 무엇인가요?
It's very simple. Let's do it step by step. So it's going to start with the first value in our list. So it's going to be calculated like this.
11:43:43
총 행의 수는 얼마인가요? 우리는 다섯 개의 행이 있습니다.
So what is the position number of the first value? It's going to be one, right? So this is the first value in our list.
11:43:50
하나를 다섯로 나누면 결과는 0.2가 됩니다.
And what is the total number of rows? We have five rows, right? So one, two, three, four, five.
11:43:55
이것이 첫 번째 행의 첫 번째 값이 될 것입니다.
So we can divide one by five and the result is going to be 0.2.
11:44:00
여기서 80이 두 번 나타납니다. 따라서 동점입니다.
So this is going to be the first value for the first row. Okay, so now I'm going to go to the next row. And this time we're going to get a special case.
11:44:07
우리는 위치 번호 두에 있습니다. 하지만 80이 여러 번 나타납니다.
As you can see, we have the 80 twice. So we have here a tie. So now first we need the position number.
11:44:14
마지막으로 80 값을 볼 수 있는 위치를 가져가게 됩니다.
As you can see, we are at the position number two, right? But since we have the 80 multiple times,
11:44:19
우리는 두 번째 위치에 있습니다, 맞죠? 하지만 80이 여러 번 나타나기 때문에,
is going to go and take the last position that we see the value 80 and the last position can be the record number three.
11:44:27
그래서 이 기록에 대해서는 세 번째 위치라고 말할 것입니다, 두 번째가 아닙니다.
So that's why it's going to say for this record, it's going to be the position number three and not two.
11:44:33
그리고 나서 그것을 다섯으로 나눌 것이고, 우리는 0.6의 값을 얻을 것입니다.
And then it's going to go and divide it by five and we will get the value of 0.6.
11:44:38
그래서 이 함수와 관련하여 가장 혼란스러운 점입니다.
So this is the most confusing thing with this function.
11:44:41
SQL이 동점을 찾으면 현재 위치 번호를 완전히 무시합니다. 그래서 우리는 두 개가 없습니다.
So if SQL finds a tie, it will completely ignore the current position number. So we don't have two.
11:44:47
같은 값에 대해 마지막 위치 번호를 가져올 것입니다.
It's going to go and take the last position number for the same value.
11:44:51
우리 목록의 마지막은 세 번째 기록이 될 것입니다. 그래서 여기서 세 개가 있는 이유입니다. 자, 이제 계속 진행합시다.
And the last in our list is going to be the record number three. So that's why we have three over here. OK, so now let's keep moving.
11:44:58
세 번째 행으로 가봅시다. 그리고 다시 보시다시피
Let's go to the third row. and as you can see we are again
11:45:01
동점이지만 이번이 마지막입니다.
in the tie but this time this is the last time we
11:45:04
80을 보므로 다음에는 80이 없으니,
see 80 so next we don't have 80 so what's
11:45:07
무슨 일이 일어날까요? 우리는 정확히 같은 결과를 얻을 것이므로 세 개를 나눌 것입니다.
gonna happen we're gonna have exact same results so it's gonna be three divided
11:45:11
다섯으로 나누면, 보시다시피,
by five so as you can see if we
11:45:14
동점이 있으면 그들은 같은 비율을 공유할 것입니다. 즉, 큐브 거리에서 같은 값이 있으면 같은 순위를 공유할 것입니다. 자, 이제 네 번째로 넘어갑시다.
have a tie they're gonna share the same percentage so that means with the cube dist if you have same values they're gonna share the same rank so let's Let's keep moving to the fourth one.
11:45:25
그렇다면 50의 위치 번호는 무엇인가요? 우리는 네 번째 기록에 있습니다. 그래서 네 번째 위치를 다섯으로 나누면.
So now what is the position number of the 50? We are at the record for. So position number four divided by five.
11:45:31
0.8을 얻을 것입니다. 자, 이제 마지막으로 넘어갑시다. 그리고 이것이 가장 쉬운 것입니다.
We will get 0,8. Okay, so now let's move to the last one. And it is the easiest one.
11:45:37
그렇다면 여기서 어떤 위치가 있나요? 다섯 번째 위치입니다. 마지막입니다. 그리고 행의 수는 다섯입니다.
So which position do we have over here? It is the position number five. It's the last one. And the number of rows is five.
11:45:44
그래서 우리는 하나를 얻을 것입니다. 자, 여러분, 이것이 누적 분포가 작동하는 방식입니다.
That's why we will get one. So guys, that's it. This is how the cumulative distribution works.
11:45:49
공식을 이해하면 매우 쉽게 될 것입니다.
Once you understand the formula, it's going to be very easy in order
11:45:52
출력을 이해하는 것이므로, 보시다시피 비율을 계산하는 것은
to understand the output so as you can see calculating the percentage
11:45:55
항상 데이터 세트의 총 크기에 따라 다릅니다.
always depends on the total size of our data sets
11:45:58
여기서 행의 수를 볼 수 있으므로, 우리는
you can see here the number of rows so with us we're going to get an
11:46:02
데이터 세트 내에서 데이터 포인트의 분포를 이해하는 데 도움이 되는 출력을 얻을 것입니다.
output that help us in order to understand the distribution of
11:46:05
모두 잘 들으세요. 이제 두 번째 함수에 집중할 것입니다.
our data points within the data sets all
11:46:11
순위로서의 비율을 생성하는 함수입니다. 우리는 백분위 순위를 가지고 있습니다.
right everyone so now we're going to go and focus on the second function that generates
11:46:15
백분위 순위는 생성하는 데 집중할 것입니다.
percentage as a rank we have the percent rank
11:46:18
그래서 사람의 순위는 생성하는 데 집중할 것입니다.
so the person rank gonna go and focus on generating the
11:46:21
각 행의 상대적 위치를 이해하기 위해
relative position of each row within a
11:46:24
이것이 의미하는 바를 이해하기 위해 간단한 예를 들어보겠습니다.
window so in order to understand what this means we can have a
11:46:27
스케일이 작동하는 방식을 이해하기 위한 아주 간단한 예입니다.
very simple example in order to understand how scale works
11:46:30
이 함수로 다시 가보겠습니다. 우리는 판매 데이터를 가지고 있습니다.
with this function so let's go okay again we have those sales
11:46:34
아주 간단한 예이며 구문은 이렇게 될 수 있습니다.
very simple example and the syntax can be like this percent
11:46:37
순위와 내부에는 어떤 인수도 사용하지 않습니다.
rank and inside it we don't use any arguments and
11:46:41
창은 이렇게 될 것이며, 판매를 기준으로 정렬됩니다.
the window gonna be like this order by it is a must sales
11:46:44
가장 높은 것에서 가장 낮은 것으로, 첫 번째 단계입니다.
descending from the highest to the lowest the first step
11:46:47
이것이 데이터를 정렬하는 방법입니다.
that is going to do it that's going to go and sort the data from the highest
11:46:50
가장 높은 것에서 가장 낮은 것으로, 다음 단계는
to the lowest and we have it already like this and next is going to go
11:46:53
백분율을 계산하기 시작하는 것입니다.
and start calculating the percentage which is very similar to
11:46:57
누적 분포와 매우 유사하지만 이번에는
the cumulative distribution but this time it's going to be like
11:47:00
이 위치 번호에서 1을 빼고
this position number then we subtract
11:47:03
1에서 빼고 행 수로 나누게 됩니다.
it from one and as well divided by the
11:47:06
정확한 공식처럼 보이지만 여기서는 한 번만 빼고 있습니다.
number of rows subtracted from one so it's
11:47:09
두 숫자 모두에 대해, 이제 모든 행을 단계별로 살펴보겠습니다.
like exact formula but we are only subtracting here once
11:47:12
단계별로 출력을 확인할 것입니다.
for both numbers okay so now let's go through all rows step
11:47:16
첫 번째 행부터 시작할 것입니다.
by step and see the output so it's going to start with the first
11:47:19
첫 번째 행의 위치 번호는 1입니다.
row right so what is the position number of the first row
11:47:22
1에서 빼야 하므로
it's gonna be one then we have to subtract it by
11:47:25
0이 됩니다. 이제 총 행 수는
one that's why we will get zero now what is
11:47:28
여기서 5개 행이 있으며, 1을 빼면
the total number of rows we have here five rows and it
11:47:31
4가 됩니다. 이제 0을 어떤 값으로 나누면
is subtracted by one that's why we're gonna get four so
11:47:34
출력은 0이 됩니다. 그래서 첫 번째 값은 0이 됩니다.
now zero divided by any value the output gonna be a zero so that's why for the first value we will get a zero all right so now let's move to the second
11:47:42
여기 그리고 여기에서 우리는 동점이라는 특별한 경우를 가지고 있습니다. 두 개의 셀이 동일한 값 80을 공유하고 있습니다.
draw over here and here we have our special case where we have a tie so we have two cells sharing the same value 80.
11:47:49
이제 백분위 순위는 다른 행동을 보일 것입니다.
so now for the percent rank is going to have different behavior than
11:47:52
qmd를 기억하세요. qmd에서 isql은 공유된 값의 마지막 위치를 찾았습니다. 그래서 그것은 세 번째 위치였습니다. 왜냐하면 80을 마지막으로 보았기 때문입니다.
the qmd remember in the qmd isql did search for the last position of the shared value so it was the position number three since this is the last time we see 80.
11:48:03
하지만 이제 백분위 순위는 첫 번째 발생에 고정될 것입니다.
but now with the percent rank is going to stick with the first occurrence
11:48:06
공유된 값의 첫 번째 발생을 확인하면, 두 개의 80을 확인하여
of the shared value so now by checking those two 80s what
11:48:10
첫 번째 발생은 두 번째 레코드입니다. 그래서
is the first occurrence it is the record number two so
11:48:13
우리는 두 번째 위치에서 1을 빼게 됩니다.
that's why we have position number two subtracted by one we
11:48:16
우리는 1을 얻고 여기서도 총 수와 동일하게 됩니다.
will get one and here the same gonna be number of totals we
11:48:20
우리는 5에서 1을 빼면 4가 됩니다. 그래서 이제 1을 4로 나누면
have five subtract by one we have four so now if you divide one
11:48:23
네 개로 나누면 0.2의 결과를 얻을 수 있습니다.
by four we will get the result of zero comma two
11:48:26
다섯, 그래서 이것이 이 값의 백분율입니다. 이제 두 번째 행으로 가보겠습니다. 여기서 다시 동점이 있으므로 위치 번호 2에 고정됩니다. 첫 번째 발생이므로 동일할 것입니다.
five so this is the percentage of this value so now let's go to the second row here we have again the tie so it's going to stick with the position number two the first occurrence so it's going to be the same
11:48:38
두에서 하나를 빼면 하나가 되고, 또한
two subtracted by one we will get one and as well the
11:48:41
총 행 수는 다섯에서 하나를 빼면 네 개가 됩니다.
total number of rows five subtract by one we will have four that's
11:48:44
그래서 우리는 동일한 정확한 결과를 얻을 것입니다. 여기에서 볼 수 있듯이 백분율 순위는 누적 분포와 같으며 공유된 값도 동일한 백분율 순위를 공유할 것입니다. 이제 네 번째로 이동하겠습니다. 값이 50입니다.
why we will get the same exact results so here as you can see with the percent rank it's like the cum dist the shared value gonna share as well the same percentage rank now let's move to the fourth one so we have the value 50.
11:48:57
그 위치는 무엇인가요? 기록 번호 4에서 하나를 빼면 3이 되고, 3을 4로 나누면
so what is the position of this it's gonna be the record number four subtract it by one we will get three and if you divide three by four
11:49:04
0.75가 나옵니다. 이제 이동합니다.
you will get 0.75 and now moving
11:49:08
여기 마지막 값으로 가면 쉬울 것입니다. 그래서
to the last value over here it's going to be easy so what
11:49:11
30의 위치 번호는 5입니다. 5에서 하나를 빼면
is the position number of the 30 it is five five subtracted
11:49:14
4가 되고, 또한 우리는 네 개를 가질 것입니다.
by one it's going to be four and as well we're going to have four
11:49:17
여기서도 총 숫자에서 하나를 빼면
as well here for the total numbers subtracted by one
11:49:21
그래서 4를 4로 나누면 1이 됩니다. 그래서 그게
so if you divide four by four you will get one so that's
11:49:24
여러분, 이것이 백분율 순위가 작동하는 방식입니다. 항상 0에서 1까지의 척도를 가지고 있습니다. 그래서 항상 이렇게 됩니다. 내부에 어떤 값이 있든 상관 없습니다.
it guys this is how the percent rank works it always has the scale from zero to one so it's always like this it doesn't matter which values do we have inside
11:49:32
그리고 연속적인 척도를 가질 것입니다. 그리고 다시 여기서
and it's gonna have like continuous scale and again here
11:49:35
동점이 있는 경우, 그들은 동일한 백분율 순위를 공유합니다.
if you have a tie they're gonna go and share the same percentage rank
11:49:39
좋아요, 여러분. 이제 이 두 함수를 비교해보면 알 수 있습니다.
okay guys so now if you go and compare those two functions you can see that they
11:49:42
서로 매우 유사합니다. 두 함수의 출력은
are really similar to each other's the output of both functions we
11:49:45
백분율 기반 순위를 생성하고 있습니다.
are generating percentage based ranking and
11:49:48
두 함수 모두 동점을 완벽하게 처리하고 있습니다.
both of them as well handling the ties perfectly so
11:49:51
그래서 두 함수는 같은 백분율 순위를 공유합니다. 구문을 확인하면 매우 유사합니다.
they share the same percentage rank if you check the syntax they are very similar and now by checking the formulas of both of them we are always considering the overall size of the data sets.
11:50:01
여기서 데이터 세트의 전체 크기를 항상 고려하고 있습니다.
So here the size is considered in the calculation to help us finding the relative position of each value to the overall.
11:50:09
계산에서 크기가 고려되어 각 값의 상대적인 위치를 찾는 데 도움을 줍니다.
And this is very important in the analysis in order to measure the contribution of each value to the overall.
11:50:15
이것은 분석에서 매우 중요합니다. 각 값이 전체에 기여하는 정도를 측정하기 위해서입니다.
So now about the use cases. If you want to focus on the distribution of your data points, go with the cumulative distribution.
11:50:21
이제 사용 사례에 대해 이야기해 보겠습니다. 데이터 포인트의 분포에 집중하고 싶다면 누적 분포를 사용하세요.
but if you want to focus on the relative position of each
11:50:24
하지만 각 행의 상대적인 위치에 집중하고 싶다면
rows then go with the percent rank all right so
11:50:27
백분율 순위를 사용하세요. 알겠죠?
now there is one more difference between the QMDIST and the percent rank and
11:50:31
이제 QMDIST와 백분율 순위 간의 또 다른 차이점이 있습니다.
that's if you check the formulas you can see that the
11:50:34
공식을 확인하면 QMDIST가 더 포괄적이라는 것을 알 수 있습니다.
QMDIST is more inclusive we always consider
11:50:37
현재 행의 위치 번호를 항상 고려하지만
the position number of the current row but with the
11:50:40
백분율 순위는 현재 행을 고려하지 않습니다. 우리는 그것을 건너뛰거나 배제합니다.
percent rank we don't consider the current row we like skip
11:50:44
그래서 우리는 백분율 순위가 더 배타적이라고 말합니다. 누적 분포는 더 포괄적입니다.
it or make it exclusive so we say for the person rank it is more exclusive and the cumulative
11:50:50
이제 만약 당신이 어떤 것을 사용할지에 대한 어려운 질문을 한다면
distribution it is more inclusive so now if you ask
11:50:53
더 포괄적이길 원한다면 누적 분포를 사용하세요.
me the hard question which one to use i'm gonna say if
11:50:56
현재 행과 함께 더 배타적이길 원한다면 백분율 순위를 사용하세요.
you want to be more inclusive go with the cumulative distribution if
11:51:00
서로 매우 유사합니다. 그래서 만약
you want to be more exclusive with the current row go with the person
11:51:03
데이터의 분포를 계산하고 싶다면 누적 분포를 사용하세요.
rank so they are very similar to each other's so if
11:51:06
각 행의 상대적인 위치를 찾고 싶다면
you want to calculate the distribution of your data go with the cumulative distribution if
11:51:10
백분율 순위를 사용하세요. 알겠죠?
you want to find the relative position of each row
11:51:13
이제 우리는 다음과 같은 작업을 가지고 있습니다.
then go with the person rank all right so now we have the following
11:51:16
가격의 상위 40%에 해당하는 제품을 찾으라고 합니다.
task it says find the products that fall within the
11:51:19
이제 해결해 보겠습니다. 우리는 테이블 제품을 목표로 하고 있습니다.
highest 40 of the prices let's go and
11:51:22
지금 해결합시다. 우리는 테이블 제품을 목표로 하고 있습니다.
solve this now we are targeting the table products and
11:51:25
나는 두 개의 열 제품 가격을 선택할 것입니다.
i will just select like two columns products price
11:51:29
판매 제품에서.
from sales products so
11:51:32
그게 다입니다. 이제 실행합시다.
that's it let's go and execute this so
11:51:35
이제 보시다시피 우리는 다섯 개의 제품과 그 가격을 얻었습니다.
now as you can see we got five products and their prices and the
11:51:38
작업은 가장 높은 40%를 찾으라고 합니다.
task says find the highest 40 percent so
11:51:41
우리는 이를 위해 백분위 순위를 생성해야 합니다.
we have to find and generate a percentage rank in order to do that we have the two functions cube dist and the percent rank i will go this time with the cube dist so let's go and do that
11:51:53
그래서 큐브 거리로 가고 정의합시다.
so cube dist and then let's go and define the
11:51:56
이렇게 윈도우를 설정할 것입니다. 우리는 정렬할 것입니다.
window like this it's gonna be order by we
11:51:59
이제 가격을 목표로 하고 있습니다. 따라서 가격을 정렬합니다.
are targeting now the prices right so order by the
11:52:02
가장 높은 가격에서 가장 낮은 가격으로 정렬합니다.
price from the highest to the lowest and let's go
11:52:06
이 순위에 이름을 붙입시다. 이제 실행합시다.
give it a name this rank so let's go and execute
11:52:09
이제 그것으로 우리는 백분위 순위를 생성할 것입니다.
this so now with that is going to go and generate for us a
11:52:12
이제 출력에서 모든 제품을 얻고 있지만 작업은
percentage ranking using the formula that we just learned
11:52:15
가장 높은 제품만 가져와야 한다고 합니다.
before so now in the output we are getting all the products but the task
11:52:18
40%입니다. 즉, 첫 번째 행입니다.
says we have to get only the products that are in the highest
11:52:21
두 번째 행이므로 그 행들은 가장 높은 40%에 있습니다.
40 so that means the first row the
11:52:25
그렇다면 데이터를 필터링하기 위해 서브 쿼리를 사용할 것입니다.
second row and that's it so those rows are in the highest 40 the rest are below that so in order to do that so filter the data we're going to use the sub query
11:52:35
그래서 스타를 선택하고 이렇게 서브 쿼리가 있습니다.
So select star from and then we have our sub query like this.
11:52:40
그런 다음 필터는 이 순위가 0.4보다 작거나 같아야 합니다.
And then our filter going to be this rank smaller or equal to zero point four.
11:52:47
이것이 데이터를 얻기 위한 기준입니다. 이제 실행합시다.
So this is our threshold in order to get the data. So let's go and execute this.
11:52:53
이제 보시다시피, 우리는 상위 40%의 제품을 얻었습니다.
And now, as you can see, we got the top of products, the top 40%. Now, of course, you can go and format the percentage.
11:52:59
이렇게 할 수 있습니다. 그러니
We can do that like this. so let's
11:53:02
리스트 순위를 100과 곱합시다.
take the list rank multiply
11:53:06
그렇게 실행합시다. 보시다시피 우리는 20%와 40%를 얻었습니다.
it with 100 so let's go and execute this so as
11:53:09
우리는 20과 40퍼센트를 얻었고, 계속 진행할 수 있습니다.
you can see we got 20 and 40 percent we can go
11:53:12
그리고 비율 기호도 추가할 수 있습니다.
and add to it as well the percentage character right so
11:53:15
우리는 연결한다고 말할 수 있고,
we can go and say concat and we're
11:53:19
그 다음에 문자를 추가할 것입니다.
gonna add the character after that like this and
11:53:22
이것을 순위 비율이라고 부르겠습니다.
let's call it this rank percentage so that's it let's go and execute it so that you have solved the task we have the
11:53:30
지금 40퍼센트에 해당하는 제품들입니다.
products that fall within the highest 40 percent now of
11:53:33
물론 비율 순위를 시도할 수 있습니다.
course you can go and try the percent rank so it's
11:53:36
매우 간단합니다. 누적 분포를 전환해야 합니다.
very simple we just have to go and switch the cumulative
11:53:39
퍼센트 뱅크 기능으로 분포를 전환합니다.
distribution with the function percent bank
11:53:43
지금 실행해 보겠습니다. 동일한 결과를 얻을 수 있습니다.
so let's go and execute it now as you can see we will get the exact same results so we're still getting the gloves and caps as the highest products within the 40 percent of the price So guys, that's it.
11:53:54
매우 간단하죠? 좋아요, 친구들.
It's very simple, right? All right, friends.
11:54:00
이제 윈도우 순위 함수에 대한 간단한 요약을 해보겠습니다.
So now let's have a quick recap for the window ranking functions. So what they're going to do, they're going to go and assign a rank for each row within a window.
11:54:07
우리는 두 가지 유형의 순위가 있습니다.
And we have two types of ranking, right? The first one is the integer based ranking.
11:54:12
첫 번째는 정수 기반 순위입니다.
It's going to go and assign a number, an integer for each row. And here we have four functions, row number, rank, dense rank, and intile.
11:54:19
각 행에 대해 숫자를 할당할 것입니다.
And the second type of ranking, we have the percentage based ranking.
11:54:23
SQL은 먼저 순위를 계산한 후 각 행에 할당합니다.
So SQL first is going to go and calculate a rank and then assign it for each row. And here we have two types of formula or functions.
11:54:31
누적 분포와 비율 순위가 있습니다.
So we have the cumulative distribution and the second one we have the percent rank.
11:54:36
구문 규칙에 대해 이야기하겠습니다.
And now to the next point if we are talking about the rules of the syntax. So the expression should be empty. We should not pass any argument to the functions.
11:54:44
데이터를 정렬하기 위해 order by를 사용해야 합니다.
We must use order by in order to sort our data. So it is required and the frame clause are not allowed to use.
11:54:50
윈도우 함수 내에서 프레임을 사용자 정의할 수 없습니다.
so you cannot go and customize a frame within the window function. And as we learned, there are many use cases for the ranking functions.
11:54:57
예를 들어, 상위 분석기와 하위 분석기가 있습니다.
For example, we have the top-in analyzers, the button-in analyzers,
11:55:01
우리 비즈니스에서 두 성과자 또는 최악의 성과자를 식별하기 위해서입니다.
in order to identify our two performers or the worst performers in our business.
11:55:07
행 번호를 사용하여 중복을 식별하고 제거할 수 있습니다.
Another use case, using the row number, we can identify and remove duplicates in our data.
11:55:12
데이터 품질 문제를 찾고 품질을 개선하는 데 사용할 수 있습니다.
So we can use it in order to find data quality issues and as well to improve the quality.
11:55:17
기본 키가 깨끗하지 않은 경우 고유 ID를 생성할 수 있습니다.
And another use case, if our table don't have a clean primary key, we can go and generate a unique IDs using the row number in order to do as well.
11:55:25
페이지 매김의 또 다른 사용 사례입니다. 데이터 세분화였습니다.
Paginating one more use case. It was the data segmentations.
11:55:28
고객, 제품, 직원 등을 세분화하기 위해 Intel을 사용할 수 있습니다.
You can use the Intel in order to segment your customers, your products, employees, and so on.
11:55:33
또 다른 사용 사례로, 데이터 분포 분석을 할 수 있습니다.
And another use case, we can do data distribution analysis.
11:55:36
우리가 배운 것처럼, Q-DIS를 사용하여 데이터 포인트의 데이터 분포를 전체와 비교하여 이해할 수 있습니다.
As we learned, we can use the Q-DIS in order to understand the data distributions of our data points compared to the overall.
11:55:43
마지막 사용 사례는 데이터 엔지니어링에 더 가깝습니다. Intel 기능을 사용하여
And the last use case, it's more for data engineering. We can use the Intel function in order to equalize
11:55:49
우리 ETL의 로딩 프로세스를 평준화할 수 있습니다. 보시다시피, 순위 함수에 대한 많은 사용 사례가 있습니다.
the loading process of our ETLs. So as you can see, there are many use cases for the ranking functions.
11:55:54
윈도우 함수를 사용하여 데이터를 순위 매기는 방법에 대한 모든 것입니다. 이제 마지막 그룹을 다룰 것입니다.
Okay, so that's all about how to rank your data using the window functions. And now we're going to cover the last group.
11:56:00
값 윈도우 함수와 다른 레코드에 접근하는 방법에 대해 배울 것입니다. 자, 시작해 봅시다.
We will learn about the value window functions, how to access another records. So let's go.
11:56:05
좋아요, 여러분. 이제 매우 간단한 예제가 있습니다.
All right, everyone. So now we have this very simple example.
11:56:11
우리는 월과 판매량이 있습니다. 이제 값 함수를 사용하여 다른 행의 값을 접근할 수 있습니다.
We have the months and the sales. Now we can use the value functions in order to access a value from another row.
11:56:19
이해하기 위해 SQL이 현재 3월을 처리하고 있다고 가정해 보겠습니다.
So in order to understand it, let's say that SQL now processing the months and we are currently at the month of March.
11:56:25
예를 들어, 2월의 이전 달의 값을 접근하고 싶습니다.
So now, for example, I would like to access the value from the previous month from February.
11:56:30
그렇게 하기 위해, lag 함수를 사용하여 10의 값을 가져올 수 있습니다.
So in order to do that, we can use the lag function in order to get the value of 10.
11:56:35
그렇게 하면 같은 행에 3월의 현재 판매량과 함께
So with that, we have in the same row, the current sales of the month, March, and as well,
11:56:41
2월의 이전 달 판매량이 있습니다.
the sales from the previous month the February and
11:56:44
다른 경우에는 4월의 다음 달 판매량을 가져오고 싶습니다.
maybe in other cases I would like to get the sales of the
11:56:47
그렇게 하기 위해, lead 함수를 사용할 수 있으며 우리는
next month from April in order to do that we
11:56:50
같은 행에서 5의 값을 얻을 것입니다. 그래서 이제 저는 매우
can use the function lead and we will get at
11:56:53
빠르게 현재 달과 이전 달을 비교할 수 있습니다.
the same row the value five so now I can very
11:56:57
그리고 다음 달과도 비교할 수 있으며, 이제 다른
quickly compare the current month with the previous
11:57:00
경우에는 목록의 첫 번째 달에 관심이 있을 수 있습니다. 그래서 여기 1월이 될 것입니다.
month and as well with the next month and now in the other
11:57:03
첫 번째 달의 판매량을 가져오려면 first value 함수를 사용할 수 있습니다.
cases you might be interested in the first month of your list so it's going to be here January so in order to get the sales of
11:57:10
마지막 옵션에 대해, 이미 이해하셨을 것이라고 생각합니다. 마지막 달의 판매량을 가져올 수 있습니다.
the first month you can use the function first value so we're going to get at the same row 20.
11:57:17
그래서 이것이 바로 값 함수 또는 분석 함수의 목적입니다.
And now for the last option I think you already get it we can go and get the value of sales of the last month so here we can get the July so for that we're going to use the function last value and we will get the value of 40.
11:57:29
우리는 값에 접근할 수 있습니다.
So this is exactly the purpose of the value functions or analytical
11:57:32
우리가 접근할 수 있는 값의 목적이 바로 이것입니다.
functions we can access a value from
11:57:36
또 다른 행에서 값을 접근할 수 있는 것이며, 여기서도 매우 중요합니다.
another rows and here it's really important on side as well the
11:57:39
값 함수는 우리가 사용해야 하는 순위 함수와 같습니다.
value functions is like the ranking functions we have to use
11:57:42
데이터를 정렬하여 이해하기 위해서 사용하는 순서입니다.
the order by in order to sort the data in order to understand
11:57:45
이 예에서 첫 번째 행과 마지막 행이 무엇인지입니다.
what is the first row and the last row in this example the
11:57:48
데이터는 월별로 정렬되어 있습니다. 그래서 접근 함수는
data is sorted by the month so guys the access functions are
11:57:51
분석에 매우 중요합니다. 다른 행에서 값을 접근하기 위해 사용할 수 있습니다.
really important for analytics you can use it in order to access a value from other rows in order to do comparison all right so now let's have a quick overview of the syntax and the rules for the value functions
11:58:03
여기서 우리는 네 가지 함수, 리드, 레그, 첫 번째 값, 마지막 값을 가지고 있습니다.
So here we have four functions lead lag first value and last value. So as you can see we can group them into two groups.
11:58:10
리드와 레그는 서로 매우 유사합니다. 특히 구문에서 세 가지 인수를 사용할 수 있습니다.
So we have the lead and lag they are very similar to each other's. Especially with the syntax we can use three things or three arguments inside it.
11:58:17
표현식, 오프셋, 기본값입니다. 첫 번째 값의 경우 오직 표현식만 사용할 수 있습니다.
Expression offset default for both of them. For the first value we can use only an expression.
11:58:23
즉, 이러한 함수에 값을 전달해야 합니다. 비워둘 수 없습니다.
So that means we have to pass a value for those functions. You cannot leave it empty.
11:58:28
이제 표현식 데이터 유형에 대해 이야기해보겠습니다. 어떤 필드와 데이터 유형도 사용할 수 있습니다.
So now about the expression data type you can use any field with any data type.
11:58:32
예를 들어 숫자만 사용하는 것에 대한 제한은 없습니다.
there is no restrictions about only for example using numbers any
11:58:35
데이터 탭이 허용됩니다. 이제 창의 정의에 대해 이야기해보겠습니다.
data tab is allowed now about the definition of the window the
11:58:39
파티션은 일반적으로 다른 그룹과 마찬가지로 선택 사항입니다.
partition by as usual is optional like any other group the
11:58:42
여기서 정렬은 필수입니다. 반드시 정의해야 합니다.
order by here is a must you must define an
11:58:45
정렬은 순위와 같아서 비워둘 수 없습니다.
order by it's like the ranking so here you cannot leave
11:58:48
이제 마지막으로 프레임 절에 대해 이야기하겠습니다.
it empty now we come to the last one we have the frame clause they
11:58:52
리드와 레그 함수의 경우 프레임을 정의할 수 없습니다.
are really different stuff over here so for the first two functions lead a lag you are not allowed to define any frame so you are not allowed to define any subset of data.
11:59:01
순위와 매우 유사합니다. 정렬을 사용해야 하지만 창의 프레임을 정의할 수 없습니다.
It's very similar to the ranking. So you must use order by, but you cannot define the frame of the window.
11:59:07
그러나 다른 두 함수인 첫 번째 값과 마지막 값은 선택 사항입니다.
But for the other two functions, the first value and the last value, they are optional. You can go and use them.
11:59:13
마지막 값의 경우 프레임 절을 정의하는 것이 권장됩니다.
And for the last value, it is recommended to define frame clause. Don't worry about it. We're going to have enough examples in order to understand.
11:59:20
이러한 함수는 서로 다른 요구 사항이 있습니다. 모든 함수에 대한 일반 규칙은 없습니다.
So as you can see, those functions has different requirements. So there is no generic rule for all of them.
11:59:26
하지만 그들이 모두 동의하는 한 가지는 반드시 정렬을 사용해야 한다는 것입니다.
but one thing that they all agree on that you must use
11:59:29
이제 우리는 이러한 함수에 대해 깊이 파고들 것입니다.
order by so now as usual what we're going to do we're going to go and
11:59:32
함수에 대해 깊이 들어가 보겠습니다. 먼저 두 개의
deep dive into those functions we're going to address first the two
11:59:35
함수인 lead와 lag에 대해 다룰 것입니다. 이들은 서로 매우 유사하기 때문에 사용 사례를 이해할 수 있습니다. 물론 SQL에서 연습도 할 것입니다. 자, 시작해 봅시다.
functions lead and lag because they are very similar to each other's we can understand the use cases when to use them and of course we're going to practice in sql so let's go
11:59:48
lead와 lag 함수에서 lead 함수는 윈도우 내에서 다음 행의 값을 접근할 수 있게 해주고, lag 함수는 정반대로 이전 행의 값을 접근할 수 있게 해줍니다.
lead lag functions the lead function can allow you to access a value from the next row within a a window where the lag function is exactly the opposite, it can allow you to access a value
12:00:00
이전 행의 값을 윈도우 내에서 접근할 수 있게 해줍니다. 매우 쉬운 것처럼 들리죠? 그러니 SQL이 이러한 함수를 어떻게 실행하는지 이해해 봅시다.
from a previous row within a window. It sounds very easy, right? So let's understand how SQL going to execute those functions.
12:00:07
좋습니다. 이제 lead와 lag 두 함수의 문법에 대해 간단히 살펴보겠습니다. lead 함수에 대한 아주 간단한 예가 있습니다.
Okay, so now let's have a quick overview of the syntax for both of the functions lead and lag. We have a very simple example for the lead function.
12:00:14
그래서 보통처럼 함수 이름부터 시작합니다. 그것은 lead가 될 것입니다. 그리고 그 후에 인수를 전달할 것입니다.
So as usual, we start with the function name. It's going to be the lead. And now after that, we're going to go and pass the arguments.
12:00:21
보시다시피 여러 가지가 있습니다. 그러니 단계별로 진행해 봅시다.
And as you can see, we have here multiple stuff. So let's do it step by step.
12:00:24
첫 번째로 할 일은 표현식을 지정하는 것입니다.
So the first thing is that we're going to go and specify an expression and
12:00:27
데이터 유형은 어떤 데이터 유형이든 될 수 있습니다. 예를 들어,
the data type could be any data type it could be a
12:00:30
여기서 판매와 같은 숫자일 수도 있고, 이름과 같은 문자일 수도 있습니다.
number like here the sales it could be a character like names or
12:00:34
날짜나 다른 무엇이든 필요합니다.
dates or anything so this is required
12:00:37
우리는 표현식을 지정해야 하며, 비워둘 수 없습니다.
we have to specify an expression we cannot leave
12:00:40
이제 다음으로 넘어가면, 여기 숫자가 있습니다. 이것은 옵셋이며, 이 옵셋은 선택 사항입니다.
it empty and we can use any data type now moving
12:00:43
그래서 건너뛸 수 있습니다. 옵셋이란 우리가 여기서 무엇을 하고 있는지를 지정하는 것입니다.
on to the next one we have here a number so what is it this is the offset and this offset is optional so you can go and skip it so what
12:00:51
SQL에서 현재 행으로부터 몇 개의 행을 앞으로 또는 뒤로 이동할지를 지정하는 것입니다.
offsets means what we are doing over here we are specifying for
12:00:54
여기서 이 예제에서는 옵셋을 2로 지정하고 있습니다.
sql the number of rows forward or backward
12:00:58
lead를 사용하여 SQL에 2개의 행으로 점프하라고 지시하고 있습니다.
from the current row so here in this example we are specifying
12:01:01
다음 2개의 행으로 점프하여 값을 가져오라고 지시합니다.
the offset as two using the lead and with that we are telling sql
12:01:04
다음 두 행으로 점프해서 값을 가져와라
go jump to the next two rows and get me the value and
12:01:07
지연(lag)을 사용하고 있다면, SQL에게 두 행 위로 돌아가서 값을 가져오라고 말하는 것이다. 여기서 SQL에게 얼마나 많은 행을 건너뛰어야 하는지를 말하고, 아무것도 지정하지 않으면 비워두는 것이다.
if you are using lag it means you are telling sql go back two rows up and get me the value so here you are telling sql how many rows it needs to jump and if you don't specify anything like leave it empty
12:01:19
하나를 사용하게 될 것이므로, 이것의 기본값은
is going to go and use a one so the default of this or the
12:01:22
오프셋은 아무것도 지정하지 않으면 하나가 될 것이다. 알겠지, 다음으로 넘어가자.
offsets is going to be one if you don't specify anything all right moving
12:01:25
마지막 것과 세 번째 것으로 넘어가면, 이것도 선택 사항이다.
on to the last one and to the third one this is as well optional you
12:01:28
비워둘 수 있으므로, 여기서 기본값이 있다.
can go and leave it empty so here it is the default value
12:01:32
이 함수들로 인해 때때로 SQL에서 발생하는 일은
now what happens with those functions that sometimes sql
12:01:35
다음 두 행으로 점프하거나 그런 것들이고 SQL
jump to the next two rows or something like that and sql
12:01:38
아무것도 찾지 못해서 더 이상 접근할 수 있는 행이 없고 SQL은
doesn't find anything so there is no more rows available to access and with that sql going to go and return
12:01:44
null을 반환하게 되므로 SQL이 다음 행으로 가면
a null so that means if sql goes to the next rows or
12:01:47
이전 행으로 가면 아무것도 찾지 못하고 SQL은
go to the previous rows and doesn't find anything sql
12:01:51
기본적으로 null을 반환하게 되므로 만약
as a default gonna go and return a null so if
12:01:54
여기서 아무것도 지정하지 않으면 그런 시나리오에서는
you don't specify anything over here in those scenarios you
12:01:57
전체 함수에서 null 값을 반환하게 됩니다
will have null values as a return from the whole function
12:02:00
하지만 어떤 시나리오에서는 null을 원하지 않고 값을 원할 수 있으므로 여기서 기본값을 정의하고 null이 아니어야 하며 10이어야 합니다.
but in some scenarios you don't want to have a null you would like to have a value so here you are defining the default value so it should not be a null it should be a 10.
12:02:10
SQL이 아무것도 찾지 못하면 10을 반환해야 합니다
so sql if you don't find anything return a 10
12:02:13
null을 반환하지 마세요. 다시 말해 기본값은
don't return a null so again guys the default values the
12:02:16
모든 정보의 오프셋은 선택 사항입니다.
offsets all those informations are optional for you in order to
12:02:19
구성을 위해 모든 정보의 오프셋은 선택 사항입니다.
configure it but you should know the default if you don't use anything for
12:02:23
오프셋은 기본값이 null이 될 것이며
the offset is going to be one for the default value going to be null
12:02:26
표현식을 지정해야 합니다.
but you must specify an expression so
12:02:29
여기서는 비워둘 수 없습니다. 알겠죠? 그래서 lead 또는 lag 함수에 전달할 수 있는 인수에 대한 모든 것입니다.
here you cannot leave it empty all right so that's all about the arguments that you can pass to the lead or lag functions then the next stuff are the standard stuff so we have the
12:02:38
over 절이 있고, 일반적으로 partition by가 있습니다.
over clause then we have the partition by as usual
12:02:41
partition by는 선택 사항이며, 그 다음은 정렬입니다.
partition by is optional and then to the order
12:02:44
이 함수들은 순위를 매기는 함수와 같으며
by those functions it's like the rank functions it requires
12:02:47
데이터를 정렬해야 하므로 정렬하는 것이 필수입니다.
you to sort the data so it is a must to sort
12:02:51
데이터를 정렬해야 하며, 이를 건너뛸 수 없습니다.
the data otherwise it's clearly not know what is the next row what are
12:02:54
기본값과 오프셋을 구성할 수 있습니다. 알겠죠? 이제 매우 간단한 예제가 있습니다.
the previous rows so we have to sort the data it is required you cannot skip this so it is not optional all right so the syntax is not crazy right we have the usual stuff but only we can go and configure
12:03:05
우리는 월과 판매가 있으며, SQL이 lead와 lag 두 함수에서 어떻게 작동하는지 이해할 것입니다.
the default value and the offsets. Okay guys now we have a very simple example we have months and sales and we're going to go and understand how the SQL works for both of the functions lead and lag side by side.
12:03:16
이제 첫 번째 예제에서는 판매에 관심이 있습니다.
So now in the first example we are interested in the sales
12:03:19
다음 달의 판매를 위해 이를 사용하려고 합니다.
of the next month so in order to do that we're going to use
12:03:22
lead 함수를 사용하고, 인수로 판매를 지정할 것입니다.
the lead function so lead and then we're going to specify the argument it is the sales we want the value of sales and then we define the window
12:03:30
이렇게 월별로 정렬하므로 오름차순이 됩니다.
like this order by month so it's going to be ascending
12:03:33
이제 오른쪽에서 우리는 매출에 관심을 가질 것입니다.
and now in the right side we're going to be interested in the sales
12:03:36
이전 월의 매출에 대해 우리는
of the previous months so in order to do that we're
12:03:39
지연 함수를 사용할 것입니다. 이것은 리드와 매우 유사합니다.
going to use the lag function so it's going to be very similar to the lead
12:03:42
우리는 지연을 가지고 있으며, 매출에 관심이 있으므로
we have lag and then the sales since we are interested in the
12:03:45
매출을 월별로 정리할 것이므로 이제 isql이 어떻게 되는지 봅시다.
sales and we're going to sell the data by the month so now let's see how isql
12:03:49
단계별로 그리고 나란히 진행할 것입니다.
going to do it step by step and side by side so
12:03:52
isql이 첫 번째로 시작할 것이므로 이제 isql이 정보를 나란히 그리고 행별로 처리하는 방법을 봅시다.
isql going to start with the first so now let's see how isql going to process those informations side by side and row by row so it's going to start
12:03:59
여기 첫 번째 행에서 1월의 다음 달은 2월입니다.
with the first row over here what is the
12:04:02
우리는 이 행의 매출에 관심이 있습니다.
next month of january it is february and
12:04:06
다음 행에서 값을 가져올 것이며,
we are interested in the sales of this row so sql
12:04:09
값이 10이 될 것입니다. 이제 1월을 살펴보면
gonna take the value from the next row and we're
12:04:12
2월의 다음 달 매출을 볼 수 있습니다.
gonna have the value of 10 so now by looking through the january we can
12:04:16
같은 행에서 이제 오른쪽을 확인해 보겠습니다.
see the sales of the next month of february in the same
12:04:19
이전 월에 관심이 있으므로 첫 번째 행의 이전 월은 없습니다.
row so now let's check the right side over here now we are interested
12:04:22
그래서 우리는 그것을 어떤 것으로도 지적할 수 없습니다.
in the previous month so what is the previous month of the first row it will be nothing right so we cannot point
12:04:29
그래서 이것은 null이라고 표시될 것입니다.
it with anything that's why it's gonna say this
12:04:32
현재 행에 대한 이전 월이 없습니다.
is null there is no previous month for the current row
12:04:35
이제 다음 행으로 넘어갈 것입니다. 우리는 2월에 있습니다.
and we're gonna have it as a null okay so now it's gonna go
12:04:39
다음 월은 3월이 될 것입니다.
to the next row we are at february what is the next month
12:04:42
우리는 3월의 매출로 30을 얻을 것입니다.
it's gonna be march and it's gonna point to it so
12:04:45
그리고 오른쪽에서 2월의 이전 월은 1월이 될 것입니다.
we will get the 30 as the sales of the next month of march and on the right side what is the previous month of february it's going to be January, right?
12:04:55
그래서 이전 월의 매출 값을 가져올 것입니다.
So it's going to get the value, the sales of the previous month. And here we will get 20.
12:05:01
그래서 보시다시피 리드에서는 항상 다음 값을 확인하고 있습니다.
so as you can see it's very simple on the lead we are always checking the
12:05:04
지연에서는 항상 이전 값을 확인하고 있습니다.
next values on the lag we are always checking the previous
12:05:07
값이므로 계속 진행합시다. 현재 위치는
value so let's keep going we are currently at
12:05:10
3월입니다. 다음 달은 4월이 될 것입니다.
march what is the next month it's going to be april so
12:05:14
이렇게 가리킬 것입니다.
it's going to go and point to it like this and
12:05:17
다음 달 4월의 판매량을 가져올 것입니다. 오른쪽에서 이전 달은
we will get the sales of the next month april for the march on the right side what is the previous month it
12:05:24
2월이 맞죠? 그래서 2월로 가리킬 것입니다.
is february right so it's gonna go and point to february so we will get the sales of 10.
12:05:30
여기 마지막 행에 흥미로운 점이 있습니다.
and now interesting to the last row over here you can see that
12:05:33
우리는 4월에 있습니다. 다음 달은
we are at april what is the next month
12:05:36
4월에는 아무것도 없습니다. 끝에 도달했기 때문입니다.
of april there is nothing because we are at the end
12:05:39
우리 테이블의 끝에 도달했습니다. 다음 달이 없으므로 출력에서 null을 받게 됩니다.
of our table right so since there is no month after that we will get a null in the output but for the lag we still have a previous month for april so So what is the previous month?
12:05:49
3월입니다. 3월의 판매량을 가져올 것입니다.
It is March and we will get the sales of the March. So it's going to be 30. So that's it, guys.
12:05:56
정말 간단하죠? 그들은 반대의 일을 하고 있습니다.
It's really simple, right? It's just like they are doing the opposite things.
12:05:59
이제 이 값을 나란히 확인하면, 첫 번째 행에 대한 값이 항상 나타납니다.
So now if you check those values side by side, you can see that with the lead, we will always get a value for the first row.
12:06:07
마지막 행은 항상 비어 있을 수 있습니다.
But for the last row, it can be always empty because there is no next value. We are at the end of the table.
12:06:13
첫 번째 값의 지연을 확인하면, 항상 null을 받게 됩니다.
But if you check the lag for the first value, we will always get a null because there is no previous value or previous record from the first row.
12:06:22
마지막 기록에 대해서는 항상 값을 받을 것입니다.
And for the last record, as you can see, we're always going to get a value because we will have a previous value.
12:06:27
SQL이 오프셋과 기본값으로 작동하는 방식을 이해하기 위해 진행합시다.
Okay, let's move on in order to understand how SQL this time works with the offsets and the default value. So now we have the same data, but we have different tasks.
12:06:35
이제 왼쪽에서 두 달 후의 판매량을 가져오고 싶습니다.
So now on the left side, we would like to get the sales of two months ahead. So it's not the next month, it's going to be two months.
12:06:41
값을 찾지 못하면 null을 반환하지 말고 0을 반환하라고 SQL에 말하고 싶습니다.
And we would like to tell SQL, if you don't find any value, don't return null, return for us is zero. So this is going to be our default.
12:06:48
구문을 확인하면 이전과 정확히 같습니다.
Now, if you check the syntax, it's going to be exact like before.
12:06:51
지금은 두 달 후에 관심이 있으므로 오프셋을 추가하고 있습니다.
But we are adding now an offset of two because we are interested in two months ahead.
12:06:56
여기에서 기본값 0을 지정하고 있습니다.
And we are specifying here a default value zero. So if you don't find anything, put zero, don't put null.
12:07:02
오른쪽에서는 정반대입니다. 두 달 전의 판매량에 관심이 있습니다.
Now on the right side, we have the exact opposite. We are interested in the sales of two months ago.
12:07:08
직접적인 이전 달에 관심이 없습니다.
So we are not interested in the direct previous month. We need the sales of two months ago. And here the same thing.
12:07:15
아무것도 찾지 못하면 null을 반환하지 말고 0을 주세요.
if you don't find anything don't return null give us a zero so
12:07:18
보시다시피 같은 구문이지만 lag 함수를 사용하고 있습니다.
as you can see we have the same syntax but using the function lag so now let's
12:07:21
SQL이 이 단계를 단계별로 실행하는 방법을 이해합시다.
understand how sql can execute this step by step and side by side
12:07:24
이제 SQL은 첫 번째 달인 1월부터 시작할 것입니다.
so it's going to start with the first month january so now sql
12:07:27
두 달 후의 판매량이 무엇인지 물어볼 것입니다.
gonna ask what is the sales of two months ahead
12:07:30
우리는 1월에 있으며, 2월이 아니라 3월이 될 것입니다.
so we are at january it will not be february it's gonna be the month of march so it's gonna go and point it like this and we will get the value of 30.
12:07:40
그래서 30이라는 값을 얻게 될 것입니다.
so 30 is the sales of two months ahead and
12:07:43
이제 오른쪽에서도 1월에 있으며, 물어볼 것입니다.
now on the right side we are as well at january it's going to ask
12:07:46
두 달 전의 판매량이 무엇인지 물어볼 것입니다.
the question what is the sales of two months ago so
12:07:50
우리는 이전 데이터가 없기 때문에 아무것도 얻지 못할 것입니다.
we don't have any previous data right so we will
12:07:53
null을 반환할 것이지만, 기본값이 있는지 확인할 것입니다.
not get anything it's going to return null but it's
12:07:56
이번에는 null을 반환하지 않고 기본값을 반환할 수 있습니다.
going to check do we have a default value well yes so this
12:07:59
이번에는 0이 될 것입니다. 자, 이제 다음 값으로 가봅시다.
time it's girl will not return null it can return the default value
12:08:02
현재 2월에 있으며, 두 달 후의 판매량은 무엇인가요?
and this time it's going to be zero all right so now let's go to the
12:08:05
두 달 후의 판매량은 무엇인지 물어볼 것입니다.
next value we are currently at february what is
12:08:09
3월이 아니라 4월이 될 것입니다.
the sales of two months ahead so it will not
12:08:12
그래서 5라는 값을 얻게 될 것입니다.
be march it's gonna be april so it's gonna go and point it like
12:08:15
현재 오른쪽에서 2월에 있으며, 질문은 무엇인가요?
this and we will get the value of five so now on
12:08:18
두 달 전의 판매량은 무엇인가요?
the right side we are currently at february now the question is what
12:08:21
우리는 이전 달의 데이터를 가지고 있지만, 두 달 전의 데이터는 없습니다.
is the sales of two months ago we have history we
12:08:24
그래서 여전히 기본값으로 0을 얻게 될 것입니다.
have the previous month but we don't have two months in the history that's why we will still get zero at the output with the default value okay so now let's keep going to the next value we are currently at march
12:08:36
두 달 후의 판매량은 무엇인지 물어볼 것입니다.
is going to ask what is the sales of the two months ahead we
12:08:39
그 후 한 달만 있지만, 두 달 전의 데이터는 없습니다.
have only one month after that but we don't have two mothers that's
12:08:43
그래서 아무것도 찾지 못하고 null을 반환할 것입니다.
why isquiel will not find anything and it's going to return null but
12:08:46
기본값을 사용하여 값을 얻을 것입니다.
it's going to go and use the default so here we're going to go and get the value of
12:08:50
테이블에 더 이상 데이터가 없지만, 현재 3월에 있습니다.
zero there is no more data available in the table but now on the right side we are currently at march and we are asking what is the sales of two months ago so now we have enough history in the past
12:09:01
20이라는 값을 얻게 될 것입니다. 자, 이제 테이블의 마지막 달인 4월로 가봅시다.
and it's going to get the value of 20. All right. So now let's go to the last month over here in our table. April.
12:09:07
두 달 후의 판매량은 얼마인가요? 데이터가 없으니 0이 될 것입니다.
What is the sales of two months ahead? We don't have any data, so it's going to be zero as well.
12:09:13
현재 4월입니다. 두 달 전의 판매량은 얼마인가요? 충분한 데이터가 있습니다.
But now on the right side, we are currently at April. What is sales of two months ago? We have enough history.
12:09:19
SQL에서 리드와 래그가 오프셋과 기본값을 사용하는 방식입니다. 이 두 기능을 연습하기 위해 SQL로 돌아가겠습니다.
That's why is going to get and point it like this. So we will get the February going to be 10. So that's it.
12:09:25
이제 다음 작업이 있습니다. 현재 월과 이전 월 간의 판매량 변화를 분석하라고 합니다.
This is how SQL works with the lead and lag using offsets and as well default value. Let's go back in SQL in order to practice those two functions.
12:09:37
즉, 현재 월과 이전 월을 비교해야 합니다.
Okay, so now we have the following task and it says analyze the month over month performance by finding the percentage change in sales between the current and the previous month.
12:09:46
리드와 래그의 주요 사용 사례는 비교 분석을 수행하는 것입니다.
So that means we have to go and compare the current month with the previous month.
12:09:50
시간 시계열 분석이라고 합니다. 이는 비즈니스와 데이터를 분석하여 시간에 따른 패턴과 추세를 이해하는 방법입니다.
So the main use case for the lead and lag is to do comparison analyzes and we have a very common use case.
12:09:56
결정권자나 기업에서 가장 중요한 질문 중 하나는 연간 분석 또는 월간 분석을 수행하는 것입니다.
It's called time series analyzes. So it is the method of analyzing our business, our data in order to understand the patterns and trends over the time.
12:10:07
연간 분석은 우리에게 이해하는 데 도움이 될 것입니다.
And one of the most important and classical question that you're going to get from the decision makers or businesses to do year over year analysis or month over month analysis.
12:10:17
성과의 전반적인 성장 또는 감소를 이해하는 데 도움이 될 것입니다.
So the year over year analysis is going to help us in order to understand
12:10:21
우리 비즈니스의 성과가 시간이 지남에 따라 어떻게 변화하는지.
the overall growth or decline in the performance
12:10:24
다른 한편으로는 월간 분석이 있습니다.
of our business over the years over the time but in
12:10:27
단기 추세 분석을 수행하고 발견하기 위해.
the other hand we have month over month analyzes in order to do
12:10:30
계절성의 패턴을 이해하는 것이 주요 초점입니다.
short term trends analyzes and as well discover
12:10:34
시간에 따른 비즈니스 성과를 이해하는 것입니다.
the patterns in the seasonality so the main focus is to understand
12:10:37
이제 hkl로 돌아가서 작업을 해결해 보겠습니다.
the performance of our business over the time so
12:10:40
먼저 데이터를 수집하고 계산을 해야 합니다.
now let's go back to hkl in order to solve the task okay guys so now let's go and do it step by step now what is the first step before we go and compare things together
12:10:48
먼저 현재 월의 총 판매량을 알아내야 합니다.
we have to collect the data we have to do the calculations first so
12:10:52
그리고 이전 월의 총 판매량을 알아내야 합니다.
we have to find out first the total sales for the current month
12:10:55
그 후에 비교할 수 있습니다. 이제 쉬운 것부터 시작해 보겠습니다.
and then the total sales for the previous month and
12:10:58
현재 월의 현재 판매량을 알아내야 합니다.
after that we can go and compare them so now let's start with the easy stuff
12:11:01
이를 위해 간단한 선택을 하겠습니다. 주문 ID와 주문 날짜가 필요합니다.
we have to find out the current sales for the current
12:11:04
그리고 판매량을 수집하겠습니다. 지금은 이 정도면 충분합니다.
month so in order to do that let's just do very simple select so what do we need we need let's take the order id let's take the order dates because inside it we have the month
12:11:15
판매 주문에서.
and let's go and collect the sales so that's it for now
12:11:18
이제 실행해 보겠습니다.
from sales orders so
12:11:22
이제 실행해 보겠습니다. 우리가 얻은 결과는
let's go and execute this so now the result we got the
12:11:25
일반적인 내용으로 10개의 주문이 있습니다.
usual stuff we have 10 orders sales and order
12:11:28
주문 날짜는 일 단위입니다.
dates but the order date is on the level of the days
12:11:31
전체 날짜에 관심이 없고
and we are not interested on the whole date we would
12:11:34
오직 월만 얻고 싶습니다.
like to get only the month in order to calculate the total sales
12:11:37
이제 월을 추출하기 위해 함수를 사용할 것입니다.
for the month now we're going to go and use a function in order to extract
12:11:40
날짜에서 월을 추출하는 방법을 보여드리겠습니다.
the month from a date don't worry about it we can have a dedicated chapter
12:11:43
SQL에서 날짜 형식을 다루는 방법을 보여드리겠습니다.
in order to show you how to deal with the dates format
12:11:47
이제 사용할 간단한 함수가 있습니다.
in sql so now what we're gonna do we will use
12:11:50
이 함수를 '주문 월'이라고 부르겠습니다.
a very simple function called month and order
12:11:53
이제 실행해 보겠습니다. 결과를 확인해 보세요.
dates and let's call it order month so
12:11:57
새 필드에는 월만 포함되어 있습니다.
that's it let's go and execute it now as you can see we got
12:12:00
여기에는 1월, 2월, 3월이 있습니다.
the new field where we have only the month of formations so
12:12:03
이제 각 월의 총 판매량을 찾고 싶습니다.
here we have january february and march so now the next step is that we
12:12:06
그렇다면 그룹화를 사용하겠습니다.
want to find the total sales for each month
12:12:09
판매량의 합계를 구할 것입니다.
so what we're gonna do we're gonna go and use group buy so let's do that we're gonna go and say we want the sum of sales i'm just gonna call it current month sales
12:12:21
이제 월별로 그룹화하겠습니다.
and let's go and get rid of all those informations we're
12:12:25
그룹화하고 월을 가져오겠습니다.
gonna go and group by the month right so group
12:12:28
이제 실행해 보겠습니다. 매우 간단합니다.
by and let's have the month so that's it let's
12:12:31
현재 월의 총 판매량을 확인했습니다.
go and execute it so it's very simple right we got
12:12:34
이제 이전 월의 총 판매량을 찾아보겠습니다.
now the three monsters and the total sales of the current month so now with that we got the The first information that we need in order to do the comparison, we have for each row the total sales for the current month.
12:12:45
이전 월의 총 판매량을 나란히 찾겠습니다.
So now the next thing that we're going to do is to find out the total sales for the previous month like side by side in the same row.
12:12:52
이를 위해 지연 함수를 사용할 수 있습니다.
And in order to do that, we have learned we can go and use the lag function.
12:12:56
이제 이전 월에 관심이 있습니다.
So we're going to go and integrate the lag window function in the same group by. So we can do it like this.
12:13:02
그래서 판매량의 합계를 구할 것입니다.
So lag, we are now interested in the previous month.
12:13:06
그래서 우리는 판매의 합계를 구할 것입니다. 그 후에 윈도우를 정의할 수 있습니다.
So that's why we're going to go and get the sum of sales as an expression inside it. And after that, we can define the window.
12:13:13
이렇게 될 수 있고 정렬은 필수입니다. 그래서 데이터를 월별로 정렬할 것입니다.
It can be like this over and order by is a must. So we're going to go and sort the data by the month. Right.
12:13:19
자, 이제 해봅시다. 그렇게 해서 우리는 이전 달의 판매를 정의했습니다.
So let's go and do it. And with that, we have defined the previous month sales.
12:13:24
당신은 이전 달의 판매입니다. 이제 결과를 보기 위해 실행해 봅시다.
So you are the previous month sales. So now let's go and execute it in order to see the results. All right.
12:13:31
우리는 첫 번째 기록과 첫 번째 달에 있기 때문에 null입니다.
So now let's check the results. The first row. What is the previous month? There is no previous month.
12:13:36
이제 2월로 가서 판매가 무엇인지 봅시다.
we are at the first record and the first month that's why we have null
12:13:39
1월의 이전 달 판매는 105입니다.
now let's go to february what is the sales
12:13:42
이것은 맞습니다. 이제 마지막 값인 3월로 갑니다.
of the previous month from january it is 105 so
12:13:46
2월의 이전 달 판매는 무엇인가요?
this is correct and now to the last value to the march
12:13:49
195입니다. 그래서 우리가 얻었습니다.
what is the sales of february the previous month
12:13:52
2월의 이전 달 판매는 195입니다.
it is 195 so that we got
12:13:55
우리가 가진 두 가지 정보는 현재 달과
the two informations we have the current month and
12:13:59
이전 달입니다. 여러분, 이건 마법 같죠? 정말 간단합니다.
as well the previous month so guys as you can see it's magic right it's very simple we can go and use the lead and lag functions in order to
12:14:06
다른 행의 값을 접근할 수 있습니다.
access another values from another rows without
12:14:09
복잡한 조인을 하지 않고, 자, 이제 무엇을 할까요?
doing any complicated joins and so on okay so now what
12:14:12
다음 단계는 현재 달의 총 판매에서 이전 달을 빼는 것입니다.
is the next step we're going to go and subtract the total sales from the current month with the previous month so in order to do that we're going to go and use a sub query like this
12:14:22
그래서 select star from을 사용하고 이렇게 서브 쿼리로 가질 것입니다.
so select star from and we're going to have it like this as sub query and now the calculation
12:14:29
계산은 매우 간단합니다. 이걸 조금 아래로 이동하겠습니다.
is very simple let me just move this little bit down
12:14:32
현재 달에서 이전 달을 뺍니다.
so it is the current month subtracted
12:14:36
이를 월별 변화라고 부릅시다.
from the previous month and let's go and call
12:14:39
그게 전부입니다. 이제 실행해 봅시다.
it month over month change so
12:14:43
첫 번째 달의 결과를 확인해 보세요. 값이 없습니다.
that's it let's go and execute this so now let's go
12:14:46
2월로 넘어가면 여기서 플러스가 있습니다.
and check the results for the first month you can see that we don't have any value and that is correct because the previous month is empty so there is no change and now
12:14:54
90입니다. 즉, 개선이 있음을 의미합니다.
Moving on to the February you can see over here we got plus
12:14:57
우리의 판매 성과가 향상되었습니다.
90 that means we have here improvement in the
12:15:01
우리의 판매 성과가 개선되고 있습니다.
performance of our sales now moving on to the last
12:15:04
정말 나쁜 상황입니다. 우리의 성과가 감소했습니다.
one it's really bad we have declined in our performance
12:15:07
현재 월은 정말 나쁜 상황임을 알 수 있습니다.
we can see that we have minus 115 so that
12:15:10
3월은 정말 나쁜 달입니다.
means the current month is doing really bad compared to the
12:15:13
출력에서 절대 수치를 확인할 수 있습니다.
previous month so the march is really bad month okay so
12:15:16
비율 변화를 찾아야 합니다.
now as you can see in the output we got the absolute numbers but the task
12:15:19
이를 백분율로 변환할 수 있습니다.
says find the percentage change so we have have to convert
12:15:22
새로운 열에서 진행하겠습니다.
this to a percentage and we can do it like this it's very
12:15:25
조금 확대하겠습니다.
simple let's do it in a new column just gonna zoom
12:15:28
변화는 차이를 이전과 나눈 것입니다.
out a little bit so it's gonna be the change
12:15:32
이전 월 판매로 나누고 100을 곱합니다.
the differences divided by the previous
12:15:35
백분율을 얻기 위해서입니다.
month sales and then let's go and multiply it with 100
12:15:38
정수이기 때문에 0이 나옵니다.
in order to get the percentage so like this and now as you can see we got zeros and that's because those numbers are integer so we
12:15:46
첫 번째 값을 변환하겠습니다.
to go and cast one of those values just gonna do it for the first
12:15:50
그래서 캐스트하고 당신은 떠다니고 있습니다.
so cast and you are float so
12:15:53
그게 다입니다. 이제 다시 실행해 봅시다.
that's it let's go and execute it again now the
12:15:56
결과가 더 좋아 보입니다. 우리는 비율을 가지고 있지만 소수점이 많습니다.
result looks better we have the percentages but we have a lot of decimals
12:15:59
그래서 숫자 2를 돌아봅시다.
so let's go around the number two let's
12:16:03
소수점 하나라고 가정합시다. 그래서 하나만 있고, 이름을 붙여줍시다.
say one decimals so only one and let's give
12:16:06
그래서 당신은 월별 비율입니다.
it a name so you are month over month percentage
12:16:09
그래서 실행해 봅시다. 이제 보시다시피
so let's execute so now as you can see
12:16:12
상황이 나아지고 있으며, 이를 통해 현재와 이전 월 간의 매출 변화를 계산했습니다. 이것이 월별 분석을 수행하는 방법입니다.
things get better and with that we have calculated the percentage change in sales between the current and the previous months and this is how we do month over month analysis
12:16:27
좋습니다. 이제 리드 및 결측 함수에 대한 또 다른 사용 사례가 있습니다.
all right so now we have another use case for the lead and lack function we can
12:16:30
고객 유지 분석을 수행하기 위해 이를 사용할 수 있습니다.
use them in order to do customer retention analyzes it's
12:16:33
고객 행동과 충성도를 측정하는 것이 전부입니다. 우리는 비즈니스와 의사 결정자가 충성 고객과 강한 관계를 구축하도록 돕고 있으며, 그들의 필요에 집중할 수 있도록 합니다.
all about measuring the customer behavior and loyalty so we are helping the business and decision makers to build strong relationship with the loyal customers and for them as well to focus on their needs.
12:16:44
이제 고객 유지 분석을 위해 리드 및 레그 함수를 사용하는 방법을 살펴보겠습니다. 시작해 보죠.
So now let's see how we can use lead and lag function in order to do customer retention analyzes. So let's go.
12:16:50
고객 충성도를 분석하기 위해 고객을 주문 간 평균 일수를 기준으로 순위를 매기라는 작업이 주어졌습니다.
All right. So now we have the following task and it says in order to analyze customer loyalty, rank customers based on the average days between the orders.
12:16:58
여기에서 많은 일이 진행되고 있습니다. 단계별로 진행해 보겠습니다. 항상 매우 간단한 선택으로 시작하고 싶습니다.
So there is a lot of things going on over here. Let's do it step by step. And I would like always to start with a very simple select.
12:17:05
주문 ID와 같은 정보를 선택해 보겠습니다.
So let's go select information like the order ID.
12:17:09
고객 ID를 가져오고 싶습니다.
get the customer id and as well since we
12:17:12
주문 날짜에서 며칠을 원하기 때문에
want the days we would like to have the date so order dates from
12:17:17
판매 주문 테이블에서
the table sales orders and
12:17:20
고객별로 정렬해 보겠습니다.
let's go and sort the data so order by customer
12:17:24
주문 날짜와 고객 ID로 정렬하겠습니다.
id and order dates so that's
12:17:27
이제 실행해 보겠습니다. 평소처럼 10개의 주문을 가져옵니다.
it let's go and execute so now as usual we get our 10 orders
12:17:30
고객과 그들이 주문한 날짜를 확인해 보겠습니다. 이제 작업을 확인하고 주문 간의 일수를 해결해 보겠습니다.
the customers and when they did order so now let's check the task let's solve this over here days between the orders so we have to find how many days are between two orders.
12:17:42
예를 들어, 고객 번호 1을 확인해 보면, 그는 1월 10일에 주문했습니다.
For example, if we check the customer number one over here, he did order around 10 January
12:17:48
두 번째 주문은 10일 후인 1월 20일입니다.
and the second order is like after 10 days, 20 January.
12:17:52
따라서 이 두 날짜를 빼야 합니다.
So we have to go and subtract those two dates.
12:17:55
모든 정보를 같은 행에 두어야 합니다.
Now in order to subtract those informations and do calculations, we have to have everything in the same row.
12:18:01
예를 들어, 여기 첫 번째 행에 있다면,
So for example, if we are at the first row over here, I
12:18:04
다음 주문의 날짜에 대한 열도 추가하고 싶습니다.
would like to have as well one column about the next
12:18:07
다음 주문의 날짜를 가져와야 하므로
order so the date of the next order so we have to
12:18:10
다른 행에서 값을 가져와야 합니다. 물론 조인을 할 수 있지만,
access a value from another row of course we can go and do
12:18:13
리드 및 레그 함수가 있습니다.
joins but we have lead and lag functions and
12:18:17
이 시나리오에서는 리드 윈도우 함수를 사용할 것입니다.
for this scenario we're going to go and use the lead window function
12:18:20
그럼 시작해 보겠습니다. 현재 주문으로 주문 날짜를 호출하겠습니다.
so let's go and do that i'm going to go and call the order
12:18:23
현재 주문으로 주문 날짜를 호출하겠습니다.
date over here as a current order and
12:18:26
리드를 계산해 보겠습니다.
let's go and calculate the lead so we i
12:18:30
다음 주문 날짜를 가져오고 싶습니다.
would like to get the next order date so i would like
12:18:33
이 값을 같은 행에서 가져오고 싶습니다.
to get this value over here in the same row that's why with
12:18:37
이번에는 주문 날짜를 가져오겠습니다.
this time we're going to get the order dates and
12:18:40
이제 창을 정의해야 하고 데이터를 분할해야 합니다.
now let's go and define the window now we have to go and partition
12:18:43
각 고객을 개별적으로 분석하고 있습니다.
the data because we are analyzing each customers separately
12:18:46
그래서 분할해야 합니다.
right so that's why we have to partition that
12:18:49
고객 ID로 분할해야 하고
by the customer id and of course in order to do
12:18:52
리드를 사용하기 위해 정렬해야 합니다.
the lead we have to use the order by so let's go and
12:18:55
정렬을 정의해야 합니다.
define that as well order by and it's going to be by
12:18:59
주문 날짜로 정렬해야 합니다.
the order date so now we have to give it a name the
12:19:02
현재 주문의 다음 주문입니다.
order date here is the current order it's going to be the
12:19:05
다음 주문을 확대해 보겠습니다.
next order so next order let me
12:19:08
조금 축소하고 실행해 보겠습니다.
zoom out a little bit and make this smaller so
12:19:12
출력에서 새로운 열을 얻었습니다.
let's go and execute it so now as you can see in the output we
12:19:15
현재 주문과 현재 행을 얻었습니다.
got a new column called next order and with
12:19:18
다음 행의 값을 얻었습니다.
that we got the current order the current row and
12:19:21
다음 행은 1월 20일입니다.
as well the value from the next row so what is the next row it's going to be the 20th january the same thing of course for
12:19:27
여기에서 현재 주문 날짜가 있습니다.
the next row over here we have the current order date
12:19:30
다음 주문 날짜와 같습니다.
and the next order date so this value going to be exactly
12:19:34
2월 15일이 됩니다.
as the next one over here 15 of february
12:19:37
이것이 전체 창입니다.
and then since we are working with windows this is this
12:19:40
고객의 마지막 주문입니다.
is the whole window over here the last order for this
12:19:43
2월 15일입니다. 다음 주문이 없습니다.
customer it's 15 of the february there is no next order so this is going to be null the same thing if you check the other customers you can see always the last order don't have any next order.
12:19:54
모든 것이 괜찮은 것 같습니다.
So looks like everything is fine. And for the last customer, he has only one
12:20:00
현재 주문과 다음 주문이 같은 행에 있습니다.
an order. So now with this, we got all the informations for our calculations.
12:20:04
이 두 주문 사이의 일수를 계산할 수 있습니다.
So we have the current order and the next order in the same row.
12:20:07
이제 우리는 두 주문 사이의 날짜를 얻기 위해 이를 빼낼 수 있습니다.
Now we can go and subtract them in order to get the days between those two orders.
12:20:13
날짜를 빼기 위해 date 함수를 사용해야 합니다. 이 함수들에 대해 걱정하지 마세요.
And now in order to subtract date, we have to use the function date. Diff don't worry about those functions.
12:20:17
다음 장에서 모든 내용을 설명할 수 있습니다. 그러니 이제 저와 함께 이 단계들을 따라오세요.
We can explain all those stuff in the next chapters. So now just follow me with those steps.
12:20:22
우리가 할 일은 이 날짜, 즉 주문 날짜를 여기 있는 전체와 빼는 것입니다. 그래서 여기 있는 전체는 다음 주문입니다.
What we're going to do, we're going to go and subtract this date, the order date with the whole thing over here right so the whole thing here is the next order so let's do it in a new line
12:20:33
그리고 이것은 매우 간단할 것입니다. 그래서 날짜 차이를 찾고 있습니다.
and it's going to be very simple so date def we
12:20:36
두 날짜 사이의 차이를 찾고 있습니다.
are finding the differences between two dates so the
12:20:39
구문은 이렇게 될 수 있습니다. 먼저 우리가 이야기하고 있는 것이 무엇인지 정의해야 합니다.
syntax can be like this first we have to define what we are talking about
12:20:42
그것이 일, 월, 년 등인지 알려줘야 합니다.
are they days months years and so on so we have to tell
12:20:45
SQL에서 날짜 차이를 찾으세요. 이제 우리는 두 날짜를 지정해야 합니다.
sql find me the differences in days now we
12:20:48
첫 번째는 주문 날짜가 될 것이고, 현재 날짜가 있으며 두 번째 날짜는
have to specify two days so the first one going to be the order date this is the current date and the second date
12:20:55
여기서 전체가 될 것입니다. 그러니 가져와서
going to be the whole thing from here so let's take it and
12:20:58
나란히 놓고 이 계산은
put it side by side and this calculation going to give
12:21:01
날 수를 줄 것입니다. 그래서 우리는 이것을 날이라고 부를 것입니다.
us number of days so we're going to call this days
12:21:05
다음 주문까지의 날입니다. 자, 이제
until next order all right so now let's
12:21:08
전체를 실행해 보겠습니다. 이제 결과를 확인해 보겠습니다.
go and execute the whole thing so now let's check the result as
12:21:11
여기서 우리는 10을 얻었습니다. 이것은 두 날짜 사이의 10일입니다.
you can see over here we got 10 so this is 10 days between those two dates and the next one we have around 26 days here we have
12:21:19
다음은 31일이 될 것입니다. 그래서 우리는 한 달이 있습니다.
null because we don't have here a date and for the next
12:21:22
여기서 모든 것이 완벽하게 작동하고 있습니다.
one we have 31 days so we have a whole month over
12:21:26
우리는 이 부분만 해결했습니다. 그들의 주문 사이의 날입니다.
here so everything is working perfectly and with that we
12:21:29
여러분, 보시다시피 이것이 리드의 마법입니다.
have solved only this part days between their
12:21:32
그리고 레그 함수입니다. 우리는 정보를 쉽게 접근할 수 있습니다.
orders so guys you see right this is the magic of the lead
12:21:35
같은 행에서 중요한 분석을 수행하기 위해 필요한 모든 정보를.
and lag function we can very easily access any information
12:21:38
매우 간단한 쿼리로 우리는 조인 같은 복잡한 작업을 하지 않습니다.
you need in the same row in order to do such important
12:21:41
리드 함수를 지정하고 있습니다. 이제 우리는 필요한 모든 정보를 얻었습니다.
analysis and with very simple query we are not doing any crazy stuff like joining and stuff we are just
12:21:47
다음으로 우리는 이들의 평균을 계산할 것입니다.
specifying the lead function so now we got all the informations that
12:21:50
우리가 필요한 정보를 모두 얻었으니
we need next we're gonna go and calculate the average of those
12:21:54
이제 평균을 계산할 것입니다
days so in order to do that we have to go and use a sub
12:21:57
일수를 계산하기 위해 서브 쿼리를 사용해야 합니다
query so let me just zoom out so let's
12:22:00
별을 선택하고 준비합시다
go and select star just prepare the
12:22:03
서브 쿼리로 전체를 만들 것입니다
sub query so the whole thing gonna be a sub query i'm
12:22:06
정렬은 이제 필요하지 않으니 제거합시다
just get rid of the order by it's not now necessary so
12:22:10
이렇게 놓고 이동시키면 이제 우리가 필요한 것은
let me just put it like this and shift it so now what do we need we need the average of the days so we need the
12:22:16
일수의 평균입니다
average of this value so what can we do we can go and use
12:22:19
고객별로 평균을 찾아야 하므로
a group by so customer id since we
12:22:23
각 고객의 평균을 찾아야 합니다
have to find the average for each customers and we're going to get this
12:22:26
값을 얻고 평균 일수라고 부를 것입니다
value and say average days until the
12:22:29
다음 주문까지의 평균 일수라고 부를 것입니다
next order and we're going to call it average days so
12:22:33
고객별로 그룹화해야 합니다
and we have here to group by so group by customer
12:22:37
매우 간단한 평균 및 그룹화 문장을 작성하고 있습니다
id so like this just make this a little bit smaller and zoom in here so that's it now we
12:22:43
이제 실행해 봅시다
are just doing a very simple average and group by statements
12:22:47
데이터를 집계할 것입니다
so let's go and execute it now as you can see it's gonna go and
12:22:50
이제 고객이 네 명만 있습니다
aggregate the data so we have now only four customers and
12:22:53
각 고객의 주문 간 평균 일수입니다
for each customer we have the average days between
12:22:57
우리 작업에서 무엇이 빠졌는지 확인해 보세요
their orders so now what is missing in our task if you check
12:23:00
고객을 기준으로 순위를 매기라고 합니다
over here it says rank the customers based
12:23:03
순위 함수를 사용해야 합니다
on this average so we have to go and use the rank function so
12:23:06
그룹화와 함께 사용할 것입니다
here again another window function that we have to go and use we're
12:23:10
조금 더 작게 만들고 여기서 해봅시다
gonna do it together with the group by so let me just make this
12:23:13
순위 함수로 진행하겠습니다
a little bit smaller and then let's do it over here
12:23:16
이렇게 정의할 것입니다
so i'm just going to go with the rank function then
12:23:19
우리는 이렇게 윈도우를 정의할 것입니다.
we're going to define the window like this over order by
12:23:22
그리고 우리는 평균 일수에 따라 데이터를 정렬할 것입니다.
and then we're going to go and sort the data by the average days
12:23:26
그래서 우리는 이 계산을 가져올 것입니다.
so that means we're going to go and get this calculation over here
12:23:29
그래서 우리는 가장 낮은 평균 일수에 집중하고 있습니다.
and put it as order by it's going to be ascending
12:23:32
그래서 이제 결과를 확인하면 순위가 생겼습니다.
so we are focusing on the lowest average days so that's it let's call it rank average so now let's go and execute this
12:23:40
그래서 이제 결과를 확인하면 순위가 생겼습니다.
so now by checking the result you can see now we have a ranking for
12:23:44
평균에 따라 고객 1 또는 가장 충성스러운 고객은
the average and here scale says that the
12:23:47
고객 번호 4는 사실 정확하지 않습니다.
number one customer or the number one loyal customer is the
12:23:51
4번 고객에 대한 정보가 많지 않습니다.
customer number four which is not really correct because the number
12:23:54
그는 단 한 번만 주문했습니다.
four we don't have a lot of informations about this customer he
12:23:57
이 고객을 필터링하고 제거해야 합니다.
or she did order only once so either now you go and
12:24:00
평균이 null이면 순위에 넣지 마세요.
like filter the data and remove this customer when you say if
12:24:03
이 값을 매우 큰 값으로 바꿀 수 있습니다.
the average is null then don't put it in the rank or
12:24:07
우리 목록의 끝에 두기 위해서입니다.
we can go and replace this value with a very huge value in
12:24:10
여기에서 null을 qualisk로 바꿉니다.
order to make it at the end of our list for example we can
12:24:13
이렇게 하고 만약에
go over here and replace the null with qualisk
12:24:16
평균이 null이면 이렇게 해주세요.
like this and we say if
12:24:19
미친 숫자를 주세요, 매우 큰 숫자입니다.
the average is null then let's say give me a
12:24:22
이제 실행하고 이 고객이
crazy number like this very huge one so that's
12:24:26
우리 목록의 끝에 있을 것입니다.
it let's go and execute and now as you can see this customer gonna be
12:24:29
이제 가장 충성스러운 고객이 1위입니다.
at the end of our list and now we can see that the
12:24:32
고객 2명은 2위입니다.
most loyal customer is number one and then the other two
12:24:35
같은 평균을 가지고 있으므로 같은 순위입니다.
customers are in the rank two here we are sharing the
12:24:38
작업을 해결하고 고객을 평균 일수에 따라 순위를 매겼습니다.
same rank since we have the same average so guys with that we have solved the
12:24:41
주문 간의 평균 일수에 따라.
task and we have ranked the customers based on the average days
12:24:44
주문 간 평균 일수를 기준으로 고객을 순위 매겼습니다.
between their orders so we have now a really
12:24:48
우리는 이제 정말 좋은 순위를 가지고 있으며 고객의 행동을 이해할 수 있습니다.
nice rank and we can understand now the behavior of the customers and
12:24:51
아마도 고객 1번에 집중하고 이해해야 할 것입니다.
maybe we have to go and focus on the customer number one and understand
12:24:54
여기서 고객 유지 분석을 수행하는 데 도움이 된 기능은 다음 주문을 찾기 위한 리드 함수입니다.
here or share needs and of course the function that helped us here in order to do such a customer retention analysis is the lead function in order to find the next order to calculate the days.
12:25:05
이것이 리드 함수를 사용하여 이러한 사용 사례를 수행하는 방법입니다.
So this is how you use lead functions to do such a use case.
12:25:12
첫 번째 값과 마지막 값 함수입니다. 이름이 모든 것을 말해줍니다.
The first value and the last value functions. I think the name says everything, right?
12:25:16
첫 번째 값은
So the first value can allow you to access a value from
12:25:20
창 내 첫 번째 행에서 값을 가져올 수 있습니다.
the first row within a window where the last
12:25:23
마지막 행에서 값을 가져올 수 있습니다.
value exactly the opposite it can allow you to access a value from
12:25:26
이제 SQL이 이러한 함수를 실행하는 방법을 이해해 보겠습니다.
the last row within a window easy right so now
12:25:29
이제 평소처럼 매우 간단한 예제를 가지고 있습니다.
let's understand how sql execute those functions okay so
12:25:32
우리는 두 번 가지고 있으며 나란히 비교하고 싶습니다.
now as usual we have this very simple example we have the monsters and sales and
12:25:36
두 함수, 첫 번째 값과 마지막 값을 나란히 비교하고 싶습니다.
we have it twice because we would like now to go and compare side
12:25:39
이제 왼쪽에서
by side the two functions first value and last value
12:25:42
첫 번째 달의 매출을 가져오고 싶습니다.
so now for the left side we would like to get the sales of
12:25:45
오른쪽에서는 마지막 달의 매출을 가져오고 싶습니다.
the first month and on the right side we would like to get
12:25:48
이제 첫 번째 작업을 위해 첫 번째 값을 사용할 수 있습니다.
the sales of the last month so now for the first task
12:25:51
매출을 원하므로 첫 번째 값 함수의 인수는 매출이 됩니다.
we can go and use the first value it's very simple so the first
12:25:55
그리고 창은 이렇게 정의됩니다.
value function then the argument going to be sales since we want the sales
12:25:58
월별로 첫 번째 달을 가져오고 싶습니다.
and then the window going to be defined like this order
12:26:01
따라서 이제 평소처럼 정렬을 사용해야 합니다.
by month because we want to get the first month so
12:26:04
오른쪽에서 마지막 달의 매출을 가져오기 위해
as usual we must use order by now on
12:26:07
마지막 값을 사용할 수 있습니다.
the right side in order to get the sales of the last month we can go and use the
12:26:10
월별로 정렬하여 왼쪽과
last value right so the same things last value sales
12:26:14
오른쪽에서 프레임 정의를 사용하지 않지만 기본값은
over order by month so as you can see on the left and
12:26:17
기본값이 사용될 것입니다.
right we don't use any frame definition but the default is
12:26:20
이제 SQL이 두 가지를 처리하는 방법을 살펴보겠습니다.
going to be used from this all right so now let's see how sql is going to process both
12:26:23
이 쿼리들을 나란히 배치할 것입니다.
of those queries side by side so the first step is going
12:26:26
데이터를 정렬하는 첫 번째 단계입니다.
to go and sort the data they are already sorted from the lowest
12:26:29
가장 낮은 값에서 가장 높은 값으로 정렬됩니다.
to the highest and then the next step is going to start row by row
12:26:32
왼쪽에서 첫 번째 값을 찾는 단계입니다.
finding the first value on the left side so what is
12:26:35
정적이며 항상 1월을 가리킬 것입니다.
the unbounded proceeding it's going to be static and always
12:26:39
항상 양쪽에서 진행됩니다.
pointing to january so this is always
12:26:42
현재 행은 이렇게 됩니다.
going to be the unbounded proceeding we have it in both sides
12:26:45
첫 번째 행의 시작에서 진행됩니다.
like this and what is the current row it's
12:26:48
여기서도 같은 것들이 있습니다.
going to be at the start at the first row and on the right side the
12:26:51
여기서도 같은 것들이 있습니다.
same things over here so the
12:26:54
이 창에서 첫 번째 값은 20입니다.
window definition gonna be is only one row right so
12:26:58
정확히 같은 결과를 얻을 것입니다.
what is the first value in this window it is 20 right the same things on the right side what is the last value in this window it is as well 20.
12:27:08
두 번째 행으로 이동하겠습니다.
so we will get exactly same results now let's move to the second row
12:27:12
2월을 가리키게 됩니다.
so it's going to be pointing to february and the
12:27:15
여기서 프레임 정의가 확장됩니다.
frame definition going to be here extended like this so
12:27:18
이 프레임의 첫 번째 값은 20입니다.
what is the first value in this frame it's going
12:27:21
이 프레임의 마지막 값은 10입니다.
to be as well 20 right so in the output we're going to
12:27:24
이제 3월로 넘어가겠습니다.
get to 20 and now in the right side the current row going to be as well pointing to february and the window going to go get extended so now what is the last value of this frame it's going to be 10.
12:27:36
프레임이 확장됩니다.
now let's keep going we're going to go to the march and the
12:27:39
기본 정의는 항상 정적입니다.
window going to get extended what is the first value it's always going to be the same so 20 on the right side window going to get extended what is the last value it's going to be 30.
12:27:52
프레임이 확장되면서 이동합니다.
so as you can see the default definition is always having the static
12:27:55
첫 번째 판매는 오른쪽에서 20이 될 것입니다.
start always the same start of the subset and as we are moving with the current row the frame going to get extended so now moving to the last one and And with that, we will get the whole data set inside the frame.
12:28:07
이번에는 마지막이 4월과 5가 될 것입니다.
And the first sale is going to be 20 on the right side. The same things going to get extended like this.
12:28:13
이번에는 마지막이 4월과 5가 될 것입니다.
And this time, the last one going to be April and five.
12:28:17
이제 나란히 비교해보면 왼쪽에서 작업이 해결되었고 모든 것이 제대로 작동하고 있음을 알 수 있습니다.
So now if you go and compare them side by side, you see that on the left side, the task is solved and everything is working correctly, right?
12:28:23
각 행마다 항상 첫 번째 행의 매출이 있습니다. 첫 번째 행은 1월입니다.
So we have for each row always the sales of the first row. And what is the first row? It is January.
12:28:30
모든 곳에 20이 있습니다. 이것은 맞습니다. 하지만 오른쪽을 확인하면 뭔가 잘못된 것을 볼 수 있습니다.
So we have everywhere a 20, which is correct. But now if you check the right side, you can see there is something wrong. Right.
12:28:35
우리는 마지막 값을 얻고 있지 않습니다. 항상 이전 값을 얻어야 합니다. 여기에는 항상 5가 있어야 합니다.
We are getting not the last value. We should always get a prior rights. We should have here everywhere five.
12:28:42
여기에서 매출과 정확히 동일한 결과가 나옵니다. 이렇게 사용하는 것은 정말 쓸모가 없습니다.
So we have here exactly the same result as the sales. So it's really useless to use it like this. Right.
12:28:47
물론 SQL이 기본 창 프레임 정의를 사용하고 있기 때문입니다.
And that's, of course, because SQL is using the default definition of the window frame.
12:28:51
마지막 값은 모든 창 함수 중에서 기본 프레임 정의를 사용할 수 없는 유일한 함수입니다.
Last value is the only function from all window functions that you cannot use the default frame definition.
12:28:57
프레임 정의를 사용자 정의해야 합니다.
You have to go and customize the frame definition
12:29:01
마지막 값의 효과를 얻기 위해서입니다.
in order to get the effect of the last value for the first value
12:29:04
기본 프레임을 사용하는 경우 모든 것이 작동합니다. 지정하지 않으면
everything is working if you are using a default frame if you are not specifying
12:29:07
마지막 값에 대해서는 효과를 제대로 얻지 못합니다.
anything but for the last value you will not get the effect correctly
12:29:10
프레임 창을 사용자 정의하지 않으면
without customizing the frame window so
12:29:14
친구들, 여러분은 첫 번째 값 함수를 사용할 수 있습니다.
my friends you can go and use the first value function like
12:29:17
프레임을 정의하지 않고 다른 모든 창 함수와 함께 사용할 수 있습니다.
all other window functions without defining a frame you can go
12:29:20
기본값과 함께 사용하면 첫 번째 값의 효과를 얻을 수 있지만
with the default and you will get the effect of the first value but the
12:29:23
마지막 값을 위해서는 프레임을 정의해야 합니다.
last value you have to go and define a frame so let's
12:29:26
그럼 이제 이 문제를 해결하는 방법을 봅시다.
see how we can solve that all right so now in order to solve this we're gonna to define the frame like this it's going to be the rows between the current row and the unbounded
12:29:35
이제 이 문제를 해결하기 위해 프레임을 이렇게 정의할 것입니다.
following so we just switch things around so now
12:29:38
현재 행과 무한대 사이의 행이 될 것입니다.
let's see how this can work now of course it's going to go and sort
12:29:41
따라서 항상 무한대 다음을 가리키게 됩니다.
the data and so on now it's going to have a pointer to
12:29:44
우리 데이터 세트의 마지막 행이 될 것이고, 단계별로 진행됩니다.
the unbounded following so it's going to point always to
12:29:47
첫 번째 행은 이렇게 될 것이고 프레임은 전체가 될 것입니다.
the last row in our data set and then it's going to proceed step by step so the first row is going to be like this and the frame going to be the whole thing right So from the current row until the unbounded following.
12:29:59
마지막 값은 무엇입니까? 마지막 행은
So what is the last value? The last row it's
12:30:02
5가 될 것이며, 4월이므로 출력에서 얻을 수 있습니다.
going to be the five right the april so we will get in the output
12:30:05
이제 다음 값으로 진행합시다
five now let's proceed to the next value the
12:30:08
프레임이 더 짧고 작아질 것입니다
frame going to be shorter and smaller and what is the
12:30:11
마지막 값입니다. 이제 우리는
last value it's going to be as well the five right so now we
12:30:14
다음으로 점프하고 프레임은 이렇게 될 것입니다
jump to the next one and the frame going to be like this
12:30:17
마지막 값입니다. 이제 우리는
what is the last value as well five and then we
12:30:20
이 마지막 값을 얻을 것입니다. 현재 행은 다음과 같습니다
will get the last value like this current row is equal to
12:30:24
무한대의 다음 값으로 우리는 하나의 행만 가지고 있습니다
the unbounded following we have only one row and it's going to be as well five
12:30:27
보시다시피 매우 간단합니다. 프레임을 수정하십시오
so as you can see it's very simple just fix the frame
12:30:30
클로즈를 사용하면 마지막 값이 예상대로 작동합니다
clause and you will get the last value working as expected so
12:30:34
이제 어떻게 진행될지 보여드리겠습니다
this is how is going to go and do it now let's go back to
12:30:37
기술을 익히고 연습을 시작합시다
a skill and start practicing all right so now we have the following task it says
12:30:40
각 제품의 최저 및 최고 판매량을 찾으십시오
find the lowest and highest sales for each product
12:30:44
이제 어떻게 할 수 있는지 봅시다. 보통처럼 시작할 것입니다
so now let's see how we can do this as usual we're going to start
12:30:47
매우 간단한 선택 문으로 시작합니다
with very simple select statements so select order
12:30:50
우리는 제품 ID와
id we need the product id and as
12:30:54
그들의 판매량을 선택할 것입니다
well their sales so let's select the table sales
12:30:57
주문을 선택하십시오. 그게 다입니다
orders so that's it let's go
12:31:00
이제 출력에서 우리의 주문 제품과
and select this now in the output we got our orders product
12:31:04
판매량을 얻었습니다. 이제 작업의 첫 번째 부분을 시작합시다
and sales so now let's start with the first part of the task find the lowest sales for each product so in order to do that we can use the first value function so let's go and do that
12:31:15
첫 번째 값, 우리가 이야기하는 것은
first value then what we are talking about we have to
12:31:18
최소 및 최대 판매량을 가져와야 합니다
give an expression we need the lowest and highest
12:31:21
이제 창을 정의해야 합니다
sales so let's go and have the sales inside it and
12:31:25
각 제품에 대해 창을 만들어야 합니다
now we have to define the window so over since we are
12:31:28
데이터를 제품별로 나누어야 합니다
saying for each product that means we have to go and make windows so
12:31:31
ID로 파티션을 사용하여 데이터를 나누어야 합니다
we have to divide the data using partition by products
12:31:35
id와 함께 데이터를 제품별로 나누어야 합니다.
id and then we must use an order by right so we have to go and sort the data by the sales since the first value should be the lowest value
12:31:45
가장 낮은 매출부터 가장 높은 매출까지 오름차순으로 정렬해야 합니다.
we have to do it as ascending from the lowest sales to the highest sales so we're just gonna leave it like this as a default and we're gonna call it lowest sales
12:31:54
이제 결과를 확인해 보겠습니다.
so let's go and execute this so
12:31:57
제품 ID별로 데이터를 나누고 매출에 따라 정렬합니다.
now let's go and check our results first skill gonna go and partition the
12:32:00
매출의 첫 번째 값은 무엇인가요? 첫 번째 행이죠? 그래서 10이 될 것입니다.
data by the product id so as you can see we got now here four windows then sort the data by the sales so the data are sorted from the lowest to the highest from 10 to 90.
12:32:12
다른 것을 확인해 봅시다. 여기 있는 것을 가져오겠습니다.
So now what is the first value of the sales? It is the first row, right? So it's going to be 10. That's why we have everywhere a 10.
12:32:19
가장 낮은 매출 또는 첫 번째 값은 25입니다.
Let's check another one. Let's take this one here. So this window has two rows and it is sorted.
12:32:25
이로써 각 제품의 가장 낮은 매출을 찾는 첫 번째 부분을 해결했습니다.
The lowest sales or let's say the first value is 25.
12:32:28
각 제품의 가장 높은 매출을 찾아야 합니다.
So with that, we have solved the first part of the task, finding the lowest sales for each product. Let's go to the next one.
12:32:35
마지막 값을 사용해야 합니다. 새로운 줄을 추가합시다.
We have to find out the highest sales for each product. So let's go and use the last value for this. So let's have a new line.
12:32:42
마지막 값을 가질 것입니다. 다시 매출입니다.
We're going to have a last value. Again, the sales. Then we're going to go and define the window.
12:32:50
정확히 같은 창이 될 것입니다.
So it's going to be the exact same window. We have to partition the data by the product ID and order the data by sales.
12:32:55
이전 것을 복사합시다. 지금은 '가장 높은 매출'이라고 부르겠습니다.
So let's go and just copy the previous one. Let's call it for now highest sales.
12:33:03
이제 실행해 보겠습니다.
So let's go and execute it. So now if you check the results, you will see our issue over here again, right?
12:33:08
이 창의 가장 높은 매출을 얻지 못하고 있습니다.
we are not getting the highest sales for this window the
12:33:11
가장 높은 매출은 90이지만, 똑같은 값을 얻고 있습니다.
highest sales is 90 but as you can see we are getting the exact same
12:33:14
이 문제를 해결하기 위해 추가할 것입니다.
sales and we have explained that in the previous example so in order
12:33:18
현재 행과 그 다음 행 사이의 프레임을 추가할 것입니다.
to fix this we're gonna go and add for it the
12:33:21
현재 행 사이의 프레임
frame so rows between current row
12:33:24
그리고 무한히 이어지는
and the unbounded following so
12:33:27
이제 가서
now let's go and
12:33:31
이것을 실행해 보겠습니다. 결과를 확인해 보니, 당신은 여기 있었습니다.
execute this so now let's check the result as you can see you were here
12:33:34
우리는 이 창에서 가장 높은 판매량을 정확히 얻었습니다.
we got the highest sales correctly so for this window
12:33:37
가장 높은 판매량은 90이며, 이 창에서도
the highest one is 90 and as well for this
12:33:40
60 등등으로, 이를 통해 두 가지를 해결했습니다.
window the 60 and so on so with that you have solved both
12:33:43
작업 중 가장 낮은 판매량과 가장 높은 판매량을 해결했습니다.
of the tasks the lowest and the highest sales but now i would
12:33:46
이 작업에 대한 제 솔직한 의견을 보여드리고 싶습니다.
like to show you my honest opinion about this task i
12:33:50
마지막 값을 사용하여 가장 높은 판매량을 찾지 않을 것입니다.
will not go and use the last value to find the highest sales so let me show you how i usually do it i'm gonna go and use the first value in order to find the last value so now let me show you what i mean
12:34:01
새로운 행을 추가해 보겠습니다.
let's go and add a new row i will just take
12:34:05
가장 낮은 판매량의 전체 데이터를 가져올 것입니다.
the whole thing from the lowest sales but what
12:34:08
순서를 변경할 것입니다.
i'm gonna do i'm just gonna go and change the order so that
12:34:11
데이터를 이렇게 오름차순으로 정렬하지 않을 것입니다.
means we will not go and sort the data like this ascending from
12:34:14
가장 낮은 판매량에서 가장 높은 판매량으로 전환할 것입니다.
the lowest sales to the highest sales we're gonna go and switch
12:34:18
가장 높은 판매량에서 가장 낮은 판매량으로 데이터를 판매할 것입니다.
it so we're gonna go and sell the data from the highest
12:34:21
첫 번째 값은 가장 높은 판매량이 될 것입니다.
sales to the lowest sales and with that the
12:34:24
이 값을 가장 높은 판매량으로 이름을 바꿉니다.
first value gonna be the highest sales so let me just
12:34:27
이 값을 가장 높은 판매량으로 이름을 바꿉니다.
rename it highest sales let's
12:34:30
이제 여기에서 정확히 같은 결과를 얻을 수 있습니다.
give it like two so let's go and execute
12:34:33
데이터를 다르게 정렬했기 때문에 같은 결과를 얻습니다.
this and now you can see over here we got the exact same results
12:34:37
첫 번째 값이므로 동일한 효과를 얻을 수 있습니다.
because we sorted the data differently and we get
12:34:40
마지막 값이므로 정의할 필요가 없습니다.
the first value so this is gonna give you the exact same effect like
12:34:43
기본 프레임을 유지하면서 순서를 변경할 수 있습니다.
the last value and as you can see i don't have to define
12:34:46
이 작업을 위해 또 다른 가능성이 있습니다.
now any window or something like that i can stick with the default frame but just twisting the order by so this is how you can do it as well using only the first value.
12:34:57
이 문제를 해결하기 위해 최소값을 사용할 수 있습니다.
So now just for the sake of this task, is as well another possibility
12:35:00
최대 함수도 사용할 수 있습니다.
in how to solve this you can go and use the min
12:35:04
최소 판매량을 위한 새로운 값을 만들 수 있습니다.
max functions so let me just take the same and
12:35:08
최소값을 가져오자고 말할 수 있습니다.
have a new one the lowest sales we can
12:35:11
최소 판매량을 찾아야 합니다.
go and say you know what let's get the min so
12:35:14
아무것도 정렬할 필요가 없습니다.
we are saying find me the minimum sales and
12:35:17
이렇게 나누면 됩니다.
we don't have to go and sort anything so we can go and just divide it
12:35:20
이렇게 하니 다른 ID를 부여합시다.
like this so let's give it another id let's
12:35:24
실행해 보겠습니다. 보시다시피 정확한 결과를 얻었습니다.
go and execute it so as you can see we got the exact
12:35:27
다른 두 개의 최고 판매와 같은 결과입니다.
same results like the other two highest sales so as
12:35:30
이 작업을 세 가지 다른 함수로 해결할 수 있음을 알 수 있습니다.
you can see we can solve this task using three different functions either
12:35:33
마지막 값을 사용하거나 첫 번째 값을 사용할 수 있습니다.
go and use the last value but you have to define the
12:35:36
순서를 바꾸거나 간단히
frame or you can go and use the first value where
12:35:40
최대 함수를 사용하여 최고 판매를 얻을 수 있습니다.
you switch or flip the order by or simply
12:35:43
보시다시피 첫 번째 값과 마지막 값을 사용할 수 있습니다.
just using the max function in order to get the highest sales
12:35:46
극단값을 찾기 위해 이 예제에서
so guys as you can see we can use the first value and the last value
12:35:49
최저 및 최고 판매를 찾기 위해
in order to find out the extremes like here in this example the
12:35:53
이 두 함수와 최소 및 최대 함수 간의 유사성이 있습니다.
lowest and the highest sales so there is like similarity between
12:35:56
이 값으로 무엇을 할 것인지에 대해
those two functions and as well the min and max and of
12:35:59
현재 판매와 비교할 수 있습니다.
course what we're gonna do with this value over here we can go and
12:36:02
현재 판매와 비교하여 차이를 찾는 작업을 확장합니다.
compare it with the current sales so for example we can go and
12:36:05
현재 판매와 최저 판매 간의 차이를 찾습니다.
extend our task where we say find the difference in
12:36:08
그렇게 하려면 모든 것을 정리하겠습니다.
sales between the current and the lowest sales so
12:36:12
첫 번째 값과 최고 값을 유지합시다.
in order to do that let me just clean up all those stuff and
12:36:15
현재 판매를 비교해야 합니다.
let's stick with the first value and the highest value like
12:36:18
이 필드에서 원래 판매와
this so we have to compare now the current sales which
12:36:21
최저 판매와 전체를 비교해야 합니다.
is this field over here the sales the original one with
12:36:25
그렇게 하겠습니다. 새 줄을 만들고
the lowest sales with the whole thing from here so let's
12:36:28
판매에서 최저를 단순히 빼겠습니다.
go and do that so we're gonna have a new line and we're gonna say just
12:36:31
이렇게 하고 이름을 판매 차이로 부여합시다.
simply subtract the sales from the lowest
12:36:34
그래서 그게 전부입니다.
sales so like this and let's give it a name sales
12:36:38
실행해 보겠습니다. 결과를 한 줄로 확인할 수 있습니다.
difference so that's it let's
12:36:41
이제 실행해 보겠습니다. 결과를 한 줄로 볼 수 있습니다.
go and execute it now as you can see in the result in one row
12:36:44
현재 판매량인 90과 비교하고 있습니다.
i'm comparing the current sales which is 90 with
12:36:48
이 제품의 최저 판매량은 10이 될 것입니다.
the lowest sales from this product it's going to be the 10 so
12:36:51
그 사이의 거리를 구할 것입니다.
that we're going to get the distance let's say between those
12:36:55
두 정보 사이의 거리는 80이 될 것입니다.
two informations and it's going to be 80 so now for the next one the distance between this value and the lowest value
12:37:01
그래서 우리는 최저값에 가까워지고 있습니다.
is shorter so we are near the lowest value so
12:37:04
여기서 판매량을 비교할 수 있습니다.
as you can see over here we can now compare the sales between
12:37:08
현재 판매량과 극단적인 값을 비교하여
the current sales and one extreme in order to
12:37:11
두 값 사이의 거리를 찾는 것이 중요합니다.
find the distances between two values so this is
12:37:14
비교를 위한 매우 중요한 분석입니다.
again very important analysis in order to do comparison
12:37:17
이제 값 함수에 대한 간단한 요약을 해보겠습니다.
analysis all right friends so now let's do a quick recap about the value functions or we call them sometimes analytical functions
12:37:28
그들이 하는 일은 다른 행에서 특정 값을 접근할 수 있게 해줍니다.
So what they do, they're going to go and allow you to access a specific value from another row.
12:37:32
복잡한 계산을 간단한 SQL로 수행하는 데 도움이 됩니다.
This can help you in order to do complex calculations with very simple SQL without having you joining tables together or doing self joins.
12:37:41
값 함수에는 네 가지 유형이 있습니다.
And for the value functions, we have four types. Or let's say for functions, the first one allows you to access the previous value like the previous month using the lag function.
12:37:51
다음은 다음 값을 접근할 수 있게 해줍니다.
The next one, it allows you to access the next values the next month using the lead function. Then we have another one.
12:37:58
서브셋에서 첫 번째 값을 접근할 수 있게 해줍니다.
It allows you to access the first value in a subset using the first value function.
12:38:03
구문 규칙으로 넘어가겠습니다.
And another option, we can go and access the last value in a subset using the last value function.
12:38:09
데이터 유형을 사용할 수 있습니다.
Moving on to the next one, we have the rules of the syntax. So about the first point, it is the expressions. We can go and use any data type.
12:38:16
정렬을 위해 order by가 필요합니다.
It could be a number, string, date, anything. Now in order to perform those functions, we have to go and sort the data by the order by.
12:38:23
프레임에서 사용할 수 있습니다.
So order by is required. is a must then
12:38:26
프레임은 항상 비워두는 것이 좋습니다.
for the frame you are allowed to use it so it is an
12:38:29
마지막 값에 대해서만 사용자 정의해야 합니다.
optional thing i would say always leave it empty for the frame but
12:38:32
사용 사례로 넘어가겠습니다.
only for the last value you have to go and customize otherwise it
12:38:36
값 함수의 중요한 사용 사례입니다.
will not work now to the next point we have the use cases we have
12:38:39
데이터 분석에서 시간을 다룰 수 있습니다.
simply very important use cases for the value functions in
12:38:42
데이터 분석에서 가치 함수의 중요한 사용 사례
data analytics so what we can do we can do time
12:38:45
우리가 할 수 있는 것은 시간 시계열 분석입니다.
series analyzes as we learned we can do month over month
12:38:48
우리가 배운 대로 월별 분석을 할 수 있습니다.
analyzes and year over year analyzes those
12:38:51
연간 분석은 고전적이며 항상 첫 번째 질문입니다.
analyzes are classical and it's always the first question and
12:38:54
우리가 성장하고 있는지 측정하기 위한 분석입니다.
that analyzes in order to measure are we growing with
12:38:58
비즈니스가 성장하고 있는지, 성과가 감소하고 있는지
the business or are we declining how the performance between the
12:39:01
현재 연도와 이전 연도 간의 성과를 비교합니다.
current year and the previous year so as you can see we are doing always
12:39:04
고객 행동과 고객 유지 분석을 할 수 있습니다.
comparison using those window functions the next
12:39:07
두 주문 사이의 평균 일수를 계산했습니다.
use case is as well about the time we can do time gap analyzes as we analyzed the customer behavior the customer retention where we have calculated the average days between two orders
12:39:18
마지막 사용 사례는 비교 분석입니다.
and the last use case it's as well about comparison comparison analyzes
12:39:22
현재 값을 비교하기 위해 가치 함수를 사용할 수 있습니다.
we can go and use the value functions in order to compare
12:39:25
현재 판매량을 가장 높은 판매량과 비교합니다.
the current value with extreme like comparing the current
12:39:28
이러한 분석은 데이터 분석에서 필수적입니다.
sales with the highest sales or to the lowest sales
12:39:31
각 회사에서 이러한 질문에 답해야 합니다.
so my friends those analyzes are essential in
12:39:35
SQL 윈도우 함수를 사용하여 쉽게 할 수 있습니다.
data analyzes you will be countering them in each
12:39:38
SQL을 사용하여 데이터를 집계하는 방법을 모두 다뤘습니다.
company in each business you have to answer those questions and you can do that very easily using the sql window functions all right my friends so So that's all about the window value functions.
12:39:48
SQL에서 데이터 분석을 수행하는 데 매우 중요한 도구입니다.
And with that, we have covered everything about how to aggregate your data using SQL.
12:39:53
이 장을 마치고 중급 수준을 다뤘습니다.
And those are very important tools on how to do data analytics in SQL, especially if you are a data scientist and data analyst.
12:40:00
데이터를 필터링하고 결합하는 방법을 배웠습니다.
So with that we are done with this chapter and I can tell you with that we have covered the intermediate level.
12:40:05
이제 세 번째이자 마지막 수준으로 넘어갑니다.
So we have learned how to filter the data, how to combine the data and as well the most important functions in SQL.
12:40:11
첫 번째 수준은 고급 SQL 기술에 관한 것입니다.
Now we're going to go to the third and last level. We will cover now the advanced level.
12:40:15
복잡한 프로젝트를 조직하기 위한 다양한 기술이 있습니다.
So the first level can be about the advanced SQL techniques.
12:40:19
내가 말하고 있는 것이 무엇인지 설명하겠습니다.
So now if you go inside it and in SQL there are like different techniques in order to organize our complex projects.
12:40:25
복잡한 쿼리와 그 필요성에 대해 이야기하겠습니다.
So first I'm going to explain for you what is exactly I'm talking about, what is
12:40:29
첫 번째 주제는 서브쿼리입니다.
complex queries and why we have it and then we can start with
12:40:32
첫 번째 주제인 서브 쿼리로 시작해 보겠습니다.
the first topic the sub queries so let's go normally
12:40:39
프로젝트에서는 데이터베이스가 있고, 그 데이터베이스를 관리하는 사람이 있습니다.
in projects we have a database and we have a person that is
12:40:42
데이터베이스를 책임지는 데이터베이스 관리자입니다.
responsible for the database the database administrator that
12:40:46
데이터베이스 구조를 관리하며, 매우 간단한 시나리오에서는 사용자가 데이터를 검색하기 위해 쿼리를 작성할 수 있습니다.
takes care of the database structure and now in very simple scenario we can have a user that is writing queries in order to retrieve data from the
12:40:54
데이터베이스에서 데이터를 검색하기 위해 SQL 쿼리를 작성하고, 이 쿼리는 데이터베이스로 전송됩니다.
database so he or she gonna write an SQL query and then this query gonna be sent to the database
12:41:00
여기서 쿼리가 실행되고, 데이터베이스는 결과를 반환할 수 있습니다.
where it's gonna execute it and then the database can return the
12:41:03
결과를 통해 사용자는 자신이 작성한 쿼리의 결과를 확인하게 됩니다.
results so at the end our user gonna see the result
12:41:06
이것은 데이터베이스를 사용하는 매우 단순화된 시나리오입니다.
of the query that he wrote so this is a very
12:41:09
하지만 실제 세계에서는 상황이 완전히 다릅니다.
simplified scenario on how we use a database but my friends in the real world things are totally different things in real projects
12:41:18
실제 프로젝트에서는 매우 복잡해질 수 있습니다.
get very complicated like this so for example you
12:41:21
예를 들어, 재무 분석가가 큰 SQL 쿼리 블록을 작성하고 있습니다.
have a financial analyst that is writing a
12:41:25
이 쿼리는 매우 복잡하며, 다른 사용자가 있을 것입니다.
huge block of sql query that is
12:41:28
다른 역할을 가진 사용자, 예를 들어 리스크 관리자가 있습니다.
very complex and there will be like another user that
12:41:31
우리는 매우 복잡한 쿼리를 작성하고 있습니다.
have different role like a risk manager that is as
12:41:34
다양한 부서와 프로젝트에서 여러 작업을 위해 많은 분석가들이 있습니다.
we're writing a very complex query and
12:41:37
많은 복잡한 쿼리를 작성하고 있습니다.
from different departments from different projects for different tasks you will have a lot of analysts that are writing many
12:41:45
모든 분석가와 관리자들은 데이터베이스에 직접 접근할 수 있습니다.
complex queries so all those analysts and managers
12:41:49
그들은 복잡한 분석 쿼리를 실행하고 있습니다.
have a direct access to your database and they are executing
12:41:52
아마도 보고서를 생성하기 위해서입니다.
a complex analytical queries in order to
12:41:55
이 외에도 데이터베이스에서 분석을 수행하는 사람들이 있습니다.
generate maybe a report or something now not only those guys
12:41:58
데이터 엔지니어인 친구도 있습니다.
are doing analysis on your database you will have
12:42:02
그는 데이터 웨어하우스를 구축하고 싶다고 말하고 있습니다.
as well our friend the data engineer that is saying
12:42:05
데이터를 추출하고 싶다고 합니다.
you know what i'm building a data warehouse and i would like to extract
12:42:08
데이터 엔지니어는 데이터를 추출하기 위해 쿼리를 작성할 것입니다.
your data so that data engineer gonna go and write an
12:42:11
데이터베이스에서 데이터를 추출하기 위한 쿼리입니다.
extract query in order to extract the data from the
12:42:14
데이터베이스에서 데이터를 추출하기 위한 쿼리
database and then he has a different script for the transformations
12:42:18
필터 정리 집계를 조작하기 위해
in order to manipulate filter cleanup aggregates
12:42:21
당신의 데이터를 수집하고 변환 결과를
your data and then a third script in order to
12:42:25
다른 데이터베이스인 데이터 웨어하우스에
collect the result of the transformations and load it in
12:42:28
여러 출처에서 데이터를 수집하고 통합하는
another database called data warehouse data warehouse
12:42:32
데이터 분석가가 있으며 쿼리를 작성합니다
is like special database that collect data from different sources and integrate it in one place in order to do analytics and reporting and now at the end of this chain you will have
12:42:42
데이터 웨어하우스의 데이터를 분석하기 위해
a data analyst and she writes as well queries in
12:42:45
데이터를 준비하기 위한 다른 쿼리가 있을 수 있습니다
order to analyze the data in the data warehouse or you might
12:42:48
파워 BI와 같은 도구에 삽입하기 전에
have a different query in order to prepare the data before
12:42:51
시각화 및 보고서를 생성하기 위해
inserting it to a tool like power bi in
12:42:55
우리는 이것을 데이터 웨어하우스 시스템 또는 비즈니스 인텔리전스
order to generate visualizations and reports so
12:42:58
시스템이라고 부릅니다. 데이터에서 추출하고 조작합니다
we call this a data warehouse system or a business intelligence
12:43:01
데이터를 분석가를 위해 변환합니다. 이제 데이터 엔지니어와 데이터 분석가가
system that extract and extract away from your data and manipulate
12:43:05
데이터베이스에 접근하고 쿼리를 수행합니다.
it and transform it for analyzers now not only we have a data engineer and data analyst
12:43:10
우리의 친구 데이터 과학자도 있습니다. 이제 데이터 과학자는
accessing your database and doing queries we have as
12:43:13
데이터베이스에 직접 접근할 수 있습니다.
well our friend the data scientist so now our data scientist
12:43:16
그는 데이터를 추출하기 위해 다양한 쿼리를 작성할 수 있습니다
as well has a direct access to your database so
12:43:20
필요한 데이터를 조작하기 위해
he might write like different queries in order to extract the
12:43:23
모델을 개발하고 머신러닝을 수행하기 위해
data and as well to manipulate the data that are needed in
12:43:26
AI와 함께 많은 프로젝트에서 볼 수 있는 시나리오입니다.
order to develop a model and doing machine learning
12:43:29
데이터 분석가의 결과가 사용될 곳입니다.
and ai and now one more scenario that i see in many projects
12:43:32
결과를 준비하기 위한 다른 쿼리에서
where the result of the data analyst is going to be used
12:43:35
시각화 파워 BI 또는 내보내기 위해
in another query in order to prepare the results for data
12:43:39
엑셀 목록처럼, 우리는 많은 사람들이
visualizations power bi or in order to export
12:43:42
데이터베이스에 접근하고 싶어하는 다양한 역할을 가지고 있습니다.
like excel list so as you can see we have a lot of people
12:43:45
다양한 역할을 가진 사람들이 귀하의 데이터베이스에 접근하고 싶어합니다.
with different roles that want to access your database
12:43:48
모두가 데이터에 기반하여 질문에 답하고 싶어하기 때문입니다.
and do analyzes on top of it and that's because
12:43:51
이것을 보면 여전히 이것이 단순화된 버전이라고 생각합니다.
everyone wants to answer questions based on the data
12:43:54
그리고 이제 이것을 보면 여전히 이것이 단순화된 버전이라고 생각합니다.
and now if i look to this i still think this is a simplified
12:43:57
데이터 프로젝트에서의 작동 방식과 실제 프로젝트에서는 이보다 훨씬 더 복잡하다는 것을 말씀드릴 수 있습니다. 이제 뒤로 물러서서 이것을 보면 많은 도전과 문제를 발견할 것입니다.
version and how things works in the data projects and i can tell you a real project things are way more complicated than this so now So now if you sit back and look to this, we will find many challenges and problems.
12:44:10
예를 들어, 모든 사람들이 서로 이야기하지 않고 각자 자신의 쿼리를 생성하고 있습니다.
For example, all those people are not talking to each other and each one of them are creating like their own query.
12:44:16
하지만 모든 쿼리를 가져와서 나란히 비교하면 반복되는 논리를 가진 스크립트와 쿼리를 발견할 수 있습니다.
But if you go and take all those queries and compare them side by side, you will find in the scripts and queries logic that is keep repeating.
12:44:24
따라서 분석가, 데이터 과학자 및 데이터 엔지니어의 쿼리에는 중복된 논리가 포함될 수 있습니다.
So the queries from the analyst or the data scientists and data engineers, they might contain a redundant logic.
12:44:32
물론 이 문제는 동일한 노력이 반복되고 있다는 것입니다.
And of course, the issue of this, we have the same effort repeating over and over.
12:44:37
그리고 아마도 모든 사람이 SQL에서 올바른 기술을 가지고 있지 않기 때문에 논리를 올바르게 구현하지 못하고 있습니다.
And maybe not everyone is getting the logic implemented correctly because not all of them having the right skills in SQL.
12:44:44
그래서 이것은 이 설정에서 큰 문제입니다. 그리고 이제 이 시나리오에서 또 다른 도전이 있습니다.
So this is a big issue in this setup. And now we have another challenge having this scenario.
12:44:49
최적화하지 않으면 모든 곳에서 성능 문제가 발생할 것입니다.
If you don't optimize it, you will have a performance issue everywhere.
12:44:53
따라서 데이터 웨어하우스나 데이터 엔지니어 스크립트는 5시간 정도 걸릴 수 있습니다.
So the data warehouse or the data engineer scripts might take like five hours.
12:44:57
그리고 분석가의 쿼리는 40분 정도 걸릴 수 있습니다.
And the query from the analyst might take like 40
12:45:01
데이터를 보고서에 삽입하기 전에 30분에서 1시간 정도 걸릴 수 있습니다.
minutes and before inserting the data to reports we might
12:45:04
그리고 다른 모든 사람들도 나쁜 성능으로 고통받고 있습니다.
have 30 minutes and one hour there 30 minutes there
12:45:07
그들의 쿼리에서 성능이 정말 나쁩니다.
and everyone else is as well suffering from bad performance
12:45:10
모든 곳에서 성능이 정말 나쁩니다.
on their queries and the performance everywhere is
12:45:13
그래서 모든 사람이 복잡한 대형 쿼리를 작성하고 있다면
really bad so if everyone is writing big complex queries
12:45:16
지금 좋은 성능을 기대하지 마세요.
don't expect that they will have a good performance now
12:45:19
제가 많은 프로젝트에서 관찰한 세 번째 도전은
to the third challenge that i observed in many projects and
12:45:22
원래 데이터베이스 뒤에 있는 복잡성입니다.
that is the complexity now behind the original database
12:45:25
하나의 애플리케이션에만 최적화된 데이터 모델이 있을 수 있습니다.
you might have a data model that is prepared and
12:45:28
그래서 데이터 모델에는 많은 테이블이 있고 모든 테이블은 서로 다른 관계를 가지고 있습니다.
optimized only for one application so you will have in the data
12:45:31
그들 사이의 관계는 개발자와 전문가만 알고 있습니다.
model a lot of tables and all those tables have different relationship
12:45:35
그들 사이의 관계와 물론 개발자와 전문가만이
between them and of course only the developers and the experts
12:45:38
이 데이터베이스의 물리적 데이터 모델을 이해합니다.
of this database understand the physical data model
12:45:41
이 데이터베이스 뒤에 있으며, 모든 분석가에게 접근을 허용하면 많은 질문이 생길 것입니다.
behind this database and now if you give access to all those analysts they will have a lot of questions because first they They have to understand the data model before writing any query.
12:45:53
즉, 많은 데이터 작업자들이 이 데이터베이스의 전문가들에게 질문을 계속하고 있다는 뜻입니다.
So that means a lot of data workers are keep asking our experts from this database questions.
12:45:59
예를 들어, 테이블 A와 테이블 B를 어떻게 연결하나요? 내 열은 어디에서 찾을 수 있나요? 이 테이블은 무엇을 의미하나요?
So for example, how to connect the table A with the table B? And where do I find my columns? What this table means?
12:46:04
쿼리에서 나쁜 결과를 얻고 있습니다. 데이터가 정말로 손상되었습니다.
I'm getting bad results in my query because your data is really corrupt.
12:46:09
따라서 데이터베이스 개발자들은 분석가들로부터 많은 질문을 받을 것입니다.
So the developers of the database will get a lot of questions from the analysts.
12:46:13
그리고 그들은 그들의 데이터 모델을 계속해서 설명해야 합니다.
and they have to explain over and over their data model
12:46:16
사용자들이 복잡한 쿼리를 작성할 수 있도록 하기 위해서입니다.
so that the users are able to write those
12:46:19
모든 사용자들이 많은 질문으로 데이터베이스 팀을 스트레스 받고 있습니다.
complex queries so that means all those users are stressing
12:46:22
사용자들이 매우 복잡한 쿼리를 작성하고 있습니다.
the database team by many questions and as well
12:46:25
복잡성은 이제 정말 큰 도전입니다.
the users are writing very complex queries so
12:46:29
이 그림을 보면 데이터베이스에서 많은 화살표를 찾을 수 있으며, 이는 많은 데이터베이스 스트레스를 유발할 수 있습니다.
the complexity is a really big challenge now as well by
12:46:32
복잡한 쿼리는 정말 큰 스트레스를 유발할 수 있습니다.
looking to this picture you will find a lot of arrows from those squares the database and this might cause a lot of database stress so keep executing repeatedly
12:46:42
데이터베이스에 큰 스트레스를 주고 데이터베이스를 다운시킬 것입니다.
a big complex queries can makes really big
12:46:45
이 그림의 마지막 도전은 데이터 보안입니다.
stress for the database and it's gonna bring the database down
12:46:49
사용자에게 직접 데이터베이스 테이블에 접근을 허용하면 안 됩니다.
and the last challenge of this picture is that the data
12:46:52
데이터베이스 테이블에 직접 접근할 수 있습니다.
security so if you leave it like this by giving the users
12:46:55
문제가 발생할 수 있습니다. 일부 데이터에 대해서는 괜찮을 수 있지만,
a direct access to your database tables you
12:46:58
각 데이터 분석가에게 데이터베이스 테이블에 대한 전체 접근을 허용하고 싶지 않습니다.
might have a problem because it might be okay for like some data
12:47:01
따라서 모든 사람이 물리적 데이터베이스 테이블에 직접 접근할 수 있도록 두어서는 안 됩니다.
engineers and so on but you don't want to give for each data analyst a full access to the database tables so you have to protect your tables the columns the the rows, everything.
12:47:11
이제 도전, 문제 및 이슈에 대한 이야기는 충분합니다.
So you cannot leave it like this where everyone having a direct access to the physical database tables.
12:47:17
물론 많은 해결책이 있지만, 지금은 다섯 가지 기술에 집중하겠습니다.
Now enough talking about challenges, problems, and issues. Let's be solution oriented. So what are the solutions of those issues?
12:47:24
서브 쿼리나 CTE, 공통 테이블 표현식을 사용할 수 있습니다.
Of course, there are many solutions, but we're going to focus now on five techniques.
12:47:28
데이터베이스에 뷰를 도입하거나 임시 테이블을 사용할 수 있습니다.
We can go and use sub queries or CTEs, comment table expressions.
12:47:32
우리는 데이터베이스에 뷰를 도입하거나 임시
We can introduce views to our database or temporary
12:47:36
테이블을 사용하거나 CTAS 기법을 사용할 수 있습니다.
tables or we can go and use the technique of the ctas
12:47:40
그래서 이것이 우리가 데이터 프로젝트에서 직면할 수 있는 모든 문제를 해결하기 위해 이 다섯 가지 기술을 이해해야 하는 이유입니다.
carrier table as select so this is exactly why we have to understand those five techniques in order to solve all those issues that we might face in our data projects
12:47:54
좋아요, 친구들. 이제 우리는
all right friends so now after we understood the importance of
12:47:57
이 다섯 가지 기술의 중요성을 이해했으니 데이터베이스 아키텍처를 간단히 살펴보겠습니다.
those five techniques let's take a quick and simplified look to the database architecture because i want you to
12:48:04
무슨 일이 일어나는지 이해하고 싶습니다.
understand what happens behind the scenes and how the database execute the queries from these five techniques.
12:48:11
서버 측과 클라이언트 측이 있습니다. 클라이언트 측에서는 예를 들어, 특정 목적을 위해 SQL 쿼리를 작성하고 있습니다.
So by understanding this architecture, you will understand how things works. So let's go. For each story, there are two sides.
12:48:18
이제 서버 측에서는 많은 것들이 있습니다. 서버는 데이터베이스가 있는 곳이며 데이터베이스 엔진과 같은 많은 구성 요소가 있습니다.
We have the server side and the client side. In the client side, it's like for example, you, you are writing an SQL query for a specific purpose.
12:48:27
데이터베이스 엔진은 데이터베이스의 두뇌로, 데이터 저장, 검색 및 관리와 같은 다양한 작업을 처리합니다.
Now in the server side, we have many things. So the server is where the database lives and it has many components like the database engine.
12:48:35
쿼리를 실행할 때마다 데이터베이스 엔진이 이를 처리합니다.
The database engine is the brain of the database that handles different operations like storing, retrieving, and managing data in the database.
12:48:45
그리고 이제 데이터베이스에는 매우 중요한 구성 요소인 저장소가 있습니다.
So each time you execute a query, the database engine is going to take care of it.
12:48:49
데이터베이스에는 두 가지 주요 저장소 유형이 있습니다: 디스크 저장소와 캐시입니다.
And now in the database, we have a very important component that is the storage.
12:48:54
디스크 저장소는 데이터가 영구적으로 저장되는 장기 메모리와 같습니다.
And the two main types of storage in a database are disk storage and cache.
12:48:59
그래서 당신의 PC의 디스크처럼, 시스템을 끄더라도 데이터를 영구적으로 저장합니다.
The disk storage is like a long-term memory where the data is stored permanently.
12:49:04
디스크의 중요한 기능 중 하나는 많은 데이터를 저장할 수 있다는 것입니다.
So it's like the disk at your PC, it stores the data permanently, even if you turn off the system.
12:49:10
하지만 디스크 저장소의 단점은 느리다는 것입니다. 쓰기와 읽기가 느립니다.
And one important feature of the disk is that it can store a lot of data.
12:49:15
이제 반면에 캐시는 데이터가 임시로 저장되는 단기 메모리입니다.
But the disadvantage of the disk storage is that it is slow. So it is slow to write and to read.
12:49:21
당신의 PC의 RAM처럼, 가장 자주 사용되는 데이터를 보유합니다.
Now, in the other hand, we have the cache is a short term memory where the data is stored temporarily.
12:49:26
그래서 데이터베이스는 데이터를 검색하기 위해 빠르게 접근할 수 있으며 캐시의 큰 장점은 빠르다는 것입니다.
It's like the RAM at your PC, it holds the most frequently used data.
12:49:31
그래서 디스크에 비해 데이터베이스가 캐시에서 데이터를 검색하는 것은 매우 빠릅니다.
So the database can access it quickly in order to retrieve data and the big advantage of the cache is that it is fast.
12:49:38
하지만 캐시의 단점은 데이터가 짧은 기간 동안만 저장된다는 것입니다.
So it is very fast for the database to retrieve data from the cache compared to the disk.
12:49:42
그래서 속도와 얼마나 많은 데이터를 저장할 수 있는지, 그리고 얼마나 오래 저장할 수 있는지 간의 균형입니다. 이제 디스크 저장소에 대해 이야기해 보겠습니다.
But the disadvantage of the cache, the data is stored there only for short period.
12:49:47
데이터베이스에서 매우 중요합니다. 일반적으로 세 가지 유형의 저장소 영역이 있습니다: 사용자 데이터, 시스템 카탈로그, 임시 데이터입니다.
So it's like trade-off between the speed and how much data you can store and how long. Now let's talk about the disk storage.
12:49:54
각 저장소 유형은 다른 목적을 가지고 있습니다. 사용자 데이터 저장소는 무엇인가요? 데이터베이스의 주요 내용입니다.
This is very important in databases. There are typically three types of storage areas there we have the user data, the system catalog, and the temporary data.
12:50:04
그래서 사용자와 관련된 모든 정보를 저장합니다.
And each storage type has a different purpose. So what is user data storage? It is the main content of the database.
12:50:11
그래서 실제 데이터를 저장합니다. 사용자와 관련된 모든 정보입니다.
So it stores the actual data, all the informations that are relevant for the users.
12:50:17
그래서 사용자들이 중요하게 생각하는 모든 데이터를 저장합니다. 이것은 사용자들이 항상 상호작용하는 저장소입니다.
So it stores there all the important data that the users cares about. So this is the storage where the users are interacting all the time.
12:50:24
그럼 사용자 데이터를 어디서 찾을 수 있을까요? 우리의 데이터베이스 SalesDB로 가서 테이블로 이동하면 됩니다.
So where do we find the user data? If you go to our database, SalesDB, and then you go to the tables.
12:50:30
이제 우리가 이미 사용했던 모든 테이블을 찾습니다. 고객, 직원, 주문 등입니다.
Now we find all these tables that we are already used. The customers, employees, orders, and so on.
12:50:35
그 테이블들이 사용자 데이터입니다. 이제 sales orders에서 선택하겠습니다.
Those tables are the user data. So now if I go and say select from sales orders.
12:50:43
지금 보고 있는 모든 정보는 사용자의 데이터입니다. 이것이 우리가 실제로 중요하게 생각하는 것입니다.
And all those informations that we are seeing now are the user's data. So this is what we users actually care about.
12:50:50
데이터베이스 내부에서 보는 다른 모든 것들은 우리가 신경 쓰지 않습니다. 우리는 오직 우리의 데이터만 신경 씁니다.
All other stuff that we see inside databases as a user, we don't care about it. We care only about our data.
12:50:56
하지만 데이터베이스에는 사용자 데이터만 있는 것이 아닙니다. 다른 많은 정보가 있습니다.
But in the database, we don't have only the user data. We have many other informations.
12:51:01
이것이 우리가 사용자 데이터 저장소라고 부르는 것입니다. 이제 Steam 카탈로그는 무엇인가요?
So this is what we mean with the user data storage. Now, what is the Steam Catalog?
12:51:10
이것은 데이터베이스의 내부 저장소로, 자체 정보를 위한 것입니다.
This is the internal storage for the database for its own information.
12:51:15
즉, 데이터베이스 자체에 대한 모든 것을 추적하는 청사진과 같습니다.
So it's like a blueprint that keeps tracking everything about the database itself.
12:51:21
즉, 시스템 카탈로그의 주요 목적은 데이터베이스에 대한 메타데이터 정보를 보유하는 것입니다.
So that means the main purpose of the system catalog is that it holds the metadata information about the database.
12:51:28
메타데이터란 무엇인가요? 메타데이터는 데이터에 대한 데이터입니다. 이제 이것이 의미하는 바를 이해해 봅시다.
So what is a metadata? Metadata is data about data. Now let's understand what this means.
12:51:35
지금까지 우리가 한 것은 고객이라는 테이블을 생성한 것입니다.
What we have done so far is that we have created a table called customers.
12:51:38
그리고 우리는 고객 ID, 이름, 성과 같은 여러 열을 정의했습니다.
And we have defined inside it like multiple columns like the customer ID, first name, last name.
12:51:43
그리고 우리는 이 테이블에 우리의 데이터를 삽입했습니다.
and then we have inserted our data inside this table so
12:51:46
우리는 다섯 명의 고객을 삽입했으므로 이 정보는 내가 생성한 데이터입니다.
we have inserted five customers so those informations are my data i have created those informations and stored it inside the database
12:51:54
그래서 우리는 이것을 사용자 데이터라고 부릅니다.
that's why we call it the user data so
12:51:58
지금까지는 새로운 것이 없습니다. 이제 무대 뒤에서 무슨 일이 일어나는지 봅시다.
nothing so far is new so now what happens behind the scenes
12:52:01
데이터베이스 서버는 제공한 사용자 데이터만 저장하는 것이 아니라, 데이터베이스에 다른 유형의 데이터도 저장합니다.
is that the database server will not only store the user data that you have provided but also it's gonna go and store a different type of data inside the database and this data is
12:52:12
그 데이터는 메타데이터입니다. 데이터베이스 서버는
the metadata so the database server gonna store the
12:52:15
고객 테이블의 메타데이터를 저장합니다.
metadata of the customers table and it
12:52:19
이것은 테이블 이름과 같은 형태일 수 있습니다.
can look like this there is like a table name there is a
12:52:22
열 이름이 있으며, 이는 데이터베이스에 정의한 열 이름입니다.
column names and those are the column names that you
12:52:25
당신이 데이터베이스에 정의한 열 이름입니다.
have defined inside your database and those are
12:52:28
당신이 정의한 열 이름은
the column names that you have defined as
12:52:31
고객 테이블을 생성하고 있으며, 추가 정보를 저장할 수 있습니다
you are creating the table customers and it can store as well
12:52:34
어떤 데이터 유형인지에 대한 추가 정보
additional informations like which data type like
12:52:37
고객 ID는 정수형이고 성은 문자열입니다
the customer id is int and the last name is varcharts
12:52:40
열의 길이와 같은 많은 다른 정보
and many other information like the length of the column
12:52:43
열이 널 허용인지 여부
and whether the column is nullable or not
12:52:46
메타데이터에서 우리는
so as you can see in the metadata we are having a
12:52:49
고객의 구조에 대한 설명 데이터
description a data about the structure of
12:52:52
테이블과 열뿐만 아니라 많은 정보를 찾을 수 있습니다
the customers and in the metadata we can find a lot of
12:52:55
스키마와 데이터베이스에 대한 정보도 포함되어 있습니다
information about not only the tables and columns but
12:52:58
기본 테이블인 고객 테이블은 데이터를 포함합니다
as well about the schemas and the database so you can find a full catalog about the structure of your database
12:53:05
실제 데이터에 대한 정보
basic table the customers table it contains data
12:53:09
고객에 대한 데이터를 저장합니다
about the actual data so it stores data about
12:53:12
고객 테이블의 메타데이터는 데이터에 대한 데이터를 포함합니다
the customers but the metadata of the customers table
12:53:15
데이터에 대한 데이터를 포함합니다
contains data about data so
12:53:18
데이터를 저장하기 위해 사용하는 각 테이블은
in the databases each table that you are using in order to
12:53:21
데이터의 구조를 설명하는 테이블 쌍이 있습니다
store your data has a table twin that describes
12:53:25
시스템 카탈로그 또는 메타데이터를 의미합니다
the structure of your data so this is what we mean with a system catalog or a metadata and now you might
12:53:31
모든 시스템 카탈로그와 메타데이터를 찾을 수 있는 곳
ask where I can find all those system catalog and metadata inside
12:53:35
여기서 클라이언트는 정보를 탐색할 수 없습니다
our client here well you cannot navigate through those informations
12:53:38
객체 탐색기에서 사용자처럼
in the object explorer like we used to do for the user
12:53:42
특별한 정보를 찾을 수 있습니다
data but you can find those informations in a special
12:53:45
정보 스키마라는 숨겨진 스키마
hidden schema called the information schema
12:53:48
SQL 서버의 정보 스키마는 시스템 정의된 스키마입니다
the information schema in SQL server is a system defined schema that contains a set of built-in
12:53:56
우리의 데이터베이스에 대한 정보를 찾는 데 도움이 되는 뷰
views that help us to find information about our
12:53:59
데이터베이스의 테이블, 열 및 기타
database like tables columns and other
12:54:02
객체를 탐색해 보겠습니다. 이제
objects so let's go and explore it we're gonna go and
12:54:05
정보를 선택하겠습니다.
say select star from information
12:54:09
스키마를 확인하고 점을 찍겠습니다.
schema and then let's have a dot and
12:54:12
이제 SQL에서 모든 뷰의 목록을 가져옵니다.
now we get from sql a list of all views that are
12:54:15
메타데이터를 탐색하기 위해 사용 가능한 모든 뷰를
available in order to browse the metadata of our database so for example you can see here tables you can see information about the
12:54:23
열을 선택하고 실행해 보겠습니다.
views and as well about the columns so
12:54:26
이제 출력에서 스키마에 대한 정보를 찾을 수 있습니다.
let's go and select the columns and let's go and execute
12:54:29
예를 들어 테이블 이름에 대한 정보입니다.
it and now in the output we can find informations about the schema
12:54:33
여기 고객이 있습니다. 이걸 선택해 보겠습니다.
about the table names like for example
12:54:36
테이블을 찾고 이 안에 있는 모든 열을
here the customers let me just go and select this
12:54:39
정렬된 순서와 각 열의 데이터 유형 및 크기를 확인합니다.
table and then we find all the columns inside this
12:54:42
이 테이블의 모든 정보와 메타데이터를 확인할 수 있습니다.
table how they are sorted so we have here the order of each column and as well the data type and the size of each column and many other stuff.
12:54:52
이 테이블의 모든 정보와 메타데이터를 확인할 수 있습니다.
So as you can see, we got here all the information, all the metadata of each table and as well for each column inside the table.
12:55:02
그래서 데이터베이스에서 어떤 테이블이 존재하는지 확인할 수 있습니다.
So with that, you can check which tables does exist in your database. For example, I find here like something called test two.
12:55:07
그래서 아마도 무언가를 테스트하려고 했던 것 같습니다.
So maybe I was trying to test something. I can go now and clean up stuff, right?
12:55:12
그래서 데이터베이스가 이러한 카탈로그를 유지하는 이유입니다.
And this is exactly why the database maintain such a catalog.
12:55:15
각 테이블과 열의 구조를 빠르게 찾는 데 도움이 됩니다.
It helps the database to quickly find the structure of each table and of each column and it helps me as well as user to browse the catalog of the database.
12:55:24
그래서 여기서 고유한 테이블 이름을 가져오겠습니다.
So for example, I can go over here and say, okay, let's get a distinct table name.
12:55:31
데이터베이스 안에 있는 모든 목록을 가져올 수 있습니다.
So with that, I will get a list of everything that I have inside the database.
12:55:35
고객, 직원 및 그들이 수행한 몇 가지 테스트가 있습니다.
So we have the customers, employees, and some tests that they have done. So metadata are awesome.
12:55:45
이제 세 번째 저장소인 임시 데이터 저장소로 넘어갑니다.
Now we come to the third storage, the temporary data storage.
12:55:48
쿼리 처리나 데이터 정렬과 같은 단기 작업에 사용되는 임시 공간입니다.
It is a temporary space used by the database for short term tasks like processing a query or sorting data.
12:55:55
이 작업이 완료되면 어떻게 될까요?
And once these tasks are done, what's going to happen? The database is going to go and clean up the storage.
12:56:00
임시 저장소를 사용하는 임시 테이블을 어디서 찾을 수 있을까요?
And now, of course, the question is where we can find these temporary tables that is using the temporary storage in the disk.
12:56:06
실제로, 객체 탐색기로 가면 SalesDB 데이터베이스 안에서는 찾을 수 없지만 시스템 데이터베이스 안에서는 찾을 수 있습니다.
Well, actually, if you go to the Object Explorer, you will not find it inside our database SalesDB, but you will find it inside the system databases.
12:56:16
이제 로컬에서 작업하고 있으므로 SQL 서버 내부의 모든 것에 완전한 접근 권한이 있습니다.
Now, since we are working locally, we have the full access to everything inside the SQL server.
12:56:21
하지만 실제 프로젝트에서는 사용자가 되거나 개발자라고 가정하면 시스템 데이터베이스에 접근할 수 없습니다. 오직 데이터베이스 관리자만 가능합니다.
But in real projects, if you are just a user or let's say a developer, you will not have access to the system databases only for the database administrators.
12:56:30
하지만 이제 우리는 로컬 복사본에서 작업하고 있습니다. 그러니 시스템 데이터베이스로 가봅시다.
But now we are working on the local copy. So let's go to the system database.
12:56:34
여기 SQL 서버에서 tempdb라는 특별한 데이터베이스가 있습니다.
And here you have a special database from the SQL server called tempdb.
12:56:39
그 안으로 들어가면 테이블과 임시 테이블을 찾을 수 있습니다.
And if you go inside it, we will find here tables and temporary tables.
12:56:43
그래서 여기에서 생성하는 모든 임시 테이블을 찾을 수 있습니다.
So this is exactly where you can find all the temporal tables that you are generating.
12:56:48
현재 우리는 어떤 임시 테이블도 생성하지 않았습니다. 그래서 비어 있습니다.
Now, currently, we didn't create any temporary tables. That's why it's empty.
12:56:52
하지만 임시 테이블을 생성하기 시작하면 이 폴더 아래에서 해당 테이블을 찾을 수 있습니다.
But once we start creating temporary tables, you will find those tables underneath this folder.
12:56:58
다음 섹션에서 임시 테이블에 대해 배울 것입니다.
We will learn about the temporary tables in the next sections.
12:57:05
이것들은 데이터베이스 아키텍처의 주요 구성 요소입니다. 이제 예제를 살펴봅시다.
So these are the main component of the database architecture. So now let's have an example.
12:57:10
이제 사용자 저장소에 저장된 orders라는 테이블이 있고 이 테이블의 메타데이터는 카탈로그에 저장되어 있습니다.
Now we have a table called orders that is stored inside the user storage and the metadata of this table is stored in the catalog.
12:57:17
이제 클라이언트 측에 있다고 가정하고 주문 데이터를 선택하기 위해 간단한 선택 쿼리를 작성합니다.
So now let's say that you are at the client side and you write a simple select query in order to select the data of the orders.
12:57:23
이제 그 쿼리가 서버로 전송되어 실행되고 데이터베이스 엔진이 쿼리를 처리할 것입니다.
So now that query is sent to the server in order to be executed and the database engine is going to take the query in order to process it.
12:57:30
먼저 데이터베이스 엔진은 캐시에 데이터가 있는지 확인할 것입니다.
So first the database engine is going to check whether we have the data in the cache.
12:57:33
데이터가 캐시에 저장되어 있다면 모든 것이 매우 빨라지고 데이터베이스 엔진이 작업을 빠르게 해결할 수 있습니다.
Because if the data is stored in the cache then things are going to be really fast and the database engine can solve the task quickly.
12:57:40
하지만 이 시나리오에서는 캐시에 주문 정보가 없습니다. 그래서 데이터베이스 엔진은 캐시에 없다고 말할 수 있습니다.
But in this scenario, we don't have the orders information in the cache. That's why the database engine can say, OK, it's not in the cache.
12:57:47
디스크를 확인해 봅시다. 그래서 디스크에서 주문 정보를 찾고 쿼리를 실행할 수 있습니다.
Let's check the disk. So it will find the orders information in the disk and the query can be executed.
12:57:52
그런 다음 이 쿼리의 결과를 클라이언트 측으로 다시 보낼 수 있습니다.
Then the result of this query can be sent back to the client side.
12:57:56
결국 출력에서 주문 테이블의 결과를 보게 될 것입니다.
Where at the end, in return, you will see in the output the result of the table orders.
12:58:01
이것이 SQL 데이터베이스가 아주 간단한 선택 쿼리를 실행하는 방법입니다.
So this is how the SQL database execute a very simple select query.
12:58:10
쿼리는 다른 쿼리 안의 쿼리입니다. 이것이 무슨 뜻일까요? 이해하기 위해 스케치를 해봅시다.
The query is a query inside another query. So what this means? Let's have a sketch to understand it.
12:58:17
지금까지 배운 것처럼 주문, 고객 등 다양한 데이터베이스 테이블이 있습니다.
So so far what we have learned, we have different database tables like the orders, customers, and so on.
12:58:22
그리고 우리는 select from where와 같은 간단한 SQL 쿼리를 작성합니다. SQL은 데이터베이스 테이블에서 데이터를 검색합니다.
And we write a simple SQL queries like select from where. So the SQL gonna retrieve data from the database tables.
12:58:29
출력에서는 어떤 종류의 결과를 얻게 될 것입니다. 지금까지 우리가 한 것은 매우 간단한 쿼리입니다.
And in the output, we will get some kind of results. So this is so far what we have done. We have done very simple queries.
12:58:35
이제 우리의 쿼리에서 조금 다른 것을 가질 수 있습니다. 그래서 우리는 쿼리 안에 또 다른 쿼리를 가질 수 있습니다.
Now in our query, we can have things a little bit different. So we could have another query that is inside our query where we do the same things like select from where.
12:58:45
우리는 이제 쿼리 안에 쿼리가 있고, 이를 임베디드 쿼리라고 부릅니다.
So we have now a query inside our query and we call this embedded query.
12:58:49
우리는 이를 서브 쿼리라고 부르며, 원래 쿼리, 즉 선택에서 가져오는 첫 번째 쿼리를 메인 쿼리라고 부릅니다.
We call it a sub query and the original query, the first one where we have select from, we call it main query.
12:58:56
전체 쿼리를 실행하면, 먼저 서브 쿼리를 선택한 다음 실행하게 됩니다.
So if you execute the whole query, what can happen is first going to go and select the sub query and then it's going to execute it.
12:59:01
따라서 데이터베이스 테이블에서 데이터를 선택하고 검색하게 됩니다.
So it's going to go and select and retrieve data from our database tables.
12:59:06
서브 쿼리의 결과는 사용자에게 전송되지 않습니다.
and the result of the sub query will not be sent to the users
12:59:09
그래서 우리는 그것을 볼 수 없고 결과가 어떻게 될지 알 수 없습니다.
to us so we cannot see it what can happen the result
12:59:12
결과는 쿼리 안에 중간으로 남아 있을 수 있습니다.
can stay inside the query as an intermediate
12:59:15
그런 다음 이제 우리의 메인 쿼리가 이 중간 결과와 상호작용을 시작할 수 있습니다.
results and then now our main query can
12:59:19
서브 쿼리에서 이 중간 결과와 상호작용을 시작할 수 있습니다.
go and start interacting with this intermediate result from
12:59:22
서브 쿼리에서 이 중간 결과 위에서 어떤 작업을 수행하게 됩니다.
the sub query so the main query gonna do some kind of operations
12:59:26
이 중간 결과 위에서 필터링이나 조인 등의 작업을 수행할 수 있습니다.
on top of this intermediate results and use it for filtering or
12:59:29
그래서 이제 메인 쿼리는 데이터의 두 가지 출처를 가지고 있습니다.
joining or any purpose and still the main query can
12:59:32
서브 쿼리는 메인 쿼리 안에 있는 쿼리이며, 지원자의 역할을 합니다.
go and query the original database tables so So now the main query has two sources for data, the original database tables and as well the result from another query.
12:59:42
그래서 서브 쿼리는 메인 쿼리를 데이터로 지원하며, 메인 쿼리의 주요 작업은 모든 데이터를 가져와서 최종적으로 파일을 보여주는 것입니다.
So now by looking to this, you can see the sub query is a query inside the main query and it's play a role of supporter.
12:59:50
이제 중간 결과에 대해 두 가지 사항이 있습니다.
So it supports the main query with data and the main job of the main queries, of course, to get all those data and to show us at the end the file.
13:00:00
서브 쿼리에서 얻은 결과에 대한 두 가지 사항이 있습니다.
results now there is now two things about this intermediate
13:00:03
쿼리 실행이 완전히 완료되면,
results that we got as a result from the sub query once
13:00:06
우리는 이 중간 결과를 파괴할 것입니다.
the execution of the query is completely done what
13:00:09
그래서 완전히 삭제되어 더 이상 찾을 수 없게 됩니다.
can happen is we're gonna go and destroy this intermediate
13:00:13
이제 중간 결과에 대한 다른 사항은 첫 번째 쿼리와 완전히 외부에 있는 또 다른 쿼리를 만드는 것입니다.
result so it's gonna totally drop it so we will not find it
13:00:16
이제 당신은 물어볼 수 있습니다, 첫 번째 쿼리의 중간 결과에 접근할 수 있는지?
anywhere it's completely lost now the other thing about the intermediate results is that imagine you are making another query that is completely outside of the first query we are selecting few tables from our database.
13:00:28
이제 우리는 완전히 외부 쿼리에 대해 이야기하고 있습니다. 그렇게 할 수 없습니다.
Now you might say, you know what, is it possible to access the intermediate results from the first query?
13:00:35
서브 쿼리의 중간 결과는 메인 쿼리 자체에서만 로컬로 알려져 있으며, 다른 쿼리에서는 전역적으로 사용할 수 없습니다.
So now we are talking about completely external query. You cannot do that.
13:00:38
그래서 서브 쿼리는 메인 쿼리에서만 사용할 수 있습니다.
The intermediate result of the sub query is only locally known from the main query itself, and it is not globally available for any other query.
13:00:48
그래서 서브 쿼리는 메인 쿼리에서만 사용할 수 있습니다.
So the sub query can be used only from the main query.
13:00:51
그래서 우리는 서브쿼리가 무엇인지 이해했고, 이제 왜 서브쿼리가 필요한지 물어볼 수 있습니다.
So with that we have understood what are subqueries and now you might ask me why do we need them in the first place?
13:01:01
서브쿼리가 중요한 이유는 무엇일까요? 다음과 같은 개요를 살펴보겠습니다.
Why subqueries are important? Let's have the following sketch. Now in our complex task we might have to do several stuffs in our query.
13:01:09
예를 들어, 첫 번째 단계로 테이블을 조인해야 합니다.
Like for example the first step we have to go and join tables in order
13:01:12
데이터를 준비하기 위해서이며, 조인의 결과는
to prepare the data and then the outcome of the joins should be
13:01:15
필터링되어야 하므로 이것이 우리의 두 번째 단계입니다.
filtered so this is going to be our step two and then on
13:01:18
그 위에, 세 번째 단계에서는 변환 작업을 해야 합니다.
top of that in the step three we have to go and do transformations
13:01:22
예를 들어, 널 값을 처리하거나 새로운
like he may be handling the nulls or creating new
13:01:25
열을 만들고 여러 가지 작업을 하며, 마지막 단계에서는
columns and many other stuff and the last step we want to go
13:01:28
데이터 집계를 수행하여 데이터를 요약하거나 평균을 찾습니다.
and do data aggregations like summarizing the data or finding average
13:01:32
이제 즉시 SQL 쿼리를 작성하기 시작하면
now if you go immediately and start writing the sql query without
13:01:35
계획 없이 무슨 일이 일어날지 알 수 없으며
having a plan what can happen you can end up having
13:01:38
긴 복잡한 SQL 쿼리를 가지게 될 것입니다.
a long complex sql query and
13:01:41
작성하기도 어렵고 이해하기도 힘들 것입니다.
it's going to be really hard to write and as well to understand and
13:01:44
대신, 우리는 작업을 나누어
read and now what we can do instead of that we're going to go and divide our
13:01:47
단계별로 쿼리 섹션을 작성할 것입니다.
task based on those steps so we're going to write one
13:01:51
예를 들어, 테이블을 조인하는 쿼리를 작성하고
query section for each step for example for joining tables we're
13:01:54
필터링을 위한 쿼리, 변환을 위한 쿼리, 마지막으로
going to have one query for filtering another one transformation another
13:01:57
집계를 위한 쿼리를 가질 것입니다.
one and for the aggregation we're going to have the last query so
13:02:01
각 단계가 다음 단계의 준비와 같으므로
now since each step is like a preparation for the
13:02:04
각 사각형은 서브 쿼리입니다.
next step we can go and say each of those squares
13:02:07
1단계, 2단계, 3단계에 서브 쿼리가 있으며
is a sub query so for step one step two step
13:02:10
모두 마지막 단계의 계산과 준비를 수행합니다.
three we have sub queries and they are all doing
13:02:13
집계를 위해 마지막 단계를 메인 쿼리라고 부릅니다.
like calculations and preparations for the last step to
13:02:17
물론 모든 작업이 하나의 쿼리로 존재할 수 있습니다.
the aggregations and we call the last step the main query
13:02:20
물론 전체가 하나의 쿼리로 존재할 수 있습니다.
and of course the whole thing can exist in one single query
13:02:23
서브 쿼리가 있는 것처럼 시각화하고 싶다면
so if you want to visual this like you have a sub query
13:02:26
원 안에 그리고 이 원은 더 큰
in circle and then this circle belongs to a bigger
13:02:29
메인 쿼리라고 불리는 원에 속합니다. 때때로 우리는
circle called the main query by the way sometimes we
13:02:32
메인 쿼리를 외부 쿼리라고 부르고
call the main query as the outer query and the
13:02:35
서브 쿼리는 내부 쿼리라고 부를 수 있으며, 물론 우리는
sub query we can call it an inner query and of course we
13:02:39
서브 쿼리를 많이 가질 수 있고 내부에 많은 작은 원을 가질 수 있습니다.
can have many sub queries and many small circles inside
13:02:42
서로를 형성하여 중첩 쿼리라고 불리는 것을 만듭니다.
each others to form something called nested queries
13:02:45
이것이 서브 쿼리를 사용하는 주된 목적입니다.
so this is the main purpose of using sub queries in
13:02:49
우리의 스크립트와 쿼리에서 복잡성을 줄이는 데 도움이 될 것입니다.
our scripts and queries it's gonna help us to reduce the complexity
13:02:52
읽기 쉽게 만들고 우리는
and gonna make it easier to read and we
13:02:55
쿼리 내에서 논리적 흐름을 가질 수 있습니다. 이제 서브 쿼리에 대해 다양한 유형과 범주가 있습니다.
can have like a flow logical flow inside our queries now for the sub queries there are many different types and categories.
13:03:06
이제 우리가 할 일은, 모든 유형과 범주의 개요를 보여주는 것입니다.
So now what we're going to do, I'm going to show you an overview of all those types and categories.
13:03:11
그리고 나중에 각 유형에 대해 깊이 들어갈 것입니다. 먼저 서브 쿼리와 메인 쿼리 간의 의존성에 대해 생각해보면, 주로 두 가지 유형의 서브 쿼리가 있습니다.
And then later, we're going to deep dive into each of those types. So first of all, if you are thinking about the dependencies between the subquery and the main query, there is mainly two types of subqueries.
13:03:22
비상관 서브 쿼리가 있습니다. 이는 서브 쿼리가 메인 쿼리와 독립적임을 의미합니다.
We have the non-correlated subquery. That means the subquery is independent from the main query.
13:03:29
두 번째 유형은 상관 서브 쿼리입니다. 이는
And the second type is the correlated sub query it's
13:03:32
정확히 반대입니다. 서브 쿼리는
exactly the opposite the sub query gonna depend on
13:03:35
메인 쿼리에 의존하게 됩니다. 물론 모든 내용을 자세히 설명할 수 있습니다.
the main query of course you can explain all those stuff in details
13:03:39
걱정하지 마세요. 이것이 첫 번째 그룹입니다. 이제 또 다른
don't worry about it so this is the first group now there is another
13:03:42
서브 쿼리를 그룹화하는 방법에 대한 그룹이 있습니다.
group on how to group up the sub queries depending
13:03:46
결과 유형에 따라 다릅니다. 즉,
on the result type so i mean with this that
13:03:49
서브 쿼리는 서로 다른 출력과 결과를 가집니다. 예를 들어
the sub query has different outputs and results for example
13:03:52
스칼라 서브 쿼리가 있으며, 이는 단일 값을 반환합니다. 또는 다른 유형인 행 서브 쿼리가 있으며, 이는
we have scalar sub query it returns only one single value or another type it's called the row sub query it's gonna return
13:04:00
여러 행을 반환합니다. 마지막 유형은 테이블
multiple rows and the final type called the table
13:04:03
서브 쿼리로, 여러 행과 여러 열을 반환하는 서브 쿼리입니다.
sub query it is a sub query that returns multiple rows
13:04:07
세 번째 방법으로 넘어갑니다.
and as well multiple columns now we come to the third way
13:04:10
서브 쿼리를 분류하는 마지막 방법입니다.
and the last way on how to categorize the sub queries and
13:04:13
이번에는 위치와 절을 기준으로 합니다.
this time based on the location and the clauses so we
13:04:17
여기서 서브 쿼리가 사용될 위치를 설명합니다.
are describing here where the sub query gonna be used
13:04:20
주 쿼리 내에서 다양한 위치에서 사용할 수 있습니다.
within the main query so we can use it in different locations
13:04:23
선택 절과 같은 절에서 사용할 수 있습니다.
and clauses like the select clause or
13:04:26
FROM 절에서 사용할 수 있으며, 이는 가장 일반적입니다.
we can use it in the from clause and this is the most common
13:04:30
테이블을 조인하기 전에 사용할 수 있습니다.
type for the subqueries or we can use it before joining
13:04:33
데이터를 필터링하기 위해 사용할 수 있습니다.
tables and we can use it in order to filter the data in the
13:04:36
작업 절에서 사용할 수 있으며, 작업 절에서는
work clause and in the work clause as we learned there are
13:04:39
두 가지 다른 연산자 세트를 사용할 수 있습니다.
two different sets of operators we can use the
13:04:42
비교 연산자와 함께 서브 쿼리를 사용할 수 있습니다.
subqueries together with the comparison operators the less
13:04:45
논리 연산자와 함께 사용할 수 있습니다.
greater equal and so on or we can use it with the
13:04:48
모두와 존재하는 것과 같은 논리 연산자입니다.
logical operators like the in any
13:04:52
이제 서브 쿼리의 다양한 유형과 범주를 살펴보겠습니다.
all and exists so now those are the different types and categories for the subqueries and we're gonna now deep dive into
13:05:00
이제 가장 쉬운 범주부터 시작하겠습니다.
So now let's go and start with the easiest category,
13:05:03
서브 쿼리의 결과 유형과 범주가 있습니다.
the result types and categories for the sub queries and we're gonna now deep dive into all of them so now let's go and start with the easiest category the result types of the sub queries now
13:05:10
결과를 기반으로 한 다양한 유형의 서브 쿼리가 있습니다.
we have different types of sub queries based on the results
13:05:13
서브 쿼리가 반환할 수 있는 데이터 양을 의미합니다.
so this means the amount of data that the sub query can return so the first type is the scalar sub query so it is a sub query that
13:05:22
첫 번째 유형은 스칼라 서브 쿼리입니다.
it's going to return only one single value like
13:05:25
예를 들어, 값 3을 반환할 것입니다.
for example the value 3 let's have an example for the scalar sub
13:05:29
예를 들어, SELECT *을 말하는 경우입니다.
query so in this query for example if you are saying select star
13:05:32
하나의 테이블에서 모든 열과 모든 행을 가져옵니다.
you will get all columns all the rows from one table
13:05:35
스칼라 서브 쿼리에는 하나의 값만 필요합니다.
but for the scalar sub query we need only one value
13:05:38
일반적으로 집계를 통해 얻습니다.
so how we usually get it is by doing some aggregations
13:05:42
예를 들어, 판매의 평균을 구하자고 하면, 실행해 보겠습니다. 그 결과로 38이라는 하나의 값만 있습니다. 이런 쿼리를 스칼라 쿼리라고 부릅니다.
for example if you go and say let's get the average of sales so let's execute it and with that in the output we have only one value with a 38 We call such a query as a scalar query.
13:05:54
그래서 이 쿼리는 한 행과 한 열만 있습니다. 그래서 이것이 스칼라 쿼리입니다. 알겠죠.
So it has only one row and only one column. So this is a scalar query. All right.
13:05:59
이제 두 번째 유형으로 넘어가겠습니다. 행 서브쿼리가 있습니다.
So now to the second type, we have the row subquery.
13:06:03
이 서브쿼리는 여러 행과 하나의 열을 반환합니다.
So it is a subquery that's going to return multiple rows and a single column.
13:06:09
그래서 우리는 값 하나, 둘, 셋을 가질 것입니다. 그래서 이것은 여러 행이 있는 하나의 열입니다. 행 쿼리의 예를 들어보겠습니다.
So we're going to have like values one, two, three. So it is only one column with multiple rows. Let's have an example for the row query.
13:06:16
보시다시피, 이제 우리는 orders 테이블에서 select star를 보고 있습니다. 이제 여러 행과 여러 열을 얻고 있습니다.
As you can see, now we are seeing select star from the table orders. And now we are getting multiple rows and multiple columns.
13:06:23
하지만 행 쿼리의 경우, 우리는 하나의 열만 필요합니다. 예를 들어, 고객 ID를 선택할 수 있습니다.
But for the row queries, we need only one column. So you can go over here, for example, say customer ID.
13:06:30
그리고 실행하면, 출력에서 우리는 하나의 열과 여러 행을 갖게 됩니다.
And if you go and execute it. So now if you check the output, we have a single column and as well multiple rows.
13:06:36
그래서 우리는 값 목록을 가지고 있습니다. 이것이 우리가 행 쿼리라고 부르는 것입니다. 알겠죠.
So we have like a list of values. And this is what we call a row query. All right.
13:06:41
이제 마지막 유형으로 넘어가겠습니다. 테이블 서브쿼리가 있습니다.
So now to the last type, we have the table sub query.
13:06:45
이 서브쿼리는 여러 행과 여러 열을 반환할 것입니다. 일반 테이블처럼요.
It's going to go and return multiple rows and as well multiple columns. like any regular tables.
13:06:51
이 서브쿼리는 많은 값을 반환할 수 있습니다. 자, 이제 그 테이블 쿼리의 예를 보겠습니다.
So this sub query can return a lot of values. Okay, so let's see an example of that table query.
13:06:57
여기 우리의 예를 확인해 보세요. orders에서 select star를 하면, 여러 행과 여러 열을 얻습니다.
So if you check our example here, select star from orders, we got here multiple rows and as well multiple columns.
13:07:05
물론, 우리는 여러 열을 선택할 수 있습니다. 예를 들어, 주문 ID와 주문 날짜를 선택할 수 있습니다.
And of course, we can go and select multiple columns like for example, the order ID and the order date.
13:07:11
그래서 여기서 실행하면, 출력에서 우리는 여러 열과 두 개의 열, 그리고 여러 행을 갖게 됩니다.
So if we execute it here in the output, we have multiple columns, we have two columns and as well multiple rows.
13:07:18
그래서 이런 종류의 쿼리는 테이블 쿼리입니다.
That's why this kind of queries as well a table
13:07:21
그래서 우리는 다양한 유형의 서브쿼리를 배웠습니다.
query all right so with that we have learned the different types of
13:07:24
결과 유형에 따라 서브쿼리를 배웠고, 이제 우리는
sub queries based on the result type now we're going to go
13:07:27
서브쿼리를 다양한 위치에서 사용하는 방법을 배울 것입니다.
and learn how to use the sub queries in different
13:07:30
그래서 우리는 from 절에서 서브쿼리를 사용하는 방법을 시작할 것입니다.
locations in our query so we're going to start with how
13:07:34
FROM 절에서 서브 쿼리를 사용하는 것
to use sub query in the from clause okay
13:07:41
그래서 우리는 일반적으로 FROM 절에서 서브 쿼리를 사용하여 메인 쿼리를 위한 테이블처럼 작용하는 임시 결과 집합을 만듭니다.
so we typically use the sub queries in the from clause in order to create temporary result sets that act as a table for the main query.
13:07:51
어떤 상황에서는 데이터베이스에서 테이블을 직접 사용할 수 없습니다.
So it's like in some scenarios, we cannot use the tables directly from the database.
13:07:55
실제 쿼리를 실행하기 전에 뭔가를 준비해야 합니다.
We have to prepare it somehow before we do our actual query.
13:08:00
좋아요, 그러면 프레임 절 안의 서브 쿼리 문법을 확인해 봅시다.
Okay, so let's check the syntax of the sub query inside the frame clause.
13:08:04
그래서 우리는 일반적인 것부터 시작합니다. 선택하고 검색하려는 몇 개의 열을 말합니다.
So we start with the usual stuff where we go and say select and few columns that you want to retrieve
13:08:10
그리고 우리는 보통 'from' 다음에 오는 것을 말합니다.
and then we say okay from usually after the from comes
13:08:13
쿼리할 데이터베이스의 테이블 이름입니다.
the table name from our database that we want to query
13:08:16
하지만 이번에는 테이블 이름을 작성하는 대신
but this time instead of writing the table name we're
13:08:20
또 다른 SQL 쿼리를 사용할 것입니다. 즉,
gonna have another sql query so that means we
13:08:23
테이블 이름을 정의하지 않고 또 다른 선택을 정의합니다.
don't define the table name we define another select
13:08:26
문에서 특정 테이블의 열을 선택하고 필터가 있을 수 있습니다.
statements where we have as well again select a
13:08:29
이것이 서브쿼리임을 SQL에 알리기 위해 괄호를 사용해야 합니다.
column from specific table and then maybe we have a filter
13:08:32
시작과 끝에 괄호가 있습니다. 이것은 서브쿼리입니다.
and in order now to tell sql this is a sub query we have to use the parentheses so we're gonna have the parentheses
13:08:39
주 쿼리가 아니며 괄호 다음에
at the start and at the end this is a subquery this
13:08:42
결과에 대한 별칭을 정의할 수 있습니다.
is not the main query and after the parentheses we
13:08:45
이 서브쿼리에서 얻을 결과에 대한 별칭입니다.
can go and define the alias for the results
13:08:48
많은 데이터베이스에서 이 별칭은 선택 사항이지만 SQL 서버에서는
that we're going to get from this subquery in many databases this
13:08:52
별칭은 선택 사항이지만 SQL 서버에서는 반드시 필요합니다.
alias is an optional but for the sql server we have to
13:08:55
따라서 별칭을 지정해야 하므로 SQL 서버에서는 필수입니다. 다시 말해, 우리는 이것을 서브쿼리라고 부르고 외부 쿼리는
go and specify an alias so it is a must in sql server so again we call this a subquery and the outer query we call it
13:09:04
주 쿼리라고 부릅니다. 그래서 이것이 서브쿼리의 구문입니다.
main query so this is the syntax of the sub query in
13:09:07
FROM 절에서요. 자, 이제 다음 작업이 있습니다. 다음과 같이 말합니다.
the from clause okay so now we have the following task and it says
13:09:10
가격이 더 높은 제품을 찾으세요.
find the products that have a price higher
13:09:13
모든 제품의 평균 가격보다. 그래서 우리는
than the average price of all products so we're
13:09:17
단계별로 진행할 것입니다. 여기에는 두 단계가 있습니다. 첫 번째 단계는
gonna do it step by step and here we have two steps the first one
13:09:20
모든 제품의 평균 가격을 계산해야 합니다.
is that we have to go and calculate the average price of all
13:09:23
두 번째 단계에서는 이 값을 사용하여
products and the second step we're gonna use this value in order
13:09:26
제품 테이블을 필터링하여
to filter the table products in order to find the
13:09:29
이 평균 가격보다 높은 가격을 찾습니다.
prices that is higher than this average price
13:09:32
자, 첫 번째 단계부터 시작해 평균 가격을 찾아봅시다.
so let's start with the first step where we're gonna find the average price
13:09:36
다음 정보를 선택할 것입니다.
i'm gonna select the following informations so
13:09:39
제품 ID 가격에서
product id price from
13:09:43
판매 제품 테이블에서
the table sales products so
13:09:47
이제 실행해 보겠습니다. 이제 제품과
let's go and execute it so now we have the product and
13:09:50
가격도 필요합니다. 평균 가격과 비교하기 위해 이 가격이 필요합니다. 즉, 이 가격과 나란히
as well the prices and we need this price here in order to compare it with the average price so that means we need this price and as well side by side
13:09:59
평균 가격이 필요합니다. 즉, 집계와 세부 정보가 필요합니다. 그래서 우리는 윈도우 함수를 사용할 것입니다.
we need the average price so that means we need aggregations and details and that's why we're going to go with the window function
13:10:06
평균이므로 이제 이것을 실행해 보겠습니다. 매우 간단합니다. 평균 가격이 될 것입니다.
average so let's go and do this it's very simple so it's going to be the average price
13:10:12
데이터를 분할하고 싶지 않으므로
and we don't want to partition the data so it's going to be an
13:10:15
빈 상태에서 평균 가격이 될 것입니다. 이제 실행해 보겠습니다. 이를 통해 계산했습니다.
over empty and this is going to be the average price like this so let's go and execute it and with that we have calculated
13:10:22
평균 가격입니다. 이제 모든 정보가 있습니다.
the average price so now we have all the informations in
13:10:25
첫 번째 단계로 평균 가격과 가격이 있습니다.
the first step we have the average price we have the price and
13:10:29
제품도 있습니다. 이제 다음 단계는
as well the products so now the next step is that we have to
13:10:32
데이터를 필터링하여 모든 제품을 찾아야 합니다.
go and filter the data to find out all the products
13:10:35
가격이 평균보다 높은
where the price is higher than the average that
13:10:38
정보를 바탕으로 이 단계를 수행할 것입니다.
means we will do this step based on those information
13:10:42
이제 우리는 서브 쿼리와 메인 쿼리의 논리를 사용해야 합니다.
that we have now so that means we have to go and use the
13:10:45
데이터를 준비하기 위한 첫 번째 단계이므로 서브 쿼리로 사용할 것입니다.
logic of sub query and main query since this is the first step to prepare the data we're going to use this as a sub query so we're going to call this a sub query like this
13:10:57
이제 메인 쿼리에서 사용해야 합니다.
and we have to go and use it in the main query so
13:11:00
그렇게 하려면 메인 쿼리를 작성해야 합니다.
how we're going to do that we have to go and write the main query
13:11:04
여기서 선택을 시작할 것입니다.
so it's going to be i'm going to start over here select
13:11:07
모든 열을 가져올 것입니다. 이것이 메인 쿼리입니다.
and then i will take all the columns from so this is the main query let me just make this a little bit smaller and what What are you going to do now?
13:11:18
이제 메인 쿼리는 서브 쿼리에서 데이터를 가져올 것입니다.
So now the main query going to get the data from the sub query. So the whole thing going to be used inside the from clause.
13:11:26
메인 쿼리 안에 서브 쿼리를 넣으려면 괄호를 사용해야 합니다.
So now in order to put the sub query inside the main query, we have to go and use the parentheses.
13:11:31
시작과 끝에 괄호를 추가할 것입니다. 일반적으로 탭을 추가하여 서브 쿼리임을 이해합니다.
So we're going to have it at the start and as well at the end. And what we usually do, we go and add like a tab in order to understand, okay, this is the sub query.
13:11:41
이제 메인 쿼리입니다. SQL 서버의 전체 서브 쿼리에 별칭을 추가해야 합니다.
And then this is the main query. So now one more thing that we have to add for the whole subquery in the SQL server that we have to give it an alias.
13:11:49
그래서 원하는 이름을 지정할 수 있습니다. 저는 보통 T로 한 글자를 사용합니다.
So you can go and give it any name that you would like. I usually go with only one character with the T.
13:11:54
T는 테이블을 의미하므로 원하는 것을 사용할 수 있습니다. 하지만 SQL 서버에서는 서브쿼리에 별칭을 줘야 합니다.
It stands for table so you can use anything that you want. But we have in SQL server to give an alias for the subquery.
13:12:01
이제 우리가 하는 것은 서브쿼리에서 모든 것을 선택하라는 것입니다.
So now what we are saying we are saying select everything from the subquery.
13:12:05
여기 가서 실행하면 결과는 동일합니다. 왜냐하면 메인 쿼리는 아무것도 하지 않기 때문입니다.
If you go over here and execute it you will get the exact same results because the main query is doing nothing.
13:12:11
서브쿼리에서 모든 것을 선택하라고 하고 있지만
it's saying just select everything from the sub query but
13:12:14
이제 작업을 해결하기 위해 모든 제품에 관심이 없습니다.
now in order to solve the task we are not interested with all products
13:12:17
우리는 가격이 더 높은 제품에만 관심이 있습니다.
we are interested only the products where the price is higher than the
13:12:20
그래서 where 절을 사용해야 합니다. 우리는 다음과 같이 말할 것입니다.
average that's why we have to go and use the
13:12:24
가격이 평균보다 높다고 말할 것입니다.
where clause so we're gonna say where the
13:12:27
가격이 평균보다 높습니다.
price is higher than the average
13:12:30
이 필터링이 완료되었습니다.
price so this filtering is done
13:12:33
메인 쿼리에서는 서브쿼리 안에 있지 않습니다.
in the main query it's not inside the sub
13:12:36
메인 쿼리에서는 서브쿼리 안에 있지 않습니다.
query so now that means in the main query we are doing something
13:12:39
이제 메인 쿼리에서 무언가를 하고 있다는 뜻입니다.
let's go and excuse it and with that we saw the
13:12:42
이제 두 개의 제품을 얻고 있으며 가격이
task we are getting now two products where the price is
13:12:45
평균 가격보다 높습니다. 보시다시피 매우 간단합니다.
higher than the average price so as you can see it's very simple if
13:12:49
작업에 여러 단계가 있다면 여러 서브쿼리를 사용하여 메인 쿼리를 만들 수 있습니다.
the task has multiple steps then we can do that using
13:12:52
여기서 서브쿼리는 메인 쿼리를 지원하기 위한 것입니다.
multiple sub queries until we have the main query and
13:12:55
이 작업을 위해서는 즉시 결과를 계산할 수 없습니다.
we can learn from this that the sub query is here is only to support the main query so we are preparing here that all the data that we need in order to have the final result for the main query.
13:13:07
먼저, 이런 종류의 작업에서는 모든 것을 하나의 선택 쿼리에 넣을 수 없습니다.
So for this task, we cannot go immediately calculating the results.
13:13:11
먼저 데이터를 하나의 서브쿼리에서 준비한 다음 메인 쿼리에 값을 전달해야 합니다.
We have first, so for this kind of task, we cannot immediately like put everything in one select query.
13:13:16
이것이 우리가 테이블 서브쿼리라고 말하는 것입니다. 그리고 여기 당신을 위한 빠른 팁이 있습니다.
We have first to prepare the data in one subquery and then pass the values for the main query.
13:13:22
이것이 우리가 테이블 서브쿼리라고 말하는 것입니다. 그리고 여기 당신을 위한 빠른 팁이 있습니다.
And this is what we mean with the table subquery. And here one quick tip for you.
13:13:27
서브쿼리에서 얻는 중간 결과를 보고 싶다면,
If you would like to see the intermediate results that we are getting from the subquery,
13:13:32
서브쿼리 자체를 괄호 없이 강조 표시할 수 있습니다.
you can go and highlight the sub query itself without the parentheses so we are just highlighting the sub query you can go now and execute it and with that israel will not go and execute everything
13:13:44
이스라엘은 당신이 강조하는 것만 실행할 수 있습니다.
israel can execute only what you are highlighting so this
13:13:47
서브 쿼리의 결과를 보는 정말 좋은 방법입니다.
is a really nice way in order to see the results of the sub
13:13:50
디버깅하거나 오류를 찾는 것처럼 서브 쿼리를 사용할 수 있습니다.
query as you are like debugging or searching for errors you can go and see the intermediate results that is used from the main query and of course if you deselect
13:13:59
아무것도 강조하지 않고 실행하면
and not highlight anything and execute it's
13:14:02
전체 쿼리를 실행하게 됩니다.
going to go and execute everything the whole query so this
13:14:06
이것이 테이블 서브 쿼리를 사용하는 방법입니다.
is how we use the table sub query inside
13:14:09
FROM 절 안에서 다른 작업을 해봅시다.
the from clause all right so let's have another task and it says
13:14:12
고객을 총 판매액에 따라 순위 매기기입니다.
rank the customers based on their total amount of sales so again if you check here we have like two steps first we have to find the total amount of sales and then after that
13:14:24
두 단계가 필요합니다.
we have to go and rank the customers so again we have like
13:14:27
첫 번째 단계에서 총액을 찾겠습니다.
two steps and we can use the sub queries in order to solve it
13:14:30
판매액을 선택합시다.
so let's start with the first step where we're going to find the total amount
13:14:33
이제 여러 고객이 출력됩니다.
of sales so let's go and select the customer id and as well the sales from the table sales orders
13:14:45
이제 총액을 찾아야 합니다.
let's go and execute it so now in the output we have like multiple customers
13:14:49
각 고객의 판매액을 찾아야 합니다.
and their sales we have to go and now find the total
13:14:52
GROUP BY를 사용해야 합니다.
amount of sales for each customer that means we have to go
13:14:55
판매액을 요약할 것입니다.
and use the group by so we're going to go and summarize the
13:14:59
데이터를 그룹화합니다.
sales so total sales
13:15:02
고객 ID로 그룹화합니다.
and then group up the data by
13:15:05
이제 실행해봅시다.
the customer id so like this
13:15:09
네 명의 고객과 각 고객의 총 판매액이 있습니다.
let's go and excuse it now as you can see in the output we
13:15:12
다음 쿼리를 준비했습니다.
have four customers and we have the total sales for each customer and with that we have solved the first step we have the total amount of sales for each customer and we have now prepared the data
13:15:22
고객을 순위 매기기 위해서입니다.
for the next query in order to rank the customers
13:15:25
서브 쿼리의 중요성을 이해하고 있습니다.
so now i think you're already getting how important are the
13:15:28
이것이 우리의 서브 쿼리입니다.
sub queries in order to do step-by-step analysis so
13:15:32
이제 메인 쿼리를 준비해야 합니다.
this is our sub query now we need the main
13:15:35
쿼리를 준비할 것입니다.
query so i will start preparing it so
13:15:38
메인 쿼리처럼 이렇게 시작하겠습니다.
main query like this and let's go first and
13:15:41
모든 것을 선택하겠습니다. 별을 선택합니다.
select everything so select star from
13:15:45
이것을 조금 더 크게 만들어 보겠습니다.
let me just make this a little bit bigger like
13:15:48
이제 이 쿼리를 서브 쿼리로 변환해야 합니다.
this and now we have to go and convert this query to a sub
13:15:51
괄호가 필요합니다. 시작하는 부분과
query so we need the parentheses so the starting
13:15:55
끝나는 부분을 위해 SQL 서버에
and the ending and for the sql server i'm going to give
13:15:58
별칭을 주고 모든 것을 오른쪽으로 밀어보겠습니다.
it an alias and i would like to push everything to the right side
13:16:01
완벽하게 실행해 보겠습니다.
so let's go and execute it perfect so it
13:16:04
서브 쿼리가 메인 쿼리로 전달되고 있습니다.
is working with that the sub query is passing the
13:16:07
물론 메인 쿼리는 이제 쓸모가 없습니다.
data in the from clause to the main query now
13:16:11
우리는 순위를 계산해야 하며, 이를 위해
of course the main query is now is useless it's just like selecting the data we have to go and calculate the rank and for that we have a very
13:16:18
아주 멋진 윈도우 함수를 사용할 것입니다.
nice window function so we're gonna go and use the
13:16:21
데이터를 정렬해야 하며, 정렬 기준은
rank so it doesn't need any parameters over we
13:16:24
총 판매량에 따라 내림차순으로 정렬해야 합니다.
have to sort the data order by so we have to
13:16:28
가장 높은 것부터 가장 낮은 것까지 진행하겠습니다.
go and sort the data by the total sales descending
13:16:31
총 판매량에 따라 내림차순으로 진행하겠습니다.
from the highest to the lowest so we're gonna go with the total
13:16:34
우리가 이미 준비한 총 판매량을 사용하고 있습니다.
sales and descending so now as you can see
13:16:37
서브 쿼리에서 데이터를 준비하지 않으면
we are using the total sales that we have already prepared
13:16:40
그게 전부입니다. 실행해 보겠습니다.
in the sub query so without preparing trace the data we will not be able to rank the customers in the main query so
13:16:47
정렬된 데이터를 가지고 있습니다.
that's it let's go and execute it and with that sql
13:16:50
서브 쿼리에서 가져온 데이터를 기반으로 한 멋진 순위입니다.
sorted our data and we have a nice ranking based
13:16:54
가장 높은 고객과 판매량입니다.
on the data that we had from the sub query so
13:16:57
고객 번호 1과 그 외의 고객들입니다.
this is the highest customer with the sales and then the
13:17:00
여러 단계가 있으며 서브 쿼리의 힘을 사용합니다.
customer number one and so on so again in this task we have
13:17:03
여러 단계가 있으며 서브 쿼리의 힘을 사용합니다
like multiple steps and we use the power of the sub queries in
13:17:07
단계별로 수행하기 위해 서브 쿼리를 사용하는 방법입니다
order to do it step by step so that's all on how to
13:17:10
서브 쿼리를 FROM 절 안에 사용하는 방법을 빠르게 살펴보겠습니다
use the sub query inside the from close okay so now let's see quickly how sql executed our query so we have
13:17:16
여기 우리의 쿼리가 있으며 우리는 orders 테이블을 쿼리하고 있습니다
here our query and we are querying the table orders so the first
13:17:19
첫 번째 단계는 서브 쿼리를 식별하는 것입니다
step is that is going to go and identify the sub query and
13:17:23
그런 다음 서브 쿼리를 실행할 것입니다
then it's going to go and execute it so is going to go and execute the
13:17:27
데이터를 집계하는 서브 쿼리 부분입니다
sub query parts where we are aggregating the data based
13:17:30
고객 ID를 기준으로 하며 서브 쿼리가 실행된 후
on the customer id so once the sub query is executed
13:17:33
다음 단계는 결과를 도입할 수 있다는 것입니다
the next step is that the result can be introduced
13:17:36
중간 결과로서 이 결과는 출력에서 보이지 않습니다
as an intermediate result so these results we will not see it in the output it's going to be like temporarily saved in the
13:17:44
임시로 메모리에 저장될 것입니다
memory so now the next step is that sql is going to go to
13:17:47
이제 다음 단계는 SQL이 메인 쿼리로 이동하는 것입니다
the main query and it's going to execute it based on the
13:17:50
메인 쿼리를 실행할 것이며
intermediate results so that means the main query will not
13:17:53
중간 결과를 기반으로 실행됩니다
go back to the original table it's going to go and
13:17:56
즉, 메인 쿼리는 원본 테이블로 돌아가지 않습니다
query the intermediate results so here what sql is going to do
13:17:59
중간 결과를 쿼리할 것입니다
going to go and rank the intermediate results by introducing
13:18:02
여기서 SQL이 할 일입니다
a new column where we see the ranks one two three four and the output of the main query going to be the final results so as you can
13:18:09
중간 결과를 순위별로 정렬할 것입니다
it's very simple first sql is executing the sub query
13:18:12
새로운 열을 도입하여 순위를 보여줍니다
and the result of the sub query going to be used in the
13:18:15
메인 쿼리의 출력은 최종 결과가 될 것입니다
main query and once the main query is executed we
13:18:18
SQL이 서브 쿼리를 실행하는 것이 매우 간단합니다
will get the final results so the sub query here is only
13:18:22
서브 쿼리의 결과는 메인 쿼리에서 사용될 것입니다
supporting the main query so those are the steps that
13:18:25
메인 쿼리가 실행되면
sql uses in order to execute the
13:18:28
최종 결과를 얻을 수 있습니다
sub queries so now let's understand how the database server execute the sub queries
13:18:38
서브 쿼리는 메인 쿼리를 지원합니다
behind the scenes let's go so now let's say that you are data analyst and
13:18:41
클라이언트 측에서 쿼리를 작성하고 있습니다.
you are writing a query at the client side where you have
13:18:44
주 쿼리 내에 서브쿼리가 있으므로 실행하면
a subquery inside the main query so once you go and execute it
13:18:47
데이터베이스 엔진이 서브쿼리를 식별하게 됩니다.
what's gonna happen the database engine gonna go and identify
13:18:51
서브쿼리를 먼저 실행할 수 있습니다.
the subquery and in this situation the database can
13:18:54
주문 테이블에서 데이터를 선택하고 검색하는 것입니다.
execute first the subquery so his subquery is
13:18:57
사용자 데이터에서 디스크 저장소에서 데이터를 검색해야 합니다.
like selecting and retrieving data from the table orders so that means the database has to retrieve the data from the disk storage
13:19:05
서브쿼리가 실행되면
from the user data so now once the subquery is executed
13:19:08
중간 결과가 캐시에 저장될 수 있습니다.
the result the intermediate results can be stored
13:19:12
서브쿼리의 결과는 임시적이며 매우 빠릅니다.
in the cache so this means the result of the subquery
13:19:15
서브쿼리의 결과를 검색하고
is temporary and as well very fast
13:19:18
주 쿼리를 실행하기 시작할 것입니다.
retrieve and now once the database engine is done with the subquery
13:19:21
이 시나리오에서는 결과에 따라 완전히 달라집니다.
it's gonna go and start executing the main query so
13:19:25
서브쿼리의 결과에 따라 주 쿼리가 캐시 저장소와 상호작용하게 됩니다.
let's see in this scenario it's completely depending on the result of
13:19:28
작업이 완료되면 결과를 데이터베이스 엔진으로 전달할 수 있습니다.
the subquery so that means the main query gonna go and interact with the cache storage so So this means now the data can be retrieved very fast from the result of the sub query.
13:19:38
그리고 당신의 측에서는 최종 결과를 찾을 수 있습니다.
Once it's done, it can forward the results to the database engine and the database engine can forward the results to the client side.
13:19:45
모든 것이 실행된 후 데이터베이스 엔진이 캐시를 정리할 수 있습니다.
And at your side, you will find the final results.
13:19:48
다른 쿼리들을 위해서입니다.
And of course, once everything is executed, the database engine can go and clean up the cache so the sub query results can be destroyed and removed completely from the cache in order to have a free space.
13:20:00
서브쿼리가 어떻게 작동하는지에 대해 이야기하겠습니다.
other queries. So this is how the database server execute the subqueries behind the scenes.
13:20:09
서브쿼리를 선택 절에서 사용하는 방법에 대해 이야기하겠습니다.
Alright, so now we're going to talk about how to use the subquery in the select clause.
13:20:13
서브쿼리를 선택 절에서 데이터와 함께 집계하는 데 사용합니다.
So now we typically use the subqueries in the select clause to aggregate the data side by side with the columns of the main query.
13:20:21
서브쿼리의 문법을 확인해 보겠습니다.
Okay, so let's check the syntax of the subquery in the select clause.
13:20:25
간단한 것부터 시작하겠습니다.
So we start with the simple stuff where we say, okay, let's go and select
13:20:29
특정 테이블에서 검색할 열을 선택합니다.
a column that you want to retrieve from specific table
13:20:32
테이블을 쿼리하고 있습니다.
so nothing new we are just querying a table and now what
13:20:35
특정 테이블에서 열을 선택할 수 있습니다.
we can do in this scale is that not only we can go and select
13:20:38
특정 테이블에서 열을 선택할 수 있습니다.
the columns from specific table we can go and
13:20:42
여기에서 또 다른 쿼리를 삽입할 수 있습니다.
insert here inside the select another query
13:20:45
전체 쿼리처럼 선택하고 어디서부터 시작하는지 다시 말하자면, 쿼리 안에 쿼리가 있습니다. 이를 서브쿼리라고 합니다.
like a full query like select from and where so again it's like query inside another query and we call this of course a sub query in
13:20:53
SQL에 이 쿼리가 서브쿼리임을 알리기 위해
order to tell sql this is a sub query we go
13:20:56
괄호를 추가해야 합니다. SQL이 이해하지 못할 것입니다.
and add the parentheses so without sql gonna understand uh-huh
13:21:00
이것은 서브쿼리이며 이 쿼리의 결과는
this is a sub query and the result of this query gonna
13:21:03
선택에서 사용될 것이므로 다른 열처럼 처리할 수 있습니다.
be used in the select so we can handle it like any
13:21:06
여기서 별칭을 줄 수 있습니다. 선택 사항입니다.
other column we can go and give it like an alias it is here optional
13:21:09
별칭을 추가할 필요는 없습니다. 이 내부 쿼리를
and not must to add an alias so this inner query
13:21:12
서브쿼리라고 부르며 외부 쿼리는 메인 쿼리가 됩니다. 서브쿼리를 선택 절에 넣는 방법입니다.
we call it a sub query and the outer query gonna be the main query so this is how you put a sub query in the select clause but there is one rule for this query that
13:21:23
이 서브쿼리의 결과는 스칼라여야 합니다.
the result of this sub query must be scalar
13:21:26
쿼리라는 것은 결과가 단일 값이어야 함을 의미합니다.
query that means the result must be a single value because
13:21:30
그렇지 않으면 작동하지 않습니다. SQL은 오직
otherwise it will not work sql here is expecting only
13:21:34
하나의 값만 기대합니다. 서브쿼리를 사용하는 방법입니다.
one value so this is how we use the sub query inside
13:21:37
선택 절 안에서. 자, 다음 작업을 해보겠습니다. 다음과 같이 표시합니다.
the select clause all right let's have the following task and it says show the
13:21:41
제품 ID, 제품 이름, 가격 및
product ids product names prices and
13:21:44
총 주문 수를 표시합니다. 이제 작업을 확인해보면
the total number of orders so now if we check the task there is
13:21:47
두 부분이 있습니다. 첫 번째 부분은 세부 정보를 보여주는 것입니다.
like two parts the first part is that we are showing the details
13:21:50
제품에 대한 세부 정보와 두 번째 부분은
about the products and the second part that we have to go and
13:21:53
총 주문 수를 계산해야 합니다. 이제 무엇을 할지 봅시다.
calculate the total number of orders so let's see what we're gonna
13:21:57
먼저 이 간단한 부분을 해결해 봅시다.
do first let's go and solve this simple part here
13:22:00
이미 제품 ID, 제품 이름 및 가격이 있습니다.
we already have the product id product names and prices
13:22:03
따라서 제품 ID와 제품, 그리고 가격을 선택할 것입니다.
so we're gonna go and select the product id and the products and then the price
13:22:09
판매 제품 테이블에서
from the table sales products
13:22:13
실행해 보겠습니다. 이를 통해 작업의 첫 번째 부분을 해결했습니다.
let's go and execute it so with that we have solved the
13:22:16
우리가 그 제품에 대한 세부 정보를 가진 작업의 첫 번째 부분을 해결했습니다.
first part of the task we have the details about that products
13:22:19
이제 두 번째 부분을 해결하러 가야 합니다. 총 주문 수를 계산해야 합니다.
now we go and solve the second part we have to go and calculate
13:22:22
이 정보는 다른 테이블에서 옵니다. 제품에서 계산할 수 없습니다.
the total number of orders now this information come
13:22:25
제품에서 주문을 쿼리해야 합니다. 이제 무엇을 해야 할까요?
from different table from the products we cannot calculate it
13:22:29
주문을 쿼리해야 합니다. 이제 무엇을 해야 할까요?
from products we have to go and query the orders so now what
13:22:32
이 부분을 별도의 쿼리로 계산할 것입니다. 여기 제품 안에 두지 않고 세미콜론을 사용하여 두 번째 쿼리를 만들겠습니다.
we're going to do i'm going to go and calculate this part in separate query instead of having it here inside the product so let's have a semicolon in order to have a second query so we're going to go
13:22:44
주문 수를 선택하고, 우리는 간단히
and select the total number of orders that means we can go simply
13:22:47
판매 테이블에서 모든 주문 수를 계산합니다.
do account star from the table sales
13:22:51
조금 더 크게 만들겠습니다.
orders let me just make it a little bit bigger
13:22:54
우리는 이를 총 주문 수라고 부를 것입니다.
so we're gonna call it total orders
13:22:57
세미콜론도 추가하겠습니다. 이제 전체를 실행하면 결과에서 두 부분을 얻을 수 있습니다.
and a semicolon as well so now if you just execute
13:23:01
첫 번째는 제품의 세부 정보입니다.
the whole thing you will get here like two parts in the results
13:23:04
두 번째 부분은 총 주문 수입니다.
first you have the details of the product and the
13:23:07
우리는 10개의 주문이 있지만, 이제 두 가지 다른
second part we have now the total number of orders we
13:23:10
쿼리가 서로 분리되어 있습니다. 두 가지 결과가 있습니다.
have 10 orders but now with that we have like two different
13:23:13
작업에서 모든 것을 보여줘야 합니다.
queries like separated from each other's and we have two
13:23:16
정보를 하나의 결과로 보여줘야 합니다. 이제 무엇을 할 수 있을까요?
different results but in the task we have to show all those
13:23:19
하나의 쿼리를 다른 쿼리 안에 넣을 수 있습니다.
informations in one result so now what we can do
13:23:22
이제 두 번째 쿼리인 총 주문 수를 확인하면 단일 값만 있습니다.
we can put one query inside another query so
13:23:26
이렇게 하면 모든 것을 한 줄에 넣을 것입니다.
now if you check the second query the total orders you can see we have only single value so we have a scalar query scalar sub query that's why we can go with this as a sub query
13:23:38
보려면 세미콜론을 제거합시다.
like this and i'm gonna go and put everything in one line
13:23:42
필요하지 않습니다. 이제 우리가 할 일은
in order to see it so let's remove the semicolons we
13:23:45
전체를 가져와서
don't need it and now what we're gonna do we're gonna go and take
13:23:48
주요 쿼리 안에 넣는 것입니다.
the whole thing and put it inside the
13:23:51
주요 쿼리입니다. 이제 새로운 것으로 생각해 보세요.
main query so this is the main
13:23:54
쿼리이고 이제 그것을 새로운 것으로 생각해 보세요
query and now think about it as new
13:23:58
열이므로 쿼리를 여기 두겠습니다. 그래서 우리의 선택에서 하나의 새로운 열입니다.
column so i will put the query here so it is just one new column in our select but in order to have it
13:24:04
서브 쿼리로 만들기 위해서는 괄호를 사용해야 합니다.
as a sub query we have to use the parentheses
13:24:07
시작과 끝에 괄호를 두고, 물론 가서
at the start and at the end and of course we have to go and
13:24:10
이름을 지어야 하므로 같은 이름을 사용할 것입니다.
give it a name so i'm gonna go and use the same name over
13:24:13
여기서 총 주문으로 할 것입니다.
here so it's gonna be as total orders
13:24:17
그래서 서브 쿼리의 설정이 준비되었습니다.
so with that the setup for the sub query is ready
13:24:20
그리고 그것은 선택 절 안에 있습니다.
and it is inside the select clause in
13:24:24
메인 쿼리에서 이제 실행해 보겠습니다. 모든 정보를 함께 가지고 있습니다.
the main query let's go and execute it now as you can see we have everything together we have the three information, the product details and as well side by side with that total orders.
13:24:34
항상 같은 값이기 때문에 각 행에 대해 반복될 수 있습니다.
And since it is always the same value, it can go and be repeated for each row.
13:24:38
이것을 스칼라 서브 쿼리라고 부릅니다.
So this is what we call scalar sub query inside the select clause.
13:24:43
선택 절 안에 서브 쿼리를 사용하는 경우 스칼라 서브 쿼리만 허용됩니다.
And here again, very important to understand if you are using a sub query inside the select clause, only the scalar sub query is allowed.
13:24:52
예를 들어 집계에서 하나의 값을 갖는 대신 주문 ID를 사용할 수 있습니다.
So for example, instead of having one value from the aggregation, we can go and use the order ID.
13:24:58
무슨 일이 일어날지 봅시다. 오류가 발생할 것입니다.
So let's see what can happen. we will get an error it's
13:25:02
서브쿼리가 하나 이상의 값을 반환하고 있다고 말할 것입니다.
gonna say subquery is returning more than one value and
13:25:05
서브쿼리를 선택 절에서 사용하고 있기 때문에 허용되지 않습니다.
this is not allowed because we are using the subquery in
13:25:08
그래서 하나의 값만 있어야 하며 집계를 사용하면 하나의 값을 얻을 수 있습니다.
the select clause so that's why we have to have only
13:25:11
수정해 보겠습니다. 이제 작동하고 있습니다.
one value and by using the aggregation you will get one value
13:25:14
서브쿼리의 결과만 보고 싶다면
so let's repair it and it's working and now again
13:25:18
서브쿼리를 강조 표시할 수 있습니다.
if you'd like only to see the results from the subquery what you
13:25:21
괄호 없이 이렇게 하고
can do you can go and highlight the sub query like
13:25:24
실행하면 출력에서 10을 볼 수 있습니다.
this without the parentheses of course and you go
13:25:27
이것은 메인 쿼리에 전달될 중간 결과입니다.
and execute it and with that you can see in the output the 10
13:25:30
전체가 실행되기를 원한다면
this is the intermediate results that's going to be passed to
13:25:34
체크를 해제하고 실행하면 모든 것이 가능합니다.
the main query and if you want the whole thing to be executed just
13:25:37
그냥 선택 해제하고 실행하면 모든 것이
like unmark it and execute and with that everything can
13:25:40
실행될 수 있습니다. 서브 쿼리와 메인 쿼리이므로
be executed the sub query and the main query so this is the
13:25:43
이것은 선택 절의 스칼라 서브 쿼리입니다. 자, 이제
scalar sub query in the select clause okay so now
13:25:47
SQL이 이 쿼리를 단계별로 실행하는 방법을 빠르게 살펴보겠습니다.
let's see quickly how sql executed this query step by step
13:25:50
이것은 우리의 원래 쿼리이며, 두 개의 테이블이 필요합니다.
so this is our original query and we need two tables
13:25:53
데이터베이스에서 이를 위해 첫 번째 단계는
from our database for it so the first step is that is going to go
13:25:56
서브 쿼리를 식별하는 것입니다.
and identify the sub query and it's
13:25:59
서브 쿼리를 식별하고 실행할 것입니다. 이것이 첫 번째 단계입니다.
going to go and execute it so this is the first step so the
13:26:02
쿼리는 주문 테이블을 대상으로 하고 있으며, 우리는 단순히
query is targeting the orders table and we are just simply
13:26:05
계산을 하고 있습니다. 출력에서 우리는
doing account so in the output we will get an
13:26:08
중간 결과를 얻을 것이며, 행 수를 세고 있습니다.
intermediate results where we are counting the number of rows of
13:26:12
주문 수를 세고 있습니다. 이제 다음 단계는 이 값을 메인 쿼리로 전달하는 것입니다.
the orders now the next step is that is clearly going to go and pass this value to the main query
13:26:17
이것은 두 번째 단계이며, 이 값을 메인 쿼리로 전달하면 이렇게 보일 것입니다.
so this is the second step and if you go and pass this value to the main query it's going to look like this so you are saying product id products and the 10.
13:26:27
SQL이 메인 쿼리를 준비한 후에 실행될 것입니다.
so after sql prepared the main query is going to go
13:26:30
이번에는 제품을 대상으로 하고 있습니다.
and execute it so this time we are targeting the products
13:26:33
출력에서 우리는 제품의 모든 정보를 얻을 것입니다.
and in the output we will get all the information from the products
13:26:36
필터 없이, 여기서는 작업 클라우드가 없기 때문에 최종 결과는 이렇게 될 것입니다.
without any filter because here we don't have any work clouds and the final results we will get it like this so we will have the product id the product
13:26:44
서브 쿼리에서 얻은 총합과 함께 제품 ID가 포함됩니다.
and the total that we got it from the sub query so as
13:26:47
여기서 서브 쿼리는 스칼라 서브 쿼리이며,
you can see the sub query here is a scalar sub query where
13:26:50
단일 값만 있습니다. 그래서 다시 말해 매우
we have only one single value so again it's very
13:26:53
간단합니다. 항상 SQL은 서브 쿼리로 시작하고
simple always sql starts with the sub query and
13:26:57
그런 다음 메인 쿼리로 값을 전달하고, 마지막에 메인 쿼리가 실행됩니다.
then it's gonna go and pass the values to the main query and at the end the main query gonna be executed and we will get the final result from it so this is how sql executed our query
13:27:12
좋습니다. 다음으로 서브 쿼리를 사용하는 방법에 대해 이야기하겠습니다.
all right next we're going to talk about how to use the sub query
13:27:15
조인 절에서, 좋습니다. 이제 조인하고 있으므로
in the join clause all right so now as we are joining
13:27:18
SQL에서 테이블을 조인하기 전에 데이터를 준비해야 할 때가 있습니다.
tables in sql sometimes we have to go and prepare
13:27:21
조인을 수행하기 전에 데이터를 준비해야 합니다.
the data before doing the join to dynamically create
13:27:25
다른 테이블과 조인하기 위해 결과 집합을 동적으로 생성해야 합니다.
a result sets for joining with another table so
13:27:28
다시 말하지만, 여기서는 테이블을 직접 조인할 수 없습니다.
again here we cannot join tables directly we have to do a preparation step before doing the joins okay
13:27:34
모든 고객 세부정보를 표시하고 각 고객의 총 주문 수를 찾는 작업을 해보겠습니다.
Let's have the following task and it says show all customer details and find the total orders of each customer.
13:27:41
SQL에서는 단 하나의 솔루션만 있는 것이 아니라 여러 솔루션이 있습니다.
Now, of course, in SQL, you don't have only one solution, you have multiple solutions, but I would like to solve this task using the sub query.
13:27:48
작업을 확인하면 두 부분이 있습니다. 첫 번째 부분은 모든 고객 세부정보를 표시하는 것입니다.
So now if you check the task, we have like two parts. The first part, we have to show all the customer details.
13:27:53
두 번째 부분은 집계로, 각 고객의 총 주문 수를 찾는 것입니다.
And the second part, we have like an aggregation, find the total orders of each customer.
13:27:59
이제 두 가지 쿼리를 사용하여 서로 다른 부분을 해결해 보겠습니다.
So now let's solve those different parts using two different queries
13:28:02
가장 쉬운 것부터 시작하겠습니다. 모든 고객 세부정보를 표시해 보겠습니다.
let's start with the easiest one show all customer details so
13:28:05
이것은 매우 간단하다고 생각합니다. 모든 항목을 선택합니다.
i think this is very simple so select star
13:28:09
판매 고객에서 모든 세부정보를 가져옵니다.
from sales customers so
13:28:12
출력을 실행하면 고객에 대한 모든 세부정보가 표시됩니다.
let's go and execute it so in the output we have all the details about the customers and we have solved the first part very simple now let's go and solve the second part we have defined the total number of orders
13:28:25
각 고객의 총 주문 수를 정의했습니다.
of each customer that means let me just have a semicolon
13:28:28
여기에서 주문 테이블로 가야 합니다.
over here we have to go to the table orders
13:28:31
먼저 주문 ID 고객을 선택해 보겠습니다.
so let's go and select first the order id customer
13:28:35
판매 테이블에서 ID를 가져옵니다.
id from the table sales
13:28:38
이렇게 주문을 하겠습니다. 이제 두 번째 쿼리를 강조 표시하고 실행하겠습니다.
orders like this so i will just highlight
13:28:41
출력에서 10개의 주문과 다양한 고객이 있습니다.
the second query and execute it now in the output we have 10 orders and we have the different customers now in order to find the total orders for each customer we have
13:28:50
각 고객의 총 주문 수를 찾기 위해 그룹 파이프를 사용해야 합니다.
go and use the group pipe in order to do that it's very
13:28:53
간단합니다. 여기에서 카운트를 하겠습니다.
simple we're gonna go over here and say so count
13:28:56
별표로 진행한 후 고객 ID로 데이터를 그룹화하겠습니다.
let's go with the star and then we're gonna go
13:28:59
이것을 총 주문 수라고 부르겠습니다.
and group up the data by the customer id
13:29:02
이 부분만 실행해 보겠습니다.
i will go and call this total orders
13:29:05
그 결과 네 명의 고객과 총 주문 수가 있습니다.
so let's go and execute only these parts
13:29:09
이제 작업의 두 번째 부분을 해결했습니다.
and with that we have four customers and we have the total number of orders so with that we have solved the second
13:29:15
작업의 두 번째 부분을 해결했습니다.
part of the task so now what i'm gonna do i'm gonna go and execute
13:29:19
세미콜론을 사용하여 두 쿼리를 각각 실행하겠습니다.
both of those queries using the semicolon separately
13:29:22
이렇게 하면 조금 더 크게 만들겠습니다.
like this i will just make this a little bit bigger
13:29:25
이제 실행해 보겠습니다. 출력에는
so let's go and execute it now in the output we have the
13:29:28
고객에 대한 모든 세부 정보와
two results all details about the customers and
13:29:32
각 고객의 총 주문 수가 포함됩니다. 이제
the total number of orders for each customer so now what
13:29:35
우리는 두 결과를 하나로 결합해야 합니다. 이를 위해 조인을 사용할 수 있습니다.
we want to do is to go and combine those two results in one and in order to do that we can use the joins so now we have to think about what is is the first query, what is the second query?
13:29:45
첫 번째 쿼리는 데이터베이스에 있는 모든 고객을 반환하므로 이를 왼쪽 테이블로 사용하겠습니다.
Since the first query returns all the customers that we have in the database, I would like to have this as the left table.
13:29:52
두 번째 쿼리에는 고객이 네 명만 있으므로 이를 오른쪽 테이블로 사용하겠습니다.
And since in the second query, we have only four customers, I would like to have it then as the right table.
13:29:58
왼쪽 조인을 사용하여 고객을 놓치지 않도록 하겠습니다.
And I will go with the left join so that i don't
13:30:02
내부 조인을 사용하면 고객 번호 5를 잃게 됩니다.
miss any customer because if i do the inner join i will lose
13:30:05
그럼 이제 첫 번째 쿼리를 실행해 보겠습니다.
the customer number five so let's go and do that so this
13:30:08
이제 이 쿼리를 메인 쿼리로 부르겠습니다.
is the first query in the main query so i'm
13:30:11
이 쿼리에도 별칭을 주겠습니다.
gonna call this main query now
13:30:15
이제 데이터베이스에서 이 테이블을 조인하겠습니다.
i'm gonna give this as well an alias like the c and
13:30:19
결과와 함께 조인하겠습니다.
now we're gonna go and join this table from the database
13:30:22
이 쿼리를 이렇게 실행하겠습니다.
together with the results the output of
13:30:25
왼쪽 조인으로 진행하겠습니다.
this query so that means we're going to do it like this
13:30:28
서브 쿼리와 조인할 것입니다.
lift join and now we're going to join with a
13:30:32
여기에 몇 개의 공백을 넣어 서브 쿼리임을 명확히 하겠습니다.
sub query so we will have our parentheses i
13:30:35
서브 쿼리의 결과와 조인할 것입니다.
will just put here few spaces so that it's clear it is a sub query and we need for this an alias so let's go and say for example the o so with that we are joining a table
13:30:46
이제 테이블을 키를 사용하여 조인해야 합니다.
with the result of a sub query and now of course
13:30:49
두 결과를 확인하면 두 쿼리 모두에서
what is missing is joining the tables using a key now
13:30:52
고객 ID가 있으므로 고객 ID로 조인하겠습니다.
if you check the two results you can see in both queries we
13:30:56
고객 ID로 조인하겠습니다.
have the customer id that's why we're gonna join with
13:30:59
고객 ID를 가지고 있으니
the customer id so on then
13:31:02
고객 ID와 함께
the customer id with the
13:31:05
서브 쿼리에서 고객 ID를
customer id from the sub query like
13:31:10
이제 모든 것을 준비했으니 실행해 보겠습니다
this so we have everything let's go and execute it now as you can see in the output
13:31:15
고객에 대한 모든 세부 정보를 가지고 있습니다
we have all the details about the customer and
13:31:18
각 고객에 대한 총 주문 수와 함께
as well together with the total number of orders for each
13:31:21
각 고객과 함께 총 주문 수를
customer together with the total number of orders for
13:31:25
각 고객에 대한 총 주문 수와 함께
each customer and as you can see we didn't miss any customers so we have all the customers from the database and we can see that
13:31:31
안나에게는 현재 주문이 없습니다
anna doesn't have any orders now you might say you
13:31:34
여기 고객 ID가 두 번 있습니다
know what we have here the customer id twice so what i'm gonna do i will select all the columns from the customers but from the sub query i'm
13:31:43
총 주문에만 관심이 있습니다
interested only on the total orders so
13:31:46
이렇게 실행해 보겠습니다
like this let's go and execute it let's make this a little bit
13:31:50
결과가 매우 깔끔해졌습니다
smaller so now the results are real clean we have all details
13:31:53
고객과 총 주문 수를
from the customers and as well the total orders
13:31:56
서브 쿼리의 결과를 확인하려면
of each customer and of course as we learned if you would like to check
13:31:59
서브 쿼리를 사용하는 방법에 집중하겠습니다
the results from only the sub query you go and highlight it and execute it so as you can see you can put the sub queries almost everywhere and this is how we use sub queries inside joins
13:32:14
WHERE 절에서 서브 쿼리를 사용합니다
okay so now we're gonna focus on how to use the sub query in
13:32:17
WHERE 절을 사용하여 테이블을 필터링합니다
the where clause so now in SQL as we learned we can
13:32:20
정적 값을 사용하지만 이제 실제 데이터에서는
go and filter the tables using the where clause by
13:32:24
복잡한 기준으로 데이터를 필터링합니다
using like static values but now in real data
13:32:27
이 복잡한 논리를 준비하기 위해
projects we're gonna go and filter the data based on like complex
13:32:30
서브 쿼리를 사용합니다
logic so now in order to prepare this complex
13:32:33
주요 테이블에 대한 동적 필터링을 만들기 위해
logic we go and use the sub queries in order
13:32:36
데이터를 필터링하기 위해
to make like dynamic filtering for our main
13:32:40
연산자를 사용해야 합니다
tables and now in order to filter data using the where clouds
13:32:43
우리는 연산자를 사용해야 하고 이를 나눌 수 있습니다.
we have to go and use operators and we can split it into
13:32:46
비교 연산자와 다른 그룹으로 나눌 수 있습니다.
like two groups we have the comparison operators and another
13:32:49
논리 연산자라고 부를 수 있는 집합입니다.
set we can call it a logical operators or sometimes we
13:32:52
서브쿼리 연산자라고 부를 수 있습니다.
call it sub queries operators so now first we're going to talk about
13:32:55
비교 연산자에 대해 이야기할 것입니다.
the comparison operators so they are operators that we
13:32:58
두 값을 비교하는 데 사용할 수 있는 연산자입니다.
can use in order to compare two values in order to help
13:33:01
특정 조건에 따라 데이터를 필터링하는 데 도움이 됩니다.
us filtering the data based on specific condition and
13:33:05
SQL 기초에서 다양한 비교 연산자를 배웠습니다.
now in sql basics we have learned that we have different comparison
13:33:08
비교하기 위해 간단한 연산자들이 있습니다.
operators and they are very simple so in order to compare
13:33:11
같은 값을 비교하는 연산자가 있습니다.
two values we have operator like the equal we have as well
13:33:14
같지 않음, 더 크거나, 더 작음이 있습니다.
not equal the opposite so we have greater than
13:33:17
같거나, 마지막으로 더 작음이 있습니다.
less than and as well we have greater than or
13:33:21
또는 같음으로, 매우 간단합니다.
equal to and the last one we have less than
13:33:24
두 값을 비교하는 대신 값을 비교할 것입니다.
or equal to so they are very simple now instead of
13:33:27
서브쿼리의 결과를 비교 연산자로 사용할 것입니다.
comparing two values we're gonna go and compare a value with
13:33:30
서브쿼리의 구문을 확인해 보겠습니다.
the result of subquery using the comparison operators all
13:33:34
비교 연산자를 사용하여 시작합니다.
right let's check the syntax of the subquery inside the where clause
13:33:37
표준적인 내용으로 몇 개의 열을 선택합니다.
using the comparison operators so we start with
13:33:40
우리가 검색하고자 하는 데이터를 직접 가져옵니다.
the standard stuff where we say select few columns that
13:33:43
특정 테이블에서 데이터를 가져옵니다.
we want to retrieve and we want to get the data directly from
13:33:46
테이블을 필터링하기 위해 WHERE 조건으로 옵니다.
specific table in our database and now we come to the where condition where we want to filter the table so we say where and then we select specific
13:33:54
그 테이블에서 특정 열을 선택합니다.
column from that table one now since we are talking about
13:33:57
비교 연산자에 대해 이야기하고 있습니다.
the comparison operators we can go with the operator for example equal
13:34:01
정적 값을 여기에서 지정합니다.
and usually we go and specify here like static value
13:34:04
숫자나 문자열 대신에 값을 가져올 수 있습니다.
like a number or string but instead of having a
13:34:07
정적 값 대신에 우리가 할 수 있는 것은 값을 가져오는 것입니다
static value what we can do we can get the value
13:34:10
다른 선택문에서, 다른 쿼리처럼
from another select statements another query like
13:34:13
여기서 테이블 두에서 열을 선택하라고 말하는 것입니다
here for saying select a column from table two and
13:34:17
필터와 함께 이제 이 서브 쿼리에서 오는 모든 것이
with the filter so now whatever comes from this sub query
13:34:20
테이블 번호 하나를 필터링하는 데 사용될 것입니다
gonna be used in order to filter the table number
13:34:23
물론 SQL에 이것이 서브쿼리임을 알리고
one and of course we are telling SQL this is a subquery by
13:34:26
시작과 끝에 괄호를 정의함으로써
defining the parentheses at the start and at the end
13:34:30
외부 쿼리는 메인 쿼리가 될 것이므로 보시다시피
and the outer query gonna be the main query so as you can see
13:34:33
서브쿼리를 사용하여 필터링하고 있습니다
we are using the subquery in order to filter
13:34:36
메인 쿼리와 여기 SQL에서 서브쿼리를 사용할 때
the main query and here in SQL if you are using subquery with
13:34:39
비교 연산자와 함께 서브쿼리는
the comparison operators we have a rule the subquery must
13:34:42
스칼라 서브쿼리여야 하며, 단일 값만 있어야 합니다
be a scalar subquery so only one single value so that's all about how to use the subquery in the where clause using the comparison operators
13:34:52
좋습니다, 이제 우리는 다시 같은 작업이 있으며 찾으라고 합니다
Alright, so now we have again the same task and it says find
13:34:55
가격이 더 높은 제품을 찾으라고 합니다
the products that have a price higher than the
13:34:58
우리가 이 작업을 수행한 평균 가격보다
average price of all products we have saw this task
13:35:01
이미 FROM 절 안에서 서브 쿼리를 사용하고 있습니다
already using the sub query inside the from clause
13:35:05
하지만 이제 우리는 다시 서브쿼리를 사용하여 해결할 것입니다
but now we're gonna go and solve it again using the sub
13:35:08
이번에는 WHERE 절 안에서 쿼리를 사용하겠습니다
query but this time inside the where clause so let's do it step by step let's go and get the informations that we need so we need the product id we need the price from the table
13:35:20
정보를 단계별로 가져오고 제품 ID와 가격을 가져와야 합니다
sales products so let's go and execute it so
13:35:23
판매 제품을 가져오고 실행해 보겠습니다
now we got the list of all products but we have to go and
13:35:27
이제 모든 제품 목록을 얻었지만
filter those informations using the column
13:35:30
정보를 열을 사용하여 필터링해야 합니다
price so that's in the result we got all the products but
13:35:33
결과에서 모든 제품을 얻었지만
we don't need all the products we need only the products where
13:35:36
우리는 모든 제품이 필요하지 않고
the price is higher than the average that means we have to
13:35:39
평균보다 가격이 높은 제품만 필요합니다
go and filter the table based on the values of the price so now in order to do that what we're gonna do we're gonna use the where clause and we have to
13:35:48
가격을 기준으로 데이터를 필터링하세요.
go and filter the data based on the price and since
13:35:51
우리는 더 높은 값을 필요로 하므로 비교 연산자를 사용할 것입니다.
we need higher than we're gonna go and use the comparison operator higher
13:35:54
이제 평균 값을 알아야 합니다.
than and now next we need the value average
13:35:57
평균 가격을 어떻게 할 것인지, 평균 가격이 없습니다.
price so how we're gonna do it we don't have the average price
13:36:00
제품 테이블에서 평균 가격을 계산해야 합니다.
like out of the box in the table products we have to go and calculate it that's why we're gonna go and write another query where we're gonna go and find the
13:36:09
평균 가격은
average price from
13:36:12
테이블 판매 제품과 같은
the table sales products like
13:36:16
이제 강조 표시하고 실행해 보겠습니다.
this so now let's go and highlight it and then execute
13:36:19
그렇게 해서 이제 평균 가격을 얻었습니다.
it and with that we got now the average price of
13:36:22
모든 제품에 대해, 에피소드에서 보시다시피 우리는 하나만 있습니다.
all products and as you can see in the episode we have only one
13:36:25
단일 값이므로 이것은 스칼라 쿼리입니다. 이제 우리가 필요한 것은 이 값을 첫 번째 쿼리를 필터링하는 데 사용해야 합니다. 그래서 첫 번째 쿼리는
single value so this is a scalar query so now what we need we need this value in order to be used in order to filter the first query so that's why the first query is
13:36:38
주 쿼리이고 두 번째는
the main query bigger the second one is
13:36:41
주 쿼리를 지원할 서브 쿼리입니다.
the sub query that's gonna support the main
13:36:44
데이터를 필터링하기 위한 쿼리입니다. 이제 우리가 할 일은
query in order to filter the data so now what we're gonna do
13:36:47
서브 쿼리를 가져와서 사용합니다.
we're gonna take the sub query and use it
13:36:50
where 절에 넣을 것입니다. 이제 물론 스케일에 이것이
in the where clause and now of course you have to tell scale this is a
13:36:53
서브 쿼리임을 알려야 하므로 두 개의 괄호 안에 넣어야 합니다.
sub query that's why we have to put it inside two parentheses
13:36:57
그래서 이렇게 해서 우리는 where 절 안에 서브 쿼리를 두어 주 쿼리를 필터링합니다. 이제 실행해 보겠습니다. 출력에서 보시다시피
so with that we have the sub query inside the where clause in order to filter the main query so let's go and execute it and now as you can see in the output
13:37:06
이제 가격이
we have now only two products where the price is
13:37:09
평균 가격보다 높은 두 개의 제품만 있습니다. 그래서 우리는
higher than the average price so with that we
13:37:12
작업을 해결했지만 이번에는 서브 쿼리를 사용하여
have solved the task but this time using the sub query in
13:37:15
주 쿼리를 필터링하기 위한 where 절에 넣었습니다. 물론
the where clouds in order to filter the main query and of course
13:37:18
이 값을 우리의 select에서 보려면
in order to see this value in our select since it
13:37:21
스칼라 서브 쿼리이므로 여기에서 가져와서
is scalar sub query we can as well go over here and put
13:37:25
값을 보기 위해 select에 넣을 수 있습니다.
it in our select just in order to see the value
13:37:28
그래서 평균 가격을 실행해 보겠습니다. 결과에서 평균 가격을 확인할 수 있습니다. 이것이 우리가
so average price so let's go and execute it and with that we can see as well in our results the average price so this is how we
13:37:35
비교를 사용하여 WHERE 절에서 서브쿼리를 사용하는 방법입니다.
use the subquery in the where clouds using the comparison
13:37:38
연산자입니다. 자, 이제 ISQL이 우리의
operator okay so let's see quickly how isql execute our
13:37:41
쿼리를 단계별로 실행하는 방법을 빠르게 살펴보겠습니다. 보통 ISQL은
query step by step so as usual first isql gonna go
13:37:44
서브쿼리를 식별할 것입니다. 우리의 선택 평균이 될 것입니다.
and identify the subquery it's gonna be our select average
13:37:48
가격과 그 외 여러 가지입니다. 이제 다음 단계로 ISQL이
price and so on and now the next step isql gonna go
13:37:51
서브쿼리를 실행할 것입니다. 이는 제품을 기반으로 합니다.
and execute our subquery so it is based on the products
13:37:54
우리가 그룹화 없이 집계를 수행하고 있기 때문에 출력에서는 하나의 값만 얻을 것입니다. 평균은 20이 될 것이고 이 값은
and since we are doing aggregations without group by at the output we will get only one value so the average is gonna be 20 this value is stored
13:38:03
메모리에 임시로 저장될 것입니다. 따라서 출력에서는 보이지 않을 것입니다.
intermediately in the memory so we will not see it in the output
13:38:06
이 값을 메인 쿼리로 전달할 것입니다.
is going to go and pass this value to
13:38:09
메인 쿼리는 이렇게 보일 것입니다. 우리는
the main query so the main query is going to look like this we
13:38:12
테이블에서 몇 개의 열을 선택하고 있으며
are selecting few columns from the table and we
13:38:15
가격이 더 높은 데이터베이스를 필터링하고 있습니다.
are filtering the database on the price that is higher
13:38:18
우리가 서브쿼리에서 얻은 값 20보다 높은
than the value 20 that we get it from the sub
13:38:21
쿼리입니다. 이제 SQL이 메인 쿼리에 필요한 모든 것을 갖추면
query so now once sql have everything for the main query it's
13:38:25
실행할 것입니다. 즉, 제품으로 이동할 것입니다.
going to go and execute it so it's going to go to the products
13:38:28
가격이 20보다 높은 제품만 선택할 것입니다. 따라서 두 개의 행만 있습니다.
and only select the products where the price
13:38:31
출력에서 최종 결과를 얻을 것입니다. 두 개의 제품이
is higher than 20 so it's only those two rows and in
13:38:34
있습니다. 제품 ID와 제품 가격입니다. 그게 전부입니다.
the output we will get the final results the two products
13:38:37
매우 간단합니다. 이것이 ISQL이 우리의 쿼리를 실행한 방법입니다.
as well so product id and product price so that's it it's
13:38:40
보통 서브쿼리로 시작하여 값을 전달합니다.
very simple this is how isql executed our query so as usual first
13:38:44
메인 쿼리로, 마지막에 메인 쿼리를 실행할 수 있습니다.
starting with the sub query passing the value to
13:38:47
서브쿼리의 정보로, 마지막에 최종 결과를 얻을 것입니다.
the main query and at the end so the main query can be executed with
13:38:50
그렇습니다. 이제 우리는
the informations from the sub query and we will get at the end the
13:38:53
두 번째 연산자 그룹에 대해 이야기할 것입니다. N으로 시작하겠습니다.
final results so that's it all right so now we're going to talk about the
13:39:01
두 번째 연산자 그룹에 대해 이야기할 것입니다.
second group of operators and we're gonna start with the n
13:39:04
연산자가 무엇인지 배웠던 것처럼
operator so what is an operator as we learned before
13:39:07
비교 연산자에서는 데이터를 필터링할 수 있습니다.
in the comparison operators we can go and filter the data
13:39:10
하나의 값만으로 데이터를 필터링해야 하는 경우도 있습니다.
based on only one single value but now in some
13:39:13
여러 값을 기준으로 데이터를 필터링해야 합니다.
scenarios we have to go and filter the data based on multiple
13:39:17
여기서 n 연산자를 사용할 수 있습니다.
values not only one in this case we can go and use the
13:39:20
n 연산자를 사용하면 값이 목록의 값과 일치하는지 확인합니다.
n operator so if you go and use the n operator it's gonna go and check whether the value matches any value from a list so a list of multiple values if it matches any of them so we will get it through.
13:39:31
이제 in 연산자를 사용하는 서브쿼리의 구문을 살펴보겠습니다.
Okay, so now let's have a quick look to the syntax of the subquery using the in operator.
13:39:37
우리는 테이블 1에서 열 1과 열 2를 검색하고 싶습니다.
So we start with the classic stuff where we say, okay, we would like to retrieve the column one, column two from the table one and we want to filter the data based on the column from the table one.
13:39:47
그 열을 지정한 후 in 연산자를 사용할 것입니다.
Now, after specifying that column, we're going to use that in operator and after that, we can go and specify static values.
13:39:54
서브쿼리에 대해 이야기하고 있으므로 값은 다른
But since we are talking about the subqueries, the values can come from another
13:40:00
쿼리에서 가져올 수 있습니다.
query so here we have another select statements from
13:40:03
이 서브쿼리의 결과를 사용할 수 있습니다.
table 2 and we filter the data for this query and
13:40:06
in 연산자를 사용하여 데이터를 필터링하는 데 사용할 수 있습니다.
now the result of this sub query can be used
13:40:09
in 연산자와 비교 연산자 사이의 큰 차이점입니다.
in order to filter the data using the in operator and
13:40:13
서브쿼리는 여러 행을 가질 수 있습니다.
now the big difference between the in operator and the comparison
13:40:16
스칼라 서브쿼리의 결과로 가질 수 있습니다.
operators that's the sub query is allowed to have multiple rows so there is no rule about having like one single
13:40:23
여러 값의 목록입니다.
value scalar subquery we can have in the result
13:40:26
in 연산자를 사용하는 서브쿼리의 구문입니다.
a list of multiple values so this is
13:40:30
이 작업을 연습해 보겠습니다.
the syntax of the subquery using the n operator
13:40:33
고객이 주문한 세부 정보를 보여줍니다.
all right let's practice using this task it says
13:40:36
독일에서 고객이 주문한 세부 정보를 보여줍니다.
show the details of orders made by customers
13:40:39
주문 세부 정보가 필요합니다.
in germany so let's see how we can solve this task first
13:40:42
출력에는 모든 주문과 모든 세부 정보가 포함됩니다.
it needs the details of orders so as we know we have the table sales orders so let's go and execute it so
13:40:51
모든 주문이 필요하지 않습니다.
in the output we have all orders and with all details
13:40:54
하지만 작업을 위해 모든 주문이 필요하지 않고
but for the task we don't need all the orders we need
13:40:57
독일 고객이 만든 주문만 필요합니다.
only the orders that made by customers from germany so
13:41:01
지금 주문 테이블을 확인하면 정보가 없습니다.
now if you check the table orders you don't find any informations
13:41:04
국가에 대한 정보가 필요하므로
about the countries right so we have to go and get it from
13:41:07
다른 테이블에서 가져와야 합니다.
another table and as we know we can find these informations
13:41:10
고객 테이블에서 정보를 찾을 수 있습니다.
in the table customers so let's build another
13:41:13
쿼리를 작성해 보겠습니다.
query so let's say select star from
13:41:16
판매 고객과 같은
sales customers like
13:41:21
이렇게 해서 두 번째 쿼리만 실행해 보겠습니다.
this so let's go and execute only the second query
13:41:24
이제 고객에서 볼 수 있는 것처럼
like this now as you can see in the customers we have the
13:41:27
국가 열이 있으며 이것이 우리가 필요한 것입니다.
country column and this is exactly what we need so now
13:41:30
독일 고객의 목록을 만들어 보겠습니다.
let's make a list of all customers from germany so we don't
13:41:33
모든 고객이 필요하지 않고 독일에서 온 고객만 필요합니다.
need all customers we need only the one that come from germany that's
13:41:36
그래서 WHERE 절을 사용하겠습니다.
why we're gonna go and use the where clause and we say
13:41:40
국가가 일반적으로 이 값과 같도록
country equal to the value generally
13:41:43
이렇게 해서 다시 실행해 보겠습니다.
like this so let's go
13:41:46
결과를 확인해 보겠습니다.
and execute it again and check the results now in
13:41:49
출력에서 독일 고객 번호 1과 4가 있습니다.
the output we have our german customers number one and number
13:41:52
이 정보를 사용하여 주문 테이블을 필터링하겠습니다.
four so now we're gonna go and use this information in order to filter
13:41:55
여기에서 고객 ID 정보가 있습니다.
the table orders so let's go back to the table orders
13:41:58
우리가 필요한 것은 고객이
over here and here we have the customer id informations and
13:42:02
1 또는 4인 주문입니다.
as we can see we need the orders where the customer is either
13:42:05
그것을 필터링하기 위해
one or four now in order to filter that we're
13:42:08
첫 번째 쿼리로 가서 WHERE 절을 사용하겠습니다.
gonna go to the first query and use the where clause
13:42:12
이렇게 해서 고객 ID를 설정하겠습니다.
like this and say the customer id
13:42:15
이제 우리는 네 개의 값 중 두 개를 가지고 있습니다.
so now since we have like two values one on four we
13:42:19
연산자를 사용하여 목록을 만들어 보겠습니다.
can go and use the operator in so let's go and use
13:42:22
하나와 네 개를 가져가서
the in and let's go and build the list so let's
13:42:25
이제 실행해 보겠습니다. 결과를 확인할 수 있습니다.
go and have the one and four so let's
13:42:28
주문 세부 정보를 확인했습니다.
go and execute it now we can see the results we have the orders but only from the customers one and four
13:42:35
독일의 고객들이 주문한 세부 정보를 확인했습니다.
so with that we have solved the task we have the details of orders made
13:42:39
이것은 나쁜 해결책입니다. 미래에 대한 대안이 필요합니다.
by customers in germany right and now of course this is really
13:42:42
새로운 고객이 생길 경우 추가하는 것이 불편합니다.
bad solution because what about if we get like in the future
13:42:45
각각의 경우에 대해 값을 추가해야 합니다.
new customer you don't want to go and keep adding
13:42:48
새로운 고객을 위해 값을 설정해야 합니다.
here like values and so on for each time you have a
13:42:51
목록을 동적으로 만들어야 합니다.
new customer we want to make the values for this
13:42:54
정적 값이 아닌 동적 값을 필요로 합니다.
list to be dynamic so we don't need a static
13:42:57
서브 쿼리를 사용하여 정보를 검색할 수 있습니다.
value we need like dynamic values and we can use
13:43:00
두 번째 쿼리에서 이미 가지고 있습니다.
the sub queries in order to retrieve those informations right
13:43:04
두 개의 값만 필요합니다.
and we have it already in the second query so let's go back
13:43:07
하나와 네 개의 값을 가져가겠습니다.
to the second query or here we need only those two values
13:43:10
고객 ID를 검색하겠습니다.
one and four that's why we're gonna go to the query and
13:43:13
다시 실행해 보겠습니다.
say okay let's retrieve the customer id
13:43:17
하나와 네 개의 값을 가지고 있습니다.
so let's go and execute it again and with
13:43:20
이 쿼리는 항상 모든 고객 ID를 검색할 수 있습니다.
that we have with the one and four exactly like we have it here in the first query and of course in the future if there's like another customer that come from germany this list is gonna be a little bit
13:43:29
국가가 일치하는 고객 ID를 검색합니다.
longer so this query can always retrieve all the
13:43:32
독일에 해당하는 고객 ID를 가져옵니다.
customer ids that have the country equal
13:43:35
서브 쿼리로 사용하겠습니다.
to germany so now what we're gonna do we're gonna take this as
13:43:38
모든 것을 가져오겠습니다.
a sub query let's go and get everything from
13:43:42
정적 값을 대신하여 사용하겠습니다.
it and now put it instead of those static values so
13:43:45
물론 우리는 이제 오른쪽에 몇 개의 공백을 추가하여 이것이 서브 쿼리임을 이해할 것입니다.
of course we're gonna go now and put few spaces to the right side in order to understand this is a sub query and of course here we don't
13:43:52
여기서는 별칭을 사용하지 않으므로 이제 우리가 하는 것은 결과입니다.
use any aliases so now what we are doing the results
13:43:56
이 서브 쿼리의 결과가 사용될 것입니다.
from this sub query gonna be used in order
13:43:59
우리의 주요 쿼리를 필터링하기 위해서입니다.
to filter our main query so let me just call
13:44:02
주요 쿼리라고 부르겠습니다.
it main query like
13:44:06
이것을 더 작게 만들어 보겠습니다.
this and make this smaller so let's go
13:44:09
실행하고 이제 우리는 동일한 결과를 얻고 있습니다.
and execute it and now we are getting the same results we
13:44:12
우리는 독일에서 온 고객 1과 4의 모든 주문을 얻고 있습니다.
are getting all the orders from only the customers one and four where they come from germany and this informations come
13:44:18
서브 쿼리에서 동적으로 가져오고 있습니다.
dynamically from the sub query and we don't have to worry
13:44:21
독일의 새로운 고객에 대해 걱정할 필요가 없습니다.
about new customers from germany it can be added here automatically
13:44:24
이 쿼리는 항상 독일의 모든 주문을 반환할 수 있습니다.
and this query can always return all the orders from
13:44:28
서브 쿼리의 힘입니다.
germany so this is the power of the sub query together
13:44:31
여러 값을 가질 때 in 연산자와 함께입니다.
with the in operator if you are having like multiple values multiple
13:44:35
이제 작업이 정반대라고 가정해 보겠습니다.
rows so we have solved the task all right now one more thing
13:44:38
고객이 오지 않는 주문의 세부 정보를 보여달라고 합니다.
let's say that the task is exactly the opposite it says show the details of orders made by customers who don't come from So now here there is like two ways in order to do it.
13:44:48
서브 쿼리로 가서, 나라가 독일과 같지 않아야 한다고 말할 수 있습니다.
Either you go to the sub query and you say, you know what? The country should not be equal to Germany.
13:44:54
실행하면 독일이 아닌 모든 고객 ID를 얻을 수 있습니다.
So if you go and execute it, you will get all the customers IDs that are not from Germany.
13:45:00
고객이 독일에서 오지 않는 모든 주문을 얻을 수 있습니다.
and if execute the whole thing you will get all the orders
13:45:03
또는 독일과 같게 유지하지만
where the customers are not from germany so either you do that
13:45:06
전체 논리를 not 연산자를 사용하여 변환합니다.
or you stay with the equal to germany but you go
13:45:09
고객 ID는 이 중 하나와 같지 않아야 합니다.
and convert the whole logic by using the operator not so now we are saying the customer id should not be equal to one of those
13:45:18
그 값을 사용하여 not in 연산자를 사용하고 있습니다.
values so it should not be equal to one or four
13:45:21
이제 실행해 보겠습니다.
and for that we are using the not in operator
13:45:24
고객이 오지 않는 주문을 얻고 있습니다.
so let's go and execute it so now with that we are getting all
13:45:27
단순히 not in 연산자를 사용하여 독일에서.
the orders where the customers don't come from
13:45:30
독일에서 not in 연산자만 사용하여
germany by just using not in operator so
13:45:34
not in과 in 연산자에 대한 모든 내용입니다
that's all about the not in and the in operators all
13:45:37
자, 이제 단계별로 카일이 우리의 쿼리를 어떻게 실행하는지 봅시다
right so now let's see step by step how is kyle execute our query
13:45:40
우리는 고객과 주문이라는 두 개의 테이블을 대상으로 하고 있습니다
so we are targeting two tables the customers and the orders so
13:45:43
첫 번째 단계는 카일이 서브 쿼리를 식별하는 것입니다
the first step is that is kyle gonna go and identify the sub query
13:45:47
그리고 그것을 실행할 것입니다. 여기서 서브 쿼리는
and it's gonna go and execute it so the sub query here
13:45:50
국가를 기준으로 데이터를 필터링하고 있습니다
is filtering the data based on the country so the
13:45:53
쿼리가 실행될 수 있으며 출력에서 우리는 오직
query can be executed and in the output we will get only
13:45:56
두 개의 행을 얻습니다. 이것은 여러 행을 가진 하나의 열입니다
two rows so it is one column with multiple rows this
13:45:59
이것은 행 서브 쿼리이며 이것이 우리의 중간 결과입니다
is the row sub query and this is our intermediate results
13:46:03
여기서 메인 쿼리로 전달될 것입니다. 우리의
where it's gonna be passed to the main query so our
13:46:06
메인 쿼리는 이렇게 생겼습니다. 우리는 주문에서 몇 가지 정보를 선택하고 고객을 기준으로 테이블 주문을 필터링하고 있습니다
main query gonna look like this we are selecting few informations from the orders and we are filtering the table orders based on the customer
13:46:13
고객 ID는 그 값 중 하나여야 합니다
ID where we are saying the customer ID must be
13:46:16
하나 또는 네이므로 서브 쿼리는
one of those values one or four so the sub query is
13:46:19
메인 쿼리를 정보로 지원하고 있습니다
supporting the main query with the informations
13:46:22
필터를 위해 이제 SQL이 모든 것을 갖추면
for the filter now once SQL have everything it's going to go
13:46:26
메인 쿼리를 실행할 것이며 이렇게 될 것입니다
and execute our main query and this is going to be like
13:46:29
다음과 같이 첫 번째 행부터 시작하겠습니다
the following so we will start with the first row and here
13:46:32
고객 ID는 2와 같으므로 값 2는
the customer ID is equal to two so the value two is
13:46:35
1 또는 4와 같지 않으므로 이 행은 최종 결과에서 제외됩니다. 이제 두 번째로 넘어갑니다
not equal to one or four that's why this row will be excluded from the final results now let's move to the second
13:46:42
우리는 여기서 값 3을 가지고 있으며 값 3은
draw we have here the value three and the value three
13:46:45
이 값 중 하나와 같지 않으므로 이
is not equal to one of those values that's why this
13:46:49
값도 실패하게 될 것입니다. 그래서 우리는 그것을 갖지 않을 것입니다
value is going to be as well failing so we will not have it
13:46:52
출력에서 그리고 이제 다음으로 넘어갑니다
at the output and then it's going to go to the next one now
13:46:55
이번에는 고객 ID가 1이며 그것은 같고
this time the customer id is one and it is equal
13:46:58
이 값 중 하나와 같으므로
to one of those values it's equal to one so we have
13:47:01
일치하므로 이 행이 포함됩니다.
a match that's why this row will be included to
13:47:04
결과와 다음 행도 마찬가지입니다. 고객 ID가 1이므로
the results and the same thing for the next row because we have the customer id one and so on now after sql checking
13:47:11
모든 고객 ID가 목록 1 또는 4에 있는지
all those customer ids whether they are in the list one or four
13:47:14
여기에서 모든 최종 결과를 얻습니다.
we will get the final results where we have here all
13:47:17
고객 ID가 1 또는 4인 주문입니다.
the orders where the customer id either one or four
13:47:20
이렇게 SQL이 n 연산자를 실행했습니다.
so this is how sql executed the n operator
13:47:23
서브 쿼리를 사용하여
using the sub queries okay
13:47:29
이제 any 연산자로 넘어갑니다.
so now moving on to the any operator so we can go
13:47:32
값을 비교하기 위해 any 연산자를 사용합니다.
and use the any operator in order to compare value if
13:47:35
목록의 어떤 값과 일치하는지 확인합니다.
it matches any value from a list so that That means we can go and use it in order to check whether a condition is true for at least one of the values in a list.
13:47:46
서브 쿼리의 구문을 빠르게 확인해 보겠습니다.
Okay, so now let's check quickly the syntax of the subquery using the any and all operators.
13:47:50
where 절 안에 서브 쿼리를 사용할 수 있습니다.
So as we learned before, we can go and use a subquery inside the where clause in order to filter the main query using like the comparison operators like here less than.
13:48:00
any 연산자의 구문은 비교 연산자를 사용하는 것입니다.
Now the syntax of the any operator is that you're going to go and use the comparison operator.
13:48:06
변환 연산자 뒤에 all 키워드를 넣습니다.
And after that, immediately you use the keyword any. And for the all operator, it's going to be exactly the same.
13:48:12
이제 다음 작업을 연습해 보겠습니다.
Where you're going to go and put after the conversion operator, the keyword all. So the syntax is very simple. We just add those keywords.
13:48:19
여성 직원의 급여가 남성 직원의 급여보다 큰 경우입니다.
So let's practice using the following task. Find female employees whose salaries are greater than the salaries of any male employee.
13:48:28
남성과 여성 간의 급여를 비교하고자 합니다.
So that means we want to go and compare the salaries between the male and female.
13:48:32
단계별로 해결해 보겠습니다.
And specifically, we are searching for female employees whose salary is greater than at least one male employee.
13:48:39
예를 들어, 직원 ID와 이름, 성별, 급여를 선택합니다.
So let's solve it step by step. Let's go and start selecting few informations.
13:48:43
이제 실행해 보겠습니다.
Like, for example, the employee ID and first name, gender, salary from the table, sales, employees.
13:48:55
남성과 여성 간의 데이터를 비교하고자 합니다.
So let's go and execute it. So now we have like five employees. Three of them are male and two are female.
13:49:01
첫 번째는 성별로 데이터베이스를 필터링하는 것입니다.
So now since we want to compare the data between male and female, let's go and create two queries.
13:49:07
여성을 위한 첫 번째 쿼리입니다.
The first one is filtering the database on the gender. So the first one is for the female.
13:49:13
이 정보를 제거할 수 있습니다.
So we can go and remove this information over here. Let me just make this a little bit smaller and zoom out.
13:49:20
두 번째 쿼리는 정반대가 될 것입니다.
And the second query, it's going to be the exact opposite.
13:49:24
남성 직원 정보를 가져오겠습니다. 그러니 이를 무시합시다.
Let's go and get employee information for the male. So let's go and excuse it.
13:49:30
이제 첫 번째 결과는 여성 직원이고 두 번째는.
Now the first results are the female employees and the second one are.
13:49:33
이제 첫 번째 결과는 여성 직원이고 두 번째는 남성 직원입니다. 이제 출력에서 무엇이 필요할까요?
So now for the first result is for the female employees and the second one is for the male employees. So now what do we need in the output?
13:49:41
여성 직원이 필요합니다. 이는 우리의 주요 쿼리가 될 것입니다.
We need the female employees. That means this is going to be our main query.
13:49:47
여성 직원에 집중하고 남성 직원은 필터로만 사용할 것입니다. 그리고 우리는 무엇이 필요할까요?
So we are focusing on the female employees and we are using the male employees only as a filter. And what do we need?
13:49:54
급여 정보만 필요합니다. 그래서 이렇게 준비할 수 있습니다.
We need only the salary information. That's why we can prepare it like this.
13:49:59
모든 것을 한 줄로 정리하겠습니다.
I will just put everything in one line to make
13:50:03
명확하게 하기 위해 이것이 우리의 서브 쿼리가 될 것입니다.
it clear so this is going to be our sub query so
13:50:06
이제 우리는 메인 쿼리로 작업할 것입니다.
now we're going to go and work with the main query where we're going to add one
13:50:09
더 많은 필터를 추가하여 데이터를 필터링할 것입니다.
more filter where we're going to filter the data based on
13:50:12
급여에 대해 말할 것입니다.
the salary right so we're going to say if the salary
13:50:16
급여가 더 크다고 말할 것입니다.
is greater than and now we need the values from the sub query right so this is our sub query we're going to put it like this and don't
13:50:24
서브 쿼리에서 값을 가져와야 합니다.
forget about the parentheses at the start and at the end and
13:50:27
여기서 두 개의 쿼리를 유지하고 싶습니다.
i would like still to have those two queries so
13:50:31
이제 실행해 보겠습니다.
let's go and execute it and now we will get an error and
13:50:34
그것은 우리의 서브 쿼리가 여러 개의 행을 반환하기 때문입니다.
that's because our sub query is returning multiple
13:50:38
비교 연산자를 사용하고 있습니다.
rows and this is not acceptable we are using the comparison
13:50:41
이 문제를 해결하기 위해 논리 연산자를 사용할 수 있습니다.
operator and sql expect from the sub query to have scalar sub query so only one single value but now in order to solve
13:50:50
모두 또는 아무거나 사용할 수 있습니다.
this issue we can go and use the logical operators either
13:50:53
여성 직원의 급여가 최소한 한 명의 남성 직원보다 높아야 합니다.
all or any so now since we are saying it's enough for
13:50:56
우리는 'any' 연산자를 사용할 것입니다.
the salary of the female employee to be higher than at least one
13:51:00
비교 연산자 뒤에 가겠습니다.
male employee we will go with the operator any
13:51:03
키워드 'any'를 사용하고 다시 실행하겠습니다.
so let's go after the comparison operator and
13:51:07
출력에서 한 명의 여성 직원만 얻었습니다.
have the keyword any and let's go and execute it again
13:51:10
이제 출력에서 보시다시피 우리는 한 명의 여성 직원만을 얻었고 그녀의 급여는 남성 직원 중 한 명보다 높습니다. 그래서 그녀의 이름을 가져오겠습니다.
and now as you can see in the output we got only one female employee where her salary is higher to one of those male employees so let me just go and get the first name
13:51:20
두 번째 쿼리에서도 마찬가지입니다.
as well from the second query
13:51:23
이렇게 하면 이제 급여를 비교할 수 있습니다.
just to have it like this so now if you go and compare the salary of
13:51:26
메리의 급여는 마이클보다 높지 않지만
mary it is not higher than michael but it
13:51:29
프랭크와 케빈보다 높습니다. 그리고 우리는
is higher than frank and kevin and since we are
13:51:32
any 연산자를 사용하고 있으므로 메리의 급여가
using the any operator it's enough for mary to
13:51:35
이 값 중 하나보다 높으면 충분합니다. 이 경우
have salary higher to one of those values in this case it's
13:51:39
프랭크와 케빈 모두보다 높고 조건이 충족됩니다.
higher than both frank and kevin and the condition is fulfilled
13:51:42
그래서 우리는 메리와 다른 여성 직원을 얻고 있습니다. 누가 더 있는지 확인해 보겠습니다. 우리는 캐롤이 있습니다.
that's why we are getting the mary and the other female let me just check who do we have else so we have carol his salary
13:51:49
그녀의 급여는 모든 남성 직원의 급여보다 낮습니다.
is less than all the salaries of the male employees
13:51:52
그래서 최소한 하나의
so it must be at least higher than one of the
13:51:55
남성 직원보다 높아야 합니다. 그래서 우리는 이 작업을 해결했습니다.
male employees so with that we have solved the task right all
13:51:58
그렇습니다. 이제 우리는 유사한 또 다른 연산자를 가지고 있습니다. 우리는 그것을
right so now we have another operator that is similar we call it
13:52:02
all 연산자라고 부릅니다. 우리는 그것을 사용하여
the all operator we can go and use it in order to compare a
13:52:05
값을 비교할 수 있습니다. 모든 값과 일치하는지
value if it matches all values in
13:52:08
확인해야 합니다. 목록의 모든 값이 조건이 참인지 확인해야 합니다. 조금 복잡하게 들릴 수 있지만
a list so that means we can go and use it if we need to check whether a condition is true every value in a list i know that might sound a little bit
13:52:17
걱정하지 마세요. 예제를 통해 설명하겠습니다. 이제
complicated but don't worry about it we can have examples now let's say that
13:52:20
우리의 작업은 급여가
our task says find female employees whose salary
13:52:23
모든 남성 직원의 급여보다 높은 여성 직원을 찾는 것입니다.
are greater than the salaries of all
13:52:27
그래서 이제 조건이 더 제한적입니다. 메리는 이제
male employees so that means now the
13:52:30
모든 남성 직원보다 높은 급여를 가져야 하며, 모든 남성 직원의 급여보다 높아야 합니다.
condition is more restrictive mary should now has
13:52:33
모든 남성 직원보다 높은 급여이므로 남성 직원들로부터 받은 모든 값보다 높아야 합니다.
a salary higher than every male employee so it should be higher to all those values that we have from the male employees and
13:52:42
메리는 마이클보다 낮은 급여를 받고 있으며,
course in this scenario it's not because we have michael
13:52:45
이는 문제입니다. 메리는 더 높은 급여를 가져야 합니다.
mary has less salaries than michael and this
13:52:49
모든 사람보다 높아야 하므로 시도해 보겠습니다.
is a problem because mary should has higher salary
13:52:52
모두보다 더 높은 급여를 받아야 하므로 가서 시도해 보자.
than everyone so let's go and try it if i go and
13:52:55
여기 모든 것을 작성하고 가서 실행해 보자.
write here all and let's go and execute it you
13:52:58
우리는 이 요구 사항을 충족하는 결과를 찾지 못할 것이다.
will see we will not find any results that fulfill this
13:53:01
여성 직원의 급여가 모든 남성 직원보다 높지 않기 때문이다.
requirement so we don't have any female employee who her salary
13:53:04
우리는 데이터 세트가 매우 작기 때문에 SQL의 서브 쿼리에서 모든 및 어떤 연산자를 사용하는 방법을 설명했다.
is higher than all male employees and that's because we have a very small data sets so this is how we use all and any operators in our sub queries in SQL.
13:53:14
좋아. 그래서 우리는 다양한 위치와 절에서 서브 쿼리를 사용하는 방법에 대해 거의 모든 것을 다뤘다.
All right. So with that, we have covered almost everything about how to use the sub queries in different locations and clauses.
13:53:21
하지만 우리는 존재 연산자에 대해 이야기하지 않았다.
But we didn't talk about the exist operator.
13:53:23
그것은 서브 쿼리에서 매우 중요한 개념을 이해하기를 원하기 때문이다.
And that's because I would like you to understand a very important concept in the sub queries, where we have two different types of the sub queries based on the dependencies, the non correlated and correlated sub queries.
13:53:35
우리는 의존성에 따라 두 가지 유형의 서브 쿼리가 있다.
And after that, we're going to go back to the exist operator.
13:53:43
그 후에 우리는 존재 연산자로 돌아갈 것이다.
All right, friends, so now we come to the part where it is a little bit complicated about the sub queries.
13:53:47
좋아, 친구들, 이제 서브 쿼리에 대해 조금 복잡한 부분에 도달했다.
Now we're going to talk about the dependencies between the sub query and the main query.
13:53:52
이제 우리는 서브 쿼리와 메인 쿼리 간의 의존성에 대해 이야기할 것이다.
So far, all the examples and the sub queries that we have learned were a non correlated sub query.
13:53:59
지금까지 우리가 배운 모든 예제와 서브 쿼리는 비상관 서브 쿼리였다.
A non correlated sub query means a sub query that can run independently from the main query.
13:54:05
비상관 서브 쿼리는 메인 쿼리와 독립적으로 실행될 수 있는 서브 쿼리를 의미한다.
So that means the sub query is like standalone query. But in the other hand, we have the exact opposite type of the subquery.
13:54:12
즉, 서브 쿼리는 독립적인 쿼리와 같다.
We have the correlated subquery. A correlated subquery is a subquery that relies on values from the main query for each row it processes.
13:54:24
반면에 우리는 상관 서브 쿼리라는 정반대의 유형이 있다.
So that means the subquery here is completely depending on the main query. So I know this might be a little bit confusing.
13:54:31
상관 서브 쿼리는 처리하는 각 행에 대해 메인 쿼리의 값에 의존하는 서브 쿼리이다.
That's why we can have the following very simple sketch in order to exactly understand how this works.
13:54:37
즉, 여기서 서브 쿼리는 메인 쿼리에 완전히 의존한다.
So as usual, we have a database tables. And now this time, SQL is going to go and start executing the main query first.
13:54:44
그래서 이 부분이 조금 혼란스러울 수 있다는 것을 알고 있다.
This is the first thing happens. So the main query is going to go and query the database in order to get results.
13:54:51
그래서 우리는 다음과 같은 간단한 스케치를 통해 이 작업이 어떻게 작동하는지 정확히 이해할 수 있다.
And SQL is going to process the results row by row. So now what can happen?
13:54:56
따라서 일반적으로 데이터베이스 테이블이 있다.
The main query is going to go and pass the first row information
13:55:00
이제 SQL은 메인 쿼리를 먼저 실행하기 시작할 것이다.
to the sub query So now the sub query gonna get
13:55:03
이것이 첫 번째로 발생하는 일이다.
the data from the main query So it's gonna execute the
13:55:06
메인 쿼리는 결과를 얻기 위해 데이터베이스를 쿼리할 것이다.
sub query So here the sub query can return a
13:55:09
SQL은 결과를 행별로 처리할 것이다.
value like for example one So here it's very important to understand that that's now the SQL or the main query gonna check Is there a result from the sub query and this example?
13:55:20
네, 결과가 있습니다. 여기서 SQL은 첫 번째 행에 대한 서브쿼리의 출력을 확인하고 있습니다.
Yes, we have a results So here SQL is checking the output for the subquery for the first row.
13:55:27
결과가 있다면, SQL은 최종 결과에서 해당 행을 반환할 것입니다.
So if there is a result, SQL gonna go and return the row in the final result.
13:55:32
이것은 첫 번째 행에 대해서만 전체 반복이 발생한 것입니다.
So this is the whole iteration happened only for the first row.
13:55:36
이제 두 번째 행에 대해 처음부터 전체 프로세스를 다시 진행할 것입니다.
So we're gonna process the whole thing again from the start for the second row.
13:55:41
주 쿼리는 데이터베이스에서 두 번째 행을 가져와 서브쿼리에 전달할 것입니다.
So the main query gonna get the second row from the database and it gonna pass it to the subquery.
13:55:47
서브쿼리가 이 새로운 정보를 받으면
once the subquery gets this new information sql
13:55:50
서브쿼리를 다시 실행할 수 있습니다.
can go and execute the subquery once again
13:55:53
이제 서브쿼리를 실행한 후를 가정해 보겠습니다.
so now let's say that after executing the subquery
13:55:56
결과가 없으므로 서브쿼리는
there were no results so the subquery is
13:55:59
실행 후 아무것도 반환하지 않으므로
not returning anything after the execution so
13:56:02
이제 SQL과 주 쿼리가 확인할 수 있는 것은
now what can happen sql and the main query gonna check
13:56:06
서브쿼리에서 결과가 없다는 것이며, 이는 이 행이 제외되어야 함을 의미합니다.
okay there is no result from the subquery and this means this row should be excluded and not presented
13:56:13
출력에서 이 행을 볼 수 없게 됩니다.
in the output so we will not see this row at the output
13:56:16
보시다시피 SQL은 서브쿼리를 실행하고 있습니다.
so as you can see sql is executing the sub query
13:56:19
두 번째 행에 대해 다시 한 번
once again for the second row so
13:56:22
이것은 우리가 행이 있는 한 계속 발생할 것입니다.
this will keep happening as long as we have row for example
13:56:26
또 다른 행이 있으므로 주 쿼리는 이를 서브쿼리에 전달할 것입니다.
we have another row the main query gonna pass it to the sub query
13:56:29
서브쿼리는 세 번째로 실행될 것이며
the sub query gonna be executed for the third time and
13:56:32
서브쿼리의 결과는 하나가 될 것이며, 같은 일이
the result of the sub query is gonna be one so the same thing
13:56:35
SQL이 확인할 것이며, 값이 있으므로 이 행은 최종 결과에 포함될 수 있습니다.
gonna happen sql gonna check it okay we have a value so this row is allowed to be in the final results
13:56:42
각 행에 대해 반복될 것입니다.
and so on the cycle gonna keep repeating for each
13:56:45
주 쿼리에서 검색될 행에 대해
row that's gonna be retrieved from the main query and
13:56:49
모든 행을 처리한 후 최종 결과를
once we have processed all the rows the final result can
13:56:52
출력에 제시할 수 있습니다.
be presented in the output so what we have understood so far
13:56:55
상관 서브 쿼리는 항상 의존합니다.
the correlated sub queries is always depending
13:56:58
주 쿼리에 따라 상관된 서브쿼리가 항상 실행됩니다.
on the main query and the sub query gonna be executed for each row that we're gonna get from the main query so in this
13:57:06
예를 들어, 우리는 네 개의 행이 있고 서브쿼리가 실행됩니다.
example we have four rows and the subquery is executed
13:57:10
네 번 실행되므로 이것이 상관된 서브쿼리입니다.
four times so this is how the correlated subquery
13:57:13
작동 방식이 조금 더 복잡합니다.
works it's a little bit more complicated than the
13:57:16
비상관 서브쿼리는 정말 간단합니다.
non-correlated subquery the non-correlated subquery
13:57:20
먼저 서브쿼리가 데이터베이스를 한 번만 실행합니다.
are really straightforward so first the subquery gonna
13:57:23
그 결과는 메인 쿼리에서 사용될 중간 결과와 같습니다.
go and execute the database only once and the output of the subquery gonna be like an intermediate results that gonna be used
13:57:31
메인 쿼리가 중간 결과를 쿼리합니다.
from the main query so the main query gonna go and
13:57:34
결과적으로 최종 결과를 얻게 됩니다.
query the intermediate results and in the output
13:57:37
비상관 서브쿼리의 실행 결과를 보면 간단합니다.
we're gonna get the final results so as you can see in the execution
13:57:40
반복이 없고 모든 것이 한 번만 실행됩니다.
of the non-correlated subquery it is straightforward there
13:57:44
비상관 서브쿼리는 메인 쿼리와 완전히 독립적입니다.
is no iterations everything gonna be executed only once
13:57:47
서브쿼리는 한 번만 실행되고 그 후에 SQL이 메인 쿼리를 실행합니다.
so now if you compare them side by side you can see that with the non-correlated subquery it is completely independent from the main query so that means the subquery gonna be executed
13:57:58
서브쿼리의 결과를 사용하여 메인 쿼리를 한 번만 실행합니다.
only once and after that sql gonna go and s will execute
13:58:02
서브쿼리의 결과를 사용하여 메인 쿼리를 실행합니다.
the main query only once using the result from
13:58:05
왼쪽의 서브쿼리는 여러 번 실행됩니다.
the sub query but on the left side the sub query
13:58:08
메인 쿼리에 따라 완전히 의존합니다.
is going to be executed multiple times and it is completely depending
13:58:11
각 행에 대해 반복이 발생합니다.
on the main query and there is like an iteration for
13:58:15
모든 행이 처리될 때까지 프로세스가 반복됩니다.
each row that's going to be retrieved from the main
13:58:18
상관된 서브쿼리와 비상관 서브쿼리가 SQL에서 작동하는 방식입니다.
query so the process is going to be cycling until all the rows are processed and this is exactly how the correlated and the non-correlated sub queries work in SQL.
13:58:28
자, 이제 다음 작업을 해봅시다.
Alright, so now let's have the following task and it says show all customer details and find the total orders of each customer.
13:58:35
우리는 이미 이 작업을 해결했습니다.
We have already solved this task and you know in SQL we don't have only one query in order to solve something.
13:58:41
우리는 여러 가지 방법으로 이를 수행할 수 있습니다.
We have multiple ways in order to do it. So we solved this task before using the sub queries and the joins.
13:58:47
이제 서브쿼리를 사용하여 이 작업을 해결하겠습니다.
Now we're going to go and solve this task using sub query in the select clause and as well using the correlated subqueries.
13:58:55
다시 한 번, 단계별로 진행하겠습니다.
So again, let's do it step by step. It's very simple. First, we need all the customer details.
13:59:01
그래서 우리가 배운 대로, sales customers에서 star를 선택하세요.
So as we learned, select star from sales customers.
13:59:06
이걸 실행하면 모든 고객의 세부 정보를 얻을 수 있습니다. 이제 각 고객의 총 주문 수를 찾아야 합니다.
So if you execute it, you will get all the details of all customers. Now we need to find the total number of orders of each customer.
13:59:14
이제, 우리는 이것을 간단한 쿼리를 사용하여 해결했습니다.
Now, before we have solved this using a simple query where we
13:59:17
count 함수를 group by와 함께 사용했지만, 이번에는 조금 다르게 할 수 있습니다. 그래서 select count 쿼리를 작성해 보겠습니다.
have used the count function together with a group by, but this time we can do it a little bit different so let's go and write query saying select count
13:59:27
sales 테이블에서 star를 선택합니다.
star from the table sales
13:59:31
이제 실행해 보겠습니다.
orders so now let's go and execute it
13:59:34
그렇게 하면 총 주문 수를 얻을 수 있습니다. 이제 이 서브 쿼리를 가져와서 select에서 사용해 보겠습니다. 스칼라 서브 쿼리로 사용하고 있습니다.
with that we have the total number of orders so let's go and take this sub query and use it in the select so we are using it as as a scalar sub query.
13:59:44
여기에 넣어 보겠습니다. 이것이 기본 쿼리입니다.
So let's just put it over here. And this is the main query.
13:59:49
서브 쿼리로 만들기 위해서 우리는 무엇을 해야 할까요? 괄호를 사용하고 총 판매량을 말할 것입니다.
And in order to make this as a sub query, what are we gonna do? We can have the parentheses and we're gonna say that total sales.
13:59:56
이제 실행해 보겠습니다. 이제 보시다시피, 우리는 모든
So now let's go and excuse it. So now as you can see, we have here all
14:00:00
고객에 대한 세부 정보와 총 판매량을 가지고 있지만
details about the customers and we have the total sales but we
14:00:03
한 가지 문제가 있습니다. 우리는 단순히 총 주문이 필요하지 않고
have one issue we don't need just the total order we need the
14:00:06
각 고객의 총 주문이 필요합니다. 각 고객은
total orders for each customer so each customer has
14:00:09
서로 다른 총 주문을 가지고 있으므로
different total orders so we cannot have like the
14:00:12
고객별로 그룹화할 수 없습니다.
following setup we cannot say group by customer
14:00:15
그 다음 고객 ID가 있어야 합니다.
id and then you have like here the customer
14:00:18
그래서 실행하면 문제가 발생합니다. 이 서브 쿼리를 실행하면 여러 행이 나옵니다.
id and so on so if you go and execute it
14:00:22
여러 열이 나오므로 테이블 쿼리가 됩니다.
you will get a problem and that's because if you go and execute this sub query over here you will get like multiple rows
14:00:28
이런 종류의 서브쿼리는 select에서 사용할 수 없습니다.
and multiple columns so you have like a table query and
14:00:32
오직 스칼라 서브쿼리만 있어야 합니다.
this type of subquery is not allowed to be used in the select
14:00:35
그래서 우리는 그렇게 할 수 없습니다.
clause right we have to have only scalar subquery
14:00:38
그래서 모든 것을 제거해야 합니다.
so that's why we cannot do that so
14:00:41
하지만 우리는 상관 서브쿼리를 사용하여 해결할 수 있습니다.
we have to go and remove all those stuff but
14:00:45
이제 서브쿼리는 기본 쿼리와 완전히 독립적입니다. 상관관계를 만들기 위해서 우리는 연결할 것입니다.
we can go and solve it using the correlated subqueries
14:00:48
테이블에 대한 별칭을 제공할 것이고, 조건을 말할 것입니다.
so now the subquery is completely independent from the main query so in order to correlate it what we're gonna do we're gonna go and connect it so i'm gonna give
14:00:58
테이블의 별칭을 주고
aliases for the tables and i'm gonna say where
14:01:01
고객 ID가 같음을
the customer id equal
14:01:04
주 쿼리의 고객 ID에
to the customer id from the main query from
14:01:07
고객과 다시 연결하고
the customers so again we are connecting the customer
14:01:10
주문 테이블의 고객 ID와
id from the orders in the sub query with
14:01:13
주 쿼리에서 가져온 고객 ID에
the customer id from the table customers that
14:01:17
이제 특정 고객에 대해서만 실행하겠다고 말하고 있습니다.
comes from the main query so now we are saying okay execute this only for a specific customer not for the whole table so let's go and executed.
14:01:27
이제 출력에서 각 고객의 총 매출을 볼 수 있습니다.
So now in the output, we have the total sales for each customer and we don't have here like the total sales in the whole table orders.
14:01:34
각 행에 대해 서브쿼리가 실행되기 때문입니다.
And that's because what is happening for each row, the subquery going to be executed.
14:01:39
고객 번호 1에 대해 이 쿼리가 이렇게 실행됩니다.
So for the customer number one, this query going to be executed like this.
14:01:44
고객 ID가 1인 주문의 총 수를 세십시오.
Count the total number of orders where the customer ID equal to the one. So let me just show you what this means.
14:01:51
여기서 이 숫자를 제거하고
If I go and remove this from here and just put the number
14:01:54
숫자 1을 넣으면
one so if i go and execute this you
14:01:57
고객 ID 1이 세 개의 주문을 가지고 있음을 볼 수 있습니다.
will see the customer id one has three orders and
14:02:01
각 고객에 대해 같은 일이 발생할 수 있습니다.
they just put it back and execute and the same
14:02:04
각 행에 대해 이 서브쿼리가 실행될 수 있습니다.
thing can happen for each customer so for each customer for
14:02:07
주 쿼리에서 가져온 고객 ID로 필터링할 수 있습니다.
each row this sub query can be executed and
14:02:10
이것은 이 작업을 해결하는 또 다른 방법입니다.
it can be filtered with the customer id that comes from the main
14:02:13
비상관 서브쿼리와의 차이점을 요약해 보겠습니다.
query so this is another way in how to solve this task
14:02:16
상관 서브쿼리를 사용하여
using the correlated sub queries so now let's summarize and understand quickly what they are the differences between the non-correlated
14:02:23
비상관 서브쿼리는 주 쿼리와 독립적입니다.
and the correlated sub queries so now if you are talking about the definition
14:02:26
주 쿼리와 독립적인 서브쿼리입니다.
then non-correlated sub query are sub queries
14:02:29
상관 서브쿼리는 주 쿼리에 의존합니다.
that are independent of the main query but
14:02:32
주 쿼리에 의존합니다.
in the other hand that correlated sub queries are dependent
14:02:36
비상관 서브쿼리는 단독으로 실행될 수 있습니다.
of the main query and now if you are talking about the execution
14:02:39
비연관 서브쿼리는 오직
the non-correlated sub queries can be executed only
14:02:42
한 번 실행될 수 있고 그 결과는 메인 쿼리에 사용됩니다.
once and then the results gonna be used by the main query
14:02:45
그러나 연관 서브쿼리는 서브쿼리가
but by the correlated sub queries the sub query
14:02:48
우리가 가진 각 행에 대해 실행됩니다.
gonna be executed for each row that we have from the
14:02:51
메인 쿼리에서 우리가 가진 각 행에 대해
main query and as we learned for the non-correlated subqueries
14:02:55
우리는 그것을 독립적으로 실행할 수 있으므로
we can execute it on its own so we can go and
14:02:58
선택하고 실행할 수 있지만 연관 서브쿼리는
select it and execute it but the correlated subqueries
14:03:01
독립적으로 실행할 수 없으므로 항상 전체를 실행해야 합니다.
we cannot execute it on its own so we have to execute
14:03:04
항상 전체를 실행해야 하며 어떤 것이 더 쉬운지
always the whole thing and if you are talking about which one
14:03:07
비연관 서브쿼리가 더 쉽다는 것은 분명합니다.
is easier i think it's clear that the non-correlated subqueries
14:03:11
비연관 서브쿼리는 작성하고 읽기 쉽고 반면에
are easier to write and to read and in the other hand the correlated subqueries are harder to read and as
14:03:17
연관 서브쿼리는 읽기 어렵고
it's complex now we are talking about the performance of the
14:03:20
복잡합니다. 이제 우리는 성능에 대해 이야기하고 있습니다.
database since the correlated subquery is going to be executed
14:03:23
연관 서브쿼리는 한 번만 실행되므로
only once this of course is going to lead you to have a better performance
14:03:26
더 나은 성능을 가져올 것입니다.
because things are really straightforward and not complicated but
14:03:29
사실이 간단하고 복잡하지 않지만
in the other hand with the correlated subquery there is more effort
14:03:33
연관 서브쿼리는 더 많은 노력이 필요합니다.
because sql has to check a lot of stuff and the subquery is going to be executed many times so the non-correlated subqueries are faster we use the non-correlated subqueries in order to do static comparison.
14:03:45
SQL이 많은 것을 확인해야 하고 서브쿼리가 여러 번 실행되므로
So the value that we are getting from the simple query is executed only once and we will get only one static value in order to use it for filtering and so on.
14:03:54
비연관 서브쿼리가 더 빠릅니다. 우리는 비연관 서브쿼리를 사용하여
But in the other hand, we use correlated subqueries in order to do row by row comparison.
14:03:58
정적 비교를 수행합니다.
And since we don't have here a static value, each time the subquery gonna run, we can have different results.
14:04:03
그래서 우리가 단순 쿼리에서 얻는 값은 한 번만 실행되고
This can add more dynamic to the filters and we don't have a static value.
14:04:07
필터링 등에 사용할 정적 값 하나만 얻습니다.
so those are the big differences between the non-correlated and the
14:04:10
반면에 우리는 행별 비교를 위해 연관 서브쿼리를 사용합니다.
correlated subqueries all right so now after we understood the
14:04:13
여기에는 정적 값이 없기 때문에 서브쿼리가 실행될 때마다
concept of the two types correlated and non-correlated subqueries
14:04:17
다른 결과를 얻을 수 있습니다.
we're gonna go now and cover the last operator for
14:04:21
서브쿼리에서 exists가 있으니, 무엇이
the subqueries we have the exists so what is
14:04:24
exists 연산자입니다.
exist operator all right
14:04:29
SQL에서 매우 흥미로운 연산자 기능에 대해 이야기할 것입니다.
so now we're gonna talk about a very interesting operator function in
14:04:32
어떤 시나리오에서는
sql that exists so now in some scenarios as
14:04:35
하나의 테이블에서 데이터를 쿼리할 때
you are querying the data from one table you would need to go
14:04:38
이 테이블의 행이
and check whether the rows of this table exist in
14:04:41
다른 테이블에 존재하는지 확인해야 합니다.
another table so that means you are checking like the existence
14:04:45
이 시나리오에서는 서브쿼리를 함께 사용합니다.
of your rows in different table and exactly
14:04:48
exists 연산자와 함께 사용합니다.
in this scenario we go and use sub queries together
14:04:51
exists 연산자는 매우 간단합니다.
with the operator exists so the exist operator is
14:04:54
서브쿼리가 결과를 반환하는지 확인합니다.
very simple it's just simply check whether the sub
14:04:57
이제 상관 서브쿼리의 구문을 이해해 봅시다.
query returns any results and your rows all right
14:05:00
exists 연산자를 사용하여, 약간 복잡할 수 있습니다.
so now let's understand the syntax of the correlated sub queries using
14:05:04
단계별로 진행할 것이니 걱정하지 마세요.
the exist operator this can be a little bit complicated
14:05:07
주 쿼리에서 쉬운 것부터 시작하겠습니다.
but we're gonna do it step by step don't worry about it so let's
14:05:10
간단한 선택을 하겠습니다.
start with the easy stuff in the main query we're gonna go and write
14:05:13
테이블 2에서 몇 개의 열을 선택합니다.
a simple select we are selecting few columns from
14:05:17
테이블 2의 모든 데이터를 필요로 하지 않습니다.
the table 2 and now we don't need all the data from table
14:05:20
where 절을 사용하여 테이블을 필터링합니다.
2 we want to filter the table using the where clause
14:05:23
where 절 이후에 즉시
now what we're gonna do after the where clause we're gonna write immediately
14:05:26
exists라는 또 다른 키워드를 작성할 것입니다.
another keyword called exists so we don't here specify
14:05:29
exists 전에 어떤 열도 지정하지 않습니다.
any column before they exist like we have done in the comparison
14:05:32
값을 기준으로 필터링하지 않기 때문입니다.
operator or the in operator we don't need that because we
14:05:35
논리를 기준으로 필터링하기 때문입니다.
are not filtering based on a value we are filtering based on
14:05:38
즉시 exist라는 단어가 필요합니다.
the logic that's why we have the word exist immediately and now directly after the exist we're gonna go and define the subquery like this So we're going to start saying select one from the table number one.
14:05:50
글쎄, 필수는 아니지만 여기서 하나를 지정하는 데 매우 일반적으로 사용됩니다.
Well, it is not like a must or something, but it is very commonly used to specify here a one.
14:05:56
우리는 테이블 1에서 정보를 검색하기 위해 서브쿼리를 사용하지 않습니다.
We are not using the subquery in order to retrieve information from the table one.
14:06:00
우리는 서브쿼리가 값을 반환할지 여부를 테스트하고 있습니다. 반환 값은 신경 쓰지 않습니다.
We are just testing whether the subquery going to return a value or not. And we don't care about the return value.
14:06:07
하나일 수도 있고, 열일 수도 있고, 무엇이든 될 수 있습니다. 그래서 우리는 검색된 데이터에 신경 쓰지 않습니다.
It could be one. It could be column. It could be anything. So we don't care about the data that is retrieved.
14:06:13
검색된 데이터에 신경 쓰지 않습니다. 우리는 서브쿼리가 반환하는지 여부만 신경 씁니다.
retrieved we are just care whether the subquery is returning
14:06:16
그래서 우리는 여기서 어떤 값을 작성합니다.
anything so that's why we go and write any value like
14:06:19
여기서 하나를 작성합니다. 이제 우리는 아직 끝나지 않았습니다.
here a one so now we are not done yet this subquery
14:06:22
이 서브쿼리는 메인 쿼리와 연결되지 않았습니다.
is not yet connected to the main query we
14:06:25
우리는 서브쿼리에서 테이블 1의 ID와 메인 쿼리의 ID를 연결해야 합니다.
have somehow to go and connect them together and we can do that using
14:06:29
메인 쿼리의 외부 쿼리와 연결해야 합니다.
the where clause where we go and connect the id from the table one from the subquery with the id from the
14:06:36
이렇게 하면 서브쿼리 간의 관계를 구축하게 됩니다.
outer query from the main query and with that we are
14:06:39
서브쿼리와 메인 쿼리 간의 관계를 구축합니다.
building like a relationship between the sub query
14:06:43
이제 서브쿼리는 메인 쿼리의 값에 의존하고 있습니다.
and the main query so with that the sub query
14:06:46
여기서 우리는 테이블 2의 ID를 가지고 있습니다.
is now depending on the values from the main
14:06:49
메인 쿼리에서 필터링됩니다.
query because here we have the table 2 id so the ids
14:06:52
서브쿼리입니다. 이것이 상관된 서브쿼리의 구문입니다.
from the main query gonna filter the
14:06:55
서브쿼리입니다. 이것이 exists를 사용하는 구문입니다.
sub query so this is the syntax of correlated
14:06:59
메인 쿼리에 완전히 의존합니다.
sub queries using the exists where we are making the subquery
14:07:02
이제 각 행이 어떻게 작동하는지 이해해 봅시다.
depending totally on the main query so let's
14:07:06
메인 쿼리에서 가져온 각 행에 대해 트리거됩니다.
understand how exist works so now for each row
14:07:09
서브쿼리의 실행을 유발합니다.
that we have from the main query it's gonna trigger
14:07:12
이 서브쿼리는 이 행을 평가하는 데 도움이 됩니다.
and cause an execution of the subquery this
14:07:15
이 행을 평가하는데, 서브쿼리가 아무것도 반환하지 않으면 결과가 없습니다.
subquery gonna help us to evaluate this row so we are testing
14:07:18
메인 쿼리에서 제외됩니다.
this row now if the subquery doesn't return anything so there is no results what can happen the row that we are evaluating
14:07:26
최종 결과에서 제외됩니다.
from the main query will be excluded from the
14:07:29
최종 결과에서 제외되지만 이제 다른 한편으로는
final results but now in the other hand if the sub
14:07:32
서브 쿼리가 값을 반환하고 있으므로 우리는 일종의
query is returning the value so we have like some kind of
14:07:35
결과가 될 것이고, 우리가 평가하고 있는 이 행은
results then this row that we are evaluating gonna
14:07:39
최종 결과에 포함될 것이므로 서브
be included in the final results so the sub
14:07:42
쿼리는 테스트를 수행하기 위해 사용되며, 결과가 있는지 없는지에 따라
query is used in order to do a test do we have a result or we don't and based on this sql either gonna include or exclude the row from
14:07:50
최종 결과에 포함되거나 제외될 것입니다. 이것이
final results so this is the logic behind the
14:07:53
SQL에서 존재하는 논리입니다. 자, 이제 같은
exists in sql all right so now we're going to go and solve the same
14:07:56
작업을 해결해 보겠습니다. 작업은
task using the exists so the task is show
14:08:00
고객이 주문한 세부 정보를 보여주는 것입니다.
the details of orders made by the customers in
14:08:03
독일에서 고객이 주문한 세부 정보입니다. 우리는 이미 이 작업을 해결했습니다.
germany so we have already solved this task using the in operator
14:08:06
IN 연산자를 사용하여 서브 쿼리를 통해 이제 우리는 EXISTS를 사용하여 해결할 것입니다.
and the sub query now we're going to go and solve it using the exists
14:08:09
다시 말해, 우리가 했던 동일한 논리적 단계를 가질 것입니다.
so again we're going to have the same logical steps that we have done
14:08:12
먼저 모든 세부 정보를 선택하겠습니다.
before so first we're going to go and select all the details
14:08:16
판매 주문 테이블에서 모든 세부 정보를 선택하겠습니다.
from the table sales orders so
14:08:19
자, 실행해 보겠습니다. 그렇게 하면 모든 주문과
let's execute it and with that we have all the orders and
14:08:22
모든 세부 정보를 얻을 수 있지만, 물론 모든 정보가 필요하지는 않습니다.
all the details but of course we don't need all those informations
14:08:26
우리는 독일에서 온 고객의 주문만 필요합니다.
we need only the orders that's made by customers from
14:08:29
그것이 첫 번째 쿼리입니다. 이제 두 번째 쿼리를 구성해 보겠습니다.
germany so that is the first query let's go and construct
14:08:32
우리는 'SELECT * FROM'이라고 말할 것입니다.
the second query we're gonna say select star from
14:08:36
판매 고객이지만, 모든 고객이 필요하지 않고
sales customers but we don't need all the customers we need only the customers
14:08:42
독일이라는 값과 같은 국가에서만 고객이 필요합니다.
from country equal to the value germany
14:08:46
그러니까 실행하러 가자
so let's go and execute it so
14:08:50
이제 우리는 독일에서 온 모든 고객을 가지고 있다
now we have all customers that come from germany now we
14:08:53
이 두 쿼리를 함께 결합해야 한다
have to go and put those two queries together in
14:08:57
최종 결과를 얻기 위해서, 우리가 이전에 배운 것처럼
order to get the final results so as we learned before the
14:09:00
두 번째 쿼리는 서브 쿼리가 될 것이므로 지원할 것입니다.
second query is going to be our sub query so it's going to be supporting
14:09:03
첫 번째 쿼리를 필터링하기 위해서입니다.
the first query in order to filter the data so the
14:09:06
첫 번째 쿼리는 우리의 메인 쿼리가 될 것입니다.
first query going to be our main query let
14:09:10
이것을 더 작게 만들겠습니다.
me just make this smaller and that takes as well now
14:09:13
모든 주문이 필요하지 않습니다. 우리는 주문만 필요합니다.
we don't need all the orders right we need only the orders
14:09:17
고객이 독일에서 온 주문만 필요합니다.
where the customer come from germany so we need the
14:09:20
이제 필터 논리를 이렇게 설정할 수 있습니다.
where clause so now we can have the filter logic like this show
14:09:23
주문 세부정보는 고객 ID가 서브 쿼리에서 존재할 때만 표시됩니다.
the order details only if the customer id exists from the sub query and now we have to go and put our sub query so our sub query gonna be
14:09:33
이것을 오른쪽으로 이동합시다.
this one over here so let's just move
14:09:36
서브 쿼리로 만들기 위해 괄호를 닫아야 합니다.
it to the right side and in order to have it as
14:09:39
존재하는 것은 상관관계 서브 쿼리입니다.
a sub query we have to close the parenthesis and now since
14:09:43
이제 서브 쿼리를 함께 연결해야 합니다.
exist is correlated sub query we cannot have it like
14:09:46
주 쿼리와 함께 연결해야 합니다.
this we have to go and connect the sub query together
14:09:49
주문 정보를 확인하기 위해서입니다.
with the main query so now the sub query is currently independent from the main query because we want to check each order information
14:09:57
서브 쿼리에 조건을 추가해야 합니다.
from the order table to check whether the customer exists
14:10:01
다음과 같이 설정할 것입니다.
in the sub query we're gonna go and add the condition
14:10:04
고객 ID를 함께 연결해야 합니다.
like the following and now it's like the joins we
14:10:07
서브 쿼리에서 고객 ID가 같아야 합니다.
have to go and connect the customer ids together so we're gonna go over here and give it like an alias and as well for the sub query and now we're gonna say customer id from the orders
14:10:19
서브 쿼리에서 오는 고객 ID와 주 쿼리에서 오는 고객 ID가 같습니다.
should be equal to the customer ID from the subquery, the table customers like this.
14:10:25
서브 쿼리는 고객의 존재를 테스트하기 위해 사용됩니다.
So again, this customer ID come from the subquery and this customer ID comes from the main query.
14:10:32
별표나 열 또는 정적 값을 사용할 수 있습니다.
So now since we are using the subquery only in order to test the existence of the customer, so if the subquery returns anything or not, it doesn't matter what you are selecting in the subquery.
14:10:45
모든 SQL 개발자가 정적 값을 선택하기로 결정했습니다.
So you can go with the star or a column or any static value.
14:10:49
물론 고객 ID와 같은 열을 추가할 수 있습니다.
But for some reason, all the SQL developers decided to go with the static value one.
14:10:53
고객 ID에서 정보를 검색하기 위한 필수 단계입니다.
And of course, you can go and add like a column like the customer ID.
14:10:57
SQL이 더 빠르게 작동할 것입니다.
But it's like a necessary step for the SQL in order to retrieve the information from the customer ID.
14:11:03
그래서 SQL에서 정보를 검색하기 위해 필요한 단계입니다.
So it's going to be way faster for SQL if you say, OK, select one. So let's stick with the best practices.
14:11:09
존재하는 값 하나를 사용하세요. 이것이 우리의 서브 쿼리입니다.
Use the one value if you are working with exist. So this is our sub query.
14:11:15
이제 모든 것이 준비된 것 같습니다. 실행해 보겠습니다. 출력에서 고객이 독일에서 온 모든 주문을 확인할 수 있습니다.
And I think we have everything. Let's go and execute it. Now, as you can see in the output, we got all the orders where the customers come from Germany.
14:11:24
물론 다른 값을 시도하고 실행하면 동일한 결과를 얻을 수 있습니다.
Now, of course, if you want to go and try another value and execute, you will get exactly the same results.
14:11:29
어떤 값을 사용하든 상관없습니다. 이렇게 해서 우리는 exists를 사용하여 작업을 수행했습니다.
So it doesn't matter which value you are using. So with that, we have saw the task, this time using the exists.
14:11:35
이제 작업에서 독일에서 오지 않는 고객의 주문 세부정보를 보여달라고 하면 매우 간단합니다.
Now, if the task says show the details of orders made by customers that don't come from Germany, it's going to be very simple.
14:11:41
우리는 exists 앞에 not 연산자를 사용할 것입니다. 그래서 where not exists입니다.
We're going to go and use the operator not before the exists. So where not exists.
14:11:47
이제 전체 논리를 뒤집고 서브쿼리와 일치하지 않아야 한다고 말하고 있습니다.
So now we are flipping the whole logic and we are saying there should be no matching with the subquery.
14:11:53
이제 실행하면 고객이 독일에서 오지 않는 모든 주문을 단순히 not 논리를 사용하여 얻을 수 있습니다.
So now if you go and execute it, you will get all the orders where the customers don't come from Germany by simply using the not logic.
14:12:02
상관 서브쿼리와 비상관 서브쿼리를 비교할 때 귀찮은 점이 하나 더 있습니다.
And there is one more thing that is annoying about the correlated subqueries if you compare it to the non-correlated subqueries.
14:12:08
이제 N 연산자로 돌아가 보겠습니다. 이것은 비상관 서브쿼리이며 서브쿼리만 선택하면 독립적으로 실행할 수 있습니다.
As we learned before, let me go back to the N operator. Now this is a non correlated subquery and if I go and select only the subquery I can go and execute it independently.
14:12:19
중간 결과를 확인하고 쿼리를 검증할 수 있습니다.
So I can go and check the intermediate results and like validate my query.
14:12:23
상관 서브쿼리의 문제는 서브쿼리를 강조 표시하고 실행할 수 없다는 것입니다.
But the problem with the correlated subquery I cannot go and highlight the subquery and then go and execute it.
14:12:30
서브쿼리의 구문에서 주 쿼리에서 가져온 열을 추가하고 있기 때문입니다.
And that's because in the syntax of the subquery we are adding a column that is outside our subquery that come from the main query.
14:12:38
현재 SQL에 대한 이 정보는 알 수 없습니다.
So this piece of information currently for the SQL is unknown.
14:12:42
이 오류가 발생하는 이유는 SQL이 이 열이 어디에서 왔는지 모른다고 말하기 때문입니다.
And that's why we are getting this error because SQL saying, okay, I don't know where this column come from. So this is a little bit annoying using the correlated subqueries.
14:12:50
중간 결과를 테스트할 수 없습니다. 하지만 제가 보통 하는 방법은 한 행에 대한 중간 결과를 테스트하는 것입니다.
You cannot go and test the intermediate results. But how I usually do it, I go and test like an intermediate result for only one row.
14:12:57
예를 들어, 고객을 선택하겠습니다. 예를 들어, 두 번째 고객입니다.
So for example, I'm going to go and pick like a customer here, for example, two.
14:13:01
고객 ID는 두와 같아야 한다고 말하겠습니다.
So I'm going to go and say, okay, the customer ID should be equal to two.
14:13:06
여기서 이 값을 제거하겠습니다.
so let me just remove this from here i got this value from
14:13:09
메인 쿼리에서 가져온 값이므로 지금 실행하면
the main query so if i go now and execute
14:13:13
서브쿼리가 아무것도 반환하지 않는 것을 확인할 수 있습니다.
it i can see here okay the subquery is not returning
14:13:16
값이 없기 때문에 한 행만 테스트하고 있습니다.
anything because there is no such a value so with
14:13:19
작동하게 하려면 메인 쿼리에서 콜론도 추가해야 합니다.
that i'm just testing like one row and of course in order to
14:13:22
그래서 상관 서브쿼리는 비상관 서브쿼리보다 이해하기 조금 더 어렵습니다.
make this working i have to go and add as well the
14:13:26
주 쿼리에서 콜론을 추가해야 하므로, 상관 서브쿼리는 비상관 서브쿼리보다 이해하기가 조금 더 어렵습니다. 중간 결과를 테스트할 수 없기 때문입니다.
colon from the main query so this is why correlated subqueries are a little bit more hard to understand compared to the non-correlated because we cannot go and test the intermediate results like we can do there.
14:13:37
이것은 상관 서브쿼리를 사용하여 이 작업을 해결하는 또 다른 방법입니다. 알겠죠?
So this is another way on how to solve this task using a correlated sub queries with the operator exists. Okay.
14:13:44
이제 SQL이 상관 서브쿼리를 어떻게 실행하는지 단계별로 살펴보겠습니다.
So now let's see step by step how SQL executed the correlated sub queries using the exists operator.
14:13:51
이번에는 SQL이 서브쿼리로 시작하지 않습니다. SQL은 바로 메인 쿼리로 시작할 것입니다.
So now this time SQL will not start with the sub query. SQL is going to go and start immediately with the main query.
14:13:57
SQL은 먼저 메인 쿼리를 식별하고 실행할 것입니다. 하지만 행 단위로 실행할 것입니다.
SQL first going to identify the main query and it's going to go and execute it. But it's going to execute it row by row.
14:14:03
첫 번째 행은 첫 번째 고객이 될 것입니다.
so the first row gonna be the first customer so
14:14:07
이제 SQL은 첫 번째 고객을 아래에 배치할 것입니다.
now sql gonna go and put the first customer under the
14:14:10
테스트입니다. 이제 다음 단계는 고객 ID의 값을 전달하는 것입니다.
test so now the next step is that is going to go and pass
14:14:13
메인 쿼리에서 서브쿼리로 고객 ID의 값을 전달합니다. 지금 우리는 정확히 하고 있습니다.
the value of the customer id from the main
14:14:16
반대입니다. 이제 무엇이 일어날 수 있는지 준비할 것입니다.
query to the sub query so we are doing now exactly
14:14:19
서브쿼리를 다음 정보로 준비할 것입니다. 고객 ID가 1과 같다고 말하고 있습니다.
the opposite so now what can happen is going to prepare the
14:14:22
SQL은 이를 실행할 것입니다.
sub query with the following information so we are saying the
14:14:25
이 쿼리를 실행한 후 결과를 얻을 것입니다.
customer id equal to one and then sql gonna go
14:14:29
결과는 1이 될 것이며, 이는 우리가
and execute it so now once sql executed this query
14:14:32
여기에서 고객 ID가 여러 번 나타나기 때문입니다.
we will get the result of one and that's because we
14:14:35
고객 ID가 1인 경우가 있습니다. 따라서 주문 테이블에 행이 있습니다.
have here multiple times where the customer id is
14:14:38
고객 ID가 1인 경우가 있습니다. 이제 무엇이 일어날 수 있는지
equal to one so there is rows in the order table
14:14:41
메인 쿼리의 행이 테스트를 통과할 것입니다.
where the customer id equal to one so now what can happen the
14:14:45
이 고객은 최종 결과에 포함될 것입니다.
row from the main query gonna pass the test and
14:14:48
이제 다음 단계는 두 번째 고객을 테스트하는 것입니다.
this customer gonna be included in the final results
14:14:51
이 고객을 테스트에 넣을 것입니다.
so now the next step is going to go and start testing the
14:14:55
이제 테스트를 진행하고 값을 전달할 것입니다.
second customer so we're gonna put this customer
14:14:58
서브쿼리로, 여기에서 두의 값을 갖게 될 것입니다.
under the test now it's gonna go and pass the value to
14:15:01
이 쿼리를 실행할 것입니다. 물론 결과를 얻을 것입니다.
the sub query so here we're gonna have the value of two and then
14:15:04
여기에서 고객 ID가 여러 번 나타나기 때문입니다.
it's gonna go and execute this query and of course we will get
14:15:07
결과가 나올 것입니다. 여기 고객 ID가 여러 번
a result because we have here multiple times where the customer id
14:15:10
2와 같기 때문에 출력에서
equal to two so that's why in the output of this
14:15:13
서브 쿼리에서 하나를 얻을 것이므로 이제 훌륭하다고 말할 것입니다. 서브 쿼리에서 값을 얻었으므로 이 고객을 보여주는 것이 안전합니다.
sub query we will get one so now it's gonna say great we have a value from the sub query that's why it is safe to show this customer
14:15:21
이제 다음 행으로 넘어갈 것입니다.
in the outwards and now it's going to go to the next row and
14:15:24
다음 두 고객도 마찬가지입니다.
so on so for the next two customers the same
14:15:27
모든 고객에게 값이 있을 것이므로
things can happen all of those customers will
14:15:31
모두 테스트를 통과하는 것과 같습니다.
have a value from the sub query and that's why they are all
14:15:34
이제 마지막 행으로 넘어갈 것입니다.
like passing the test so we will have it
14:15:37
테이블 고객에서 이제 안나와
in the outwards now it's going to go to the last row from the
14:15:40
안나를 테스트에 넣을 것입니다. 이제 발생할 수 있는 것은
table customers so we have the anna and
14:15:43
서브 쿼리에 값 5를 전달하고
we're going to put anna to the test so now what can happen is going to go and pass the value five to the sub query and it's going to go
14:15:51
이 쿼리를 테이블 주문에 실행할 것입니다. 이제
and execute this query to the table orders now once
14:15:54
SQL이 이 쿼리를 실행하면 아무것도 반환되지 않을 것입니다.
sql execute this query there will be nothing returned
14:15:57
주문 테이블에 고객 ID가 없기 때문입니다.
and that's because we don't have here in the table orders
14:16:00
고객 ID가 5와 같기 때문입니다.
a customer id equal to five and now sql
14:16:03
이 고객은 실패할 것이며 SQL은 출력에 표시하지 않을 것입니다.
gonna say well we are not getting any results from the sub query
14:16:06
고객 안나는 서브 쿼리가 아무것도 반환하지 않기 때문에 제외됩니다.
that's why this customer gonna fail and sql will not show it at the output so it will be completely removed so the
14:16:15
고객 ID 번호 5, 안나는 주문 테이블에 존재하지 않습니다.
customer Anna is excluded because the subquery is not returning anything.
14:16:20
그래서 테스트에 실패할 수 있으며 최종 결과에는 고객만 남게 됩니다.
Customer ID number five, Anna does not exist in the table orders.
14:16:24
그래서 이것이 존재의 목적입니다. 우리는 다른 테이블의 행 존재를 확인하고 테스트하고 있습니다.
So it can fail the test and we will have in the final results only for customers.
14:16:29
그래서 이것이 SQL이 존재 연산자를 사용하여 상관 서브 쿼리를 실행하는 방법입니다.
So this is exactly the purpose of the exist. We are checking and testing the existence of our rows from another table from another query.
14:16:37
좋습니다, 친구들, 그래서 이를 통해 서브 쿼리에 대한 모든 것, 모든 다양한 카테고리와 유형을 다루었습니다.
So this is how SQL executes that correlated subqueries using the operator exists.
14:16:48
그래서 이것이 SQL이 상관 서브 쿼리를 실행하는 방법입니다.
All right, friends, so with that, you have covered everything about the sub queries, all the different categories and types of the sub queries.
14:16:55
이제 서브 쿼리에 대한 간단한 요약을 하겠습니다. 우리가 배운 대로, 서브 쿼리는 다른 쿼리 안에 있는 쿼리입니다.
And now we're going to do a quick recap about the sub queries. So as we learned, sub queries is just simply a query inside another query.
14:17:02
우리는 서브 쿼리를 사용하여 복잡한 쿼리를 더 작고 단순한 조각으로 나누기 위해 사용합니다.
And we use the sub queries in order to break down a complex queries into smaller, simpler,
14:17:09
관리하기 쉬운 조각으로 나누어 모든 것을 더 쉽게 개발하고 읽을 수 있게 합니다.
easy to manage pieces that makes everything easier to develop and as well to read.
14:17:14
우리가 배운 것처럼 서브 쿼리는 다양한 사용 사례가 있습니다.
And as we learned, there are like many different use cases for the sub queries.
14:17:18
서브 쿼리를 사용하여 나중에 다른 쿼리에서 사용할 임시 결과 집합을 생성합니다.
So we use sub queries in order to create temporary result sets to be used later from another query.
14:17:24
서브 쿼리를 사용하여 테이블을 조인하기 전에 데이터를 준비할 수 있습니다.
And we learned that we can use the sub queries in order to prepare the data before joining the tables.
14:17:30
서브 쿼리의 또 다른 중요한 사용 사례는 동적이고 복잡한 필터 로직을 사용하여 데이터를 필터링하는 것입니다.
And another very important use case for the sub query is that we can use it in order to filter our data using a dynamic and as well complex filter logics.
14:17:40
상관 서브 쿼리를 사용하여 다른 테이블의 데이터와 행의 존재를 확인할 수 있습니다.
And as we learned, we can go and use the correlated subqueries using the exist operator in order to check the existence of data and rows from another tables.
14:17:50
상관 서브 쿼리를 사용하면 행별 비교를 수행할 수 있습니다.
And as well, using the correlated subqueries help us to do row by row comparison. All right, my friends.
14:17:56
이제 SQL에서 쿼리를 중첩하는 방법에 대한 중요한 기술을 다루었습니다.
So with that, we have covered an important technique on how to nest your queries in SQL.
14:18:01
다음 단계에서는 SQL에서 다단계를 수행하는 가장 유명한 기술 중 하나인 CTE에 대해 이야기할 것입니다.
Now, in the next step, we're going to talk about one of the most famous technique on how to do multi steps in SQL, the CTE common table expression.
14:18:08
자, 시작합시다. ECT
So let's go. ECT
14:18:15
는 복잡한 쿼리를 단순화하고 정리하기 위해 쿼리 내에서 여러 번 사용할 수 있는 가상의 테이블과 같은 임시 이름의 결과 집합입니다.
is a temporary named result set like a virtual table that could be used multiple times within your query to simplify and organize complex query.
14:18:26
이제 다음 스케치를 사용하여 이것이 무엇을 의미하는지 이해해 봅시다.
So let's understand what this means using the following sketch.
14:18:30
우리는 주문, 고객 등과 같은 데이터베이스 테이블을 가지고 있습니다.
So we have our database tables like orders, customers and so on.
14:18:34
매우 간단한 시나리오에서 우리는 간단한 SQL을 작성합니다.
And in very simple scenario, we write a simple SQL
14:18:37
데이터베이스에서 데이터를 쿼리하고 검색하기 위해서입니다.
in order to query and retrieve the data from the database
14:18:40
그리고 출력에서 우리는 쿼리의 결과를 얻습니다.
and then in the output we will get the result of the query
14:18:43
이제 데이터 쿼리의 가장 간단한 버전입니다.
so this is the simplest version of querying data now
14:18:46
프로젝트에서는 상황이 복잡해지고 다음과 같은 기술을 사용할 수 있습니다.
things get complicated in our projects and we could have the following technique
14:18:50
우리의 쿼리에서 우리는 여전히 이 섹션을 가지고 있습니다.
in our query so we still have this section where we are saying
14:18:53
선택에서 시작하지만 이제 쿼리 내부에서
select from but now inside our query we
14:18:57
예를 들어 선택에서 어디에서와 같은 또 다른 쿼리를 작성할 수 있으며, 이는 첫 번째 쿼리와는 완전히 관련이 없습니다. 우리는 이 새로운 쿼리를 이름으로 쿼리 내에 넣을 수 있습니다.
can write another query like for example select from where which is completely nothing to do with the first query and we can give this new query inside our query in name
14:19:07
도시라고 하고 이 쿼리를 cte라고 부를 수 있습니다.
city and we can call this query a cte
14:19:10
쿼리 공통 테이블 표현식이며 첫 번째
query common table expression and the first
14:19:13
도시 외부의 쿼리를 우리는
query outside the city we call it a
14:19:16
주 쿼리라고 부릅니다. 이제 이것을 확인하면 우리는 쿼리를 가지고 있습니다.
main query now if you check this we have like a query
14:19:19
다른 쿼리 안에 있으니 이제 퀼이 무엇을 할지 보자.
inside another query so now let's see what is quill gonna
14:19:22
첫 번째로 퀼이 도시 쿼리를 실행할 것이다. 도시 쿼리가 실행되고 우리는 데이터베이스 테이블에서 몇 가지 정보를 가져올 것이다.
do with this the first thing is quill gonna go and execute the city query so the city query gonna be executed and we're gonna go and retrieve few informations from our database tables.
14:19:32
이제 출력은 쿼리에서만 사용할 수 있으며, 출력은 예를 들어 판매와 같은 테이블 형태를 가질 수 있다.
Now the output can be available only in the query and the output can have the shape of like a table, like for example, the sales.
14:19:40
이제 판매 테이블과 주문 테이블, 둘 다 테이블이지만 하나는 데이터베이스에 저장되고 다른 하나는 중간 가상 테이블이다.
So now the sales table and the orders tables, both of them are tables, but one is stored in the database and the other one is an intermediate virtual table.
14:19:50
이제 메인 쿼리에서 어떤 일이 일어날 수 있을까?
So now what can happen in the main query?
14:19:52
우리는 판매 테이블을 쿼리하기 시작할 수 있으며, CTE의 결과는 다른 일반 테이블처럼 사용할 수 있다.
We can go and start querying the sales table, the result from the CTE as any other normal table.
14:20:00
데이터베이스 테이블에 하는 것처럼 메인 쿼리가
like we do to the database tables so the main query gonna
14:20:03
몇 가지 정보를 가져오고 아마도 몇 가지 조작을 할 것이다.
go and retrieve few informations and maybe do some manipulations
14:20:06
판매 테이블 위에서 또는 CTE 결과 위에서, 물론 메인 쿼리도
on top of the sales table or let's say the
14:20:09
뭐, 몇 개의 테이블을 쿼리하자.
cte results and of course the main query as well can go and say
14:20:12
데이터베이스에서 몇 개의 테이블을 쿼리하자. 메인 쿼리는 두 개의 테이블 소스를 가진다.
you know what let's go and query as well few tables from
14:20:15
데이터베이스에서 직접 가져오거나 쿼리 내에서 생성된 테이블에서 가져올 수 있다. 그리고 모든 것이 끝나면
the database so the main query has two sources of tables
14:20:19
메인 쿼리의 최종 결과가 제시될 것이다.
either get it directly from the database or get it from the table that is created inside the query and then once everything is done the
14:20:27
사용자에게 최종 결과로서, 따라서 볼 수 있듯이
final results of the main query gonna be presented
14:20:30
CTE 쿼리는 생성하는 작업이 하나 있다.
for the user as a final result so as you can
14:20:33
우리 쿼리 안에 있는 테이블처럼.
see the cte query has one task where it generates
14:20:37
우리는 그것을 원하는 대로 사용할 수 있다. 이제 이 중간
like a table that lives inside our query
14:20:40
CTE에서 생성된 테이블은 두 가지 특징이 있다. 첫째
and we can go and use it as we want so now this intermediate
14:20:43
이 테이블은 오래 살지 않으므로 쿼리가 끝나면
table that is created from the cte has two features first
14:20:47
무슨 일이 일어날지는 이 테이블이 파괴될 것이다.
this table will not live long so once the query
14:20:50
그래서 이후에는 사용할 수 없으며 우리는 더 이상 쿼리할 수 없다.
ends what can happen is going to gonna go and destroy this
14:20:53
이스퀼이 여기서 하는 것은
table so it will not be available afterward and we are not
14:20:56
정리 작업을 하는 것이고, 두 번째 특징은 이것을 상상해 보자.
able to query it anymore so isquiel is doing here like
14:21:00
우리가 다른 사이드 쿼리를 가지고 있고 테이블을 가져오고 있다.
a cleanup and the second character about this let's imagine that
14:21:03
데이터베이스 테이블에서 직접.
we have another side query and it's retrieving tables
14:21:06
이제 데이터베이스 테이블에서 직접
directly from the database tables now if you say let's
14:21:09
그 테이블들을 조인하자고 하면
go and join those tables as well with the
14:21:12
첫 번째 쿼리의 판매와 함께 조인하더라도
sales from the first query well it will not be working because isquiel gonna say i don't know what you are talking about and that's because
14:21:20
판매는 같은 쿼리의 메인 쿼리에만 로컬로 제공되기 때문에 작동하지 않을 것입니다.
the sales is only locally available for the main query in the same query.
14:21:27
즉, 모든 쿼리에 대해 데이터베이스 테이블처럼 전역적으로 사용 가능하지 않다는 뜻입니다.
So that means it's not globally available like the database tables for any query.
14:21:32
이것은 같은 쿼리 내에서 메인 쿼리 전용입니다.
It is dedicated only for the main query within the same query.
14:21:36
이제 당신은 나에게 말할지도 모릅니다, 바라, 잠깐, 잠깐, 이 이야기를 전에 들은 적이 있죠?
And now you might tell me, Bara, wait, wait, wait, I have heard this story before, right?
14:21:40
그래서 이것은 당신이 서브쿼리에 대해 말한 것과 동일한 이야기입니다.
So this is an identical story to the one that you have told us about the sub queries.
14:21:45
서브쿼리와 CTE의 정확한 차이는 무엇인가요? 당신이 완전히 맞습니다.
So what is exactly the difference between the subquery and the CTE? Well, you are totally right.
14:21:50
서브쿼리와 CTE 사이의 이야기는 동일하지만 여전히 차이점이 있습니다. 몇 가지 차이점을 보여드리겠습니다.
The story is identical between the subquery and the CTE, but still there are differences between them. So let me show you a few differences.
14:21:58
이제 그들을 나란히 놓아봅시다. 왼쪽에는 서브쿼리가 있고, 오른쪽에는 CTE가 있습니다.
Now let's put them side by side. We have on the left side the subquery, on the right side we have the CTE.
14:22:03
이제 CTE와 서브쿼리를 어떻게 작성했는지 보면, 서브쿼리는 아래에서 위로 작성하고 있습니다.
So now if you look on how we wrote the CTE and the subquery, you can see that on the subquery we are writing it from bottom to top.
14:22:10
먼저 이 내부 쿼리, 서브쿼리가 있습니다.
So first we have this inner query, the subquery.
14:22:14
그 위에 메인 쿼리가 있습니다.
and then on top of it we have the main query but now on
14:22:17
반면 CTE는 위에서 아래로 작성합니다.
the other hand the CTE we are writing it from top to bottom
14:22:20
먼저 이 내부 쿼리, CTE 쿼리를 작성합니다.
so first we write this inner query the CTE query
14:22:23
그 아래에 메인 쿼리를 작성할 것입니다.
and then beneath it we're gonna go and write the
14:22:26
이것이 그들 사이의 첫 번째 차이점입니다.
main query so this is the first difference between them on
14:22:29
쿼리를 작성하는 방식, 그래서 내가 서브쿼리에 대해 생각하고 있다면
the way we write the query so if I'm thinking about sub
14:22:32
아래에서 위로 시작합니다. CTE에 대해 생각하고 있다면 위에서 아래로 생각합니다. 하지만 여전히 당신은 아시죠, 우리가 어떻게 작성하는지는 상관하지 않습니다.
queries I start from bottom to top if I'm thinking about CTE I think from top to bottom but still you say you know not I don't care how we write it
14:22:40
그들은 서브쿼리가 도입하는 것과 같은 일을 하고 있습니다.
they are doing the same thing the sub query is introducing
14:22:43
나중에 사용되는 중간 결과입니다.
an intermediate result that is used later
14:22:46
메인 쿼리에서와 CTE에 대해서도 마찬가지입니다.
from the main query and the same thing for the cte
14:22:49
중간 테이블처럼 제시됩니다.
it presents like intermediate table that is
14:22:52
메인 쿼리에서도 사용됩니다. 이제 큰 것을 말씀드리겠습니다.
used as well from the main query now let me tell you the big
14:22:56
서브 쿼리의 차이점은 결과를 한 번만 사용할 수 있다는 것입니다.
differences between them is that in the sub query the
14:22:59
결과를 한 번만 사용할 수 있다는 것입니다.
result can be used only once so you cannot
14:23:02
메인 쿼리의 다른 위치에서 재사용할 수 없습니다.
have another place in your main query where you go
14:23:05
서브 쿼리의 결과를 재사용할 수 없습니다.
and reuse the results from the sub query so you can
14:23:08
한 위치에서만 사용할 수 있습니다.
use it maximum only in one position and only
14:23:11
도시 기법을 사용하면 판매 테이블을 가상 테이블로 생각할 수 있습니다.
once but in the other hand with the city technique you
14:23:14
판매 테이블을 가상 테이블로 생각할 수 있습니다.
can think about the sales table as a virtual table and not only you can use it in one place in the main query
14:23:21
여러 다른 위치에서 사용할 수 있습니다.
you can go and use it in many other places so
14:23:24
다시 조인할 수 있다는 의미입니다.
you can go and join it again so that means i'm using the
14:23:28
CTE 쿼리의 출력을 두 곳에서 사용할 수 있습니다.
output from the cte query in two different places
14:23:31
메인 쿼리에서 또는 세 개의 다른 위치에서 사용할 수 있습니다.
in the main query or maybe from three different places so you can have another place where you go as well and query the sales table
14:23:38
서브 쿼리와 CTE의 가장 중요한 차이점입니다.
that is only available in our query so this is the
14:23:41
공통 테이블 표현식이라는 이름에서 비롯됩니다.
main and the most important difference between the subquery and the cte
14:23:44
CTE의 결과를 테이블로 생각합니다.
it's from the name common table expression we think about
14:23:48
cte의 결과를 테이블로 나타내면
the result of the cte as a table so
14:23:51
우리가 선택할 수 있고, 다른 어떤 것과 조인할 수 있습니다.
we can go and select it we can go and join it with any other
14:23:54
테이블처럼 숨겨진 가상 테이블이 존재합니다.
table so it is like a hidden virtual table lives
14:23:57
우리 쿼리 내부에 있지만 서브쿼리는 완전히 다릅니다.
inside our query but the sub queries it's totally different
14:24:01
주 쿼리에서 하나의 위치에 대한 결과일 뿐입니다.
it's a result only for one position in the main
14:24:04
그리고 그것은 한 번만 사용됩니다.
query and it's used only once so that
14:24:07
즉, 서브쿼리를 두세 군데에서 사용하고 싶다면 서브쿼리를 세 번 다르게 작성해야 한다는 의미입니다. 이제 왜 city가 필요하고 서브쿼리가 왜 필요한지 이해하게 되었습니다.
means if you want the subquery in two three different places you have to go and write the subquery three different times so now you understand why do we have city and why do we have subqueries
14:24:22
좋습니다. 이제 city가 무엇인지 이해하셨습니다.
all right so with that you have understood what is city now the
14:24:25
이제 질문은 왜 처음부터 city가 필요한가, city의 주요 목적이 무엇인가입니다. 이제 스케치로 돌아가 보겠습니다. 복잡한 SQL 작업에서 다음 단계를 수행해야 한다고 가정해 보겠습니다.
question is why do we need city in the first place what is the main purpose of the city let's go back to the sketch now let's say in In our complex SQL task, we have to do the following step.
14:24:36
첫 번째 단계는 모든 데이터를 준비하기 위해 테이블을 함께 조인해야 합니다.
Step one, we have to go and join the tables together in order to prepare all the data that we need for the next step.
14:24:42
이제 두 번째 단계에서는 데이터를 집계해야 합니다. 아마도 우리는 요약 작업을 하고 있을 것입니다.
And now in the second step, we have to go and aggregate the data. Maybe we are doing summarizations.
14:24:47
이제 우리의 작업에서 서로 다른 데이터에 기반하여 다양한 집계를 수행해야 합니다.
Now in our task, we have to do as well different types of aggregations based on different data.
14:24:52
그리고 이제 우리가 해야 할 일은 데이터를 준비하고 다양한 유형의 집계를 수행하기 위해 동일한 테이블을 다시 조인해야 한다는 것입니다.
And now what might happen is that we have to go and join again the same tables in order to prepare the data and perform different type of aggregations.
14:25:00
예를 들어, 마지막 단계에서 평균을 구할 수 있습니다.
Like for example, the average, which can be in the last step.
14:25:04
이제 우리는 이전에 서브 쿼리를 사용하여 이 논리적 흐름을 만들 수 있다는 것을 배웠습니다.
Now we have learned before we can go and use the sub queries in order to make this logical flow.
14:25:08
따라서 1단계, 2단계, 3단계에서는 서브 쿼리가 있으며 마지막 단계는 메인 쿼리에 있을 것입니다.
So for step one, step two, step three, we will have sub queries and the final step going to be in the main query.
14:25:15
하지만 이제 우리가 계속 이렇게 하면 문제가 발생할 수 있습니다. 즉, 동일한 단계를 여러 번 반복하고 있다는 것입니다.
But now if we keep doing this, we can have a problem. And that is we are repeating the same step more than once.
14:25:23
따라서 우리는 1단계와 3단계에서 서로 다른 목적을 위해 테이블을 두 번 조인하고 있으며, 이는 정확히 동일한 두 개의 서브 쿼리를 생성하게 됩니다.
So we are joining the table twice in step number one and three for different purposes, which cause us to have two different sub queries that looks exactly the same.
14:25:32
그리고 이것이 바로 서브 쿼리의 약점입니다. 중복이 발생할 수 있습니다.
And this is exactly the weak point of the sub queries. It might introduce redundancies.
14:25:38
즉, 서브 쿼리만으로는 코드에서 모든 중복을 제거할 수 없습니다.
So that means the sub queries alone will not help you to eliminate all the duplicates in your code.
14:25:44
하지만 여전히 이 문제를 해결하기 위한 다양한 기술이 있습니다.
But still, we have different techniques in order to solve this issue.
14:25:47
우리가 할 일은 테이블을 조인하기 위한 단계를 하나만 두는 것입니다.
So what we're going to do, we're going to have only one step in order to join the tables.
14:25:52
그리고 이 데이터는 2단계에서 데이터를 집계하는 데 사용될 수 있으며, 다시 데이터를 조인하는 3단계는 필요하지 않습니다.
And then this data can be used in the step two in order to aggregate the data. And then we don't need the step three of joining again the data.
14:26:00
우리는 1단계를 재사용할 것이며, 평균을 사용하여 데이터를 집계하는 4단계에 동일한 데이터를 사용할 것입니다.
We're going to reuse the step one. And we're going to use the same data for the step four, which is aggregating the data using average.
14:26:08
그리고 우리는 놀라운 CTE의 도움으로 이를 수행할 수 있습니다.
And we can do this with the help of the amazing CTE.
14:26:11
서브 쿼리의 단계와 CTE의 단계를 비교하면, CTE를 사용하면 단계 수를 줄이고 있음을 알 수 있습니다.
So if you compare the steps in the subqueries with the steps with the CTE, you can see with the CTE, we are reducing the number of steps,
14:26:19
이는 쿼리의 크기를 줄이는 데 기여할 수 있습니다. 이제 서브 쿼리에서는 아래에서 위로 단계를 생각합니다.
which can lead to reduce the size of the query. So now again here in subquery, we think about the steps from bottom to top.
14:26:27
하지만 CTE에서는 반대입니다. 우리는 위에서 아래로 생각합니다. 즉, 가장 위의 첫 번째 단계는 테이블을 조인하는 것입니다.
But in the CTE, it's the way around. We think from top to bottom. So that means the first step on the top is going to be joining the tables.
14:26:34
그리고 그 아래에는 2단계와 3단계가 있습니다. 물론 조인을 반복하고 있으므로 이를 CTE에 넣을 수 있습니다.
And then below it is going to be step two and step three. And of course, since we are repeating the join, we can put it in CTE.
14:26:40
그리고 우리는 메인 쿼리의 다른 장소에서 두 번 사용할 수 있습니다. 보시다시피, CTE에는 많은 장점이 있습니다.
And then we can use it twice in different places in the main query. So as you can see, there are a lot of benefits of the CTE.
14:26:46
서브 쿼리와 마찬가지로 복잡한 쿼리를 작성하기 쉽고 관리하기 쉬운 작은 조각으로 나누고 있습니다.
It's like the subqueries. we are breaking down complex queries into smaller pieces that are easier to write, manage, understand.
14:26:54
또한 1단계, 2단계, 3단계의 논리적 흐름이 있습니다.
And as well, we have like a logical flow from step one, two, three.
14:26:58
하지만 한 가지 더 이점이 있습니다. 코드의 중복을 줄여 테이블을 두 번 조인할 필요가 없습니다.
But with one more benefit, that's we reduce the redundancies of our code so we don't have to join the tables twice.
14:27:05
이제 CTE가 우리의 삶을 어떻게 더 쉽게 만드는지 간단한 예를 보여드리겠습니다. 우리의 쿼리에서는 다양한 작업을 수행해야 할 수 있습니다.
Now I'm going to show you a simple example how the CTE makes our life easier. In our query, we might have to do different stuff.
14:27:12
예를 들어, 최고의 고객을 찾아야 합니다.
Like, for example, we have to go and find the top customers
14:27:16
그래서 우리는 이를 하나의 CTE에 넣을 수 있으며, 또한 필요할 수 있습니다.
so we can put this in one cte and we might need as well
14:27:19
상위 제품을 계산하기 위해
to calculate what are the top products and we can
14:27:22
다른 도시에도 이것을 넣을 수 있으니
put as well this in another city so you don't have to
14:27:25
모든 것을 하나의 큰 도시로 넣으면 같은 문제가 발생할 수 있습니다.
put everything in one big city then you can have the same issue
14:27:28
복잡한 쿼리를 처리해야 하고, 또한
of having complex query and let's say that we have as well to find and
14:27:31
일일 수익을 계산해야 하며, 이를 위해
calculate the daily revenue and for this as well we
14:27:34
이제 모든 부분을 하나의 도시로 넣어야 합니다.
have to put it in one city now once we have all those parts we
14:27:38
주요 쿼리에 모든 것을 함께 넣을 수 있습니다.
can put everything together in the main query so
14:27:41
이 구조를 보면 정말 이해하기 쉽습니다.
now if you look to this structure you can see it's really easy to
14:27:44
이 코드를 이해하기 쉽고 읽기 쉽습니다.
understand this code it's easy to read so cte
14:27:48
우리 쿼리의 가독성을 향상시킵니다.
improves the readability of our queries so
14:27:51
즉, 코드가 명확한 섹션으로 나뉘어져 있습니다.
that means your code is divided into clear sections making
14:27:54
즉, 각 부분이 하는 일을 이해하기 쉬워집니다.
it easier to understand what each part does
14:27:57
계속 살펴보면 또 다른 장점이 있습니다.
now if you keep looking to this we have another advantage of
14:28:00
CTE는 모듈성을 도입합니다.
the cte introduces modularity so
14:28:03
즉, 코드를 더 작고 관리 가능한 부분으로 나눕니다.
that means it breaks your code into smaller manageable parts so this This means instead of writing one huge complex query, you break it down into smaller chunks using CTE.
14:28:15
각 CTE는 독립적으로 특정 문제의 일부를 처리합니다.
Each CTE is like self-contained and handles a specific part of the problem and then you can combine them all together in the final query.
14:28:23
퍼즐을 조각조각 맞추는 것과 같습니다.
It's like we are putting together a puzzle piece by piece.
14:28:27
CTE의 가장 중요한 장점 중 하나는 재사용성입니다.
And now one very important advantage of the CTE is the reusability.
14:28:31
즉, 쿼리 내에서 여러 번 사용되는 결과 집합을 가질 수 있습니다.
So that means we can have a result set that is used multiple times inside our query.
14:28:37
즉, 논리를 한 번만 작성하고 쿼리 내의 다른 위치에서 사용할 수 있습니다.
So that means you write the logic the code only once and then use it in different places inside your query.
14:28:42
이는 매우 중요합니다. 같은 내용을 반복해서 작성하는 시간을 낭비하지 않게 해줍니다.
This is very important not only you are wasting time writing the same stuff over and over, but also it reduces the errors and mistakes that you might do if you are repeating the same code.
14:28:52
특히 나중에 논리를 변경하고 싶을 때, 각 위치를 방문해야 합니다.
Especially if later you want to go and change the logic then you have to go and visit each time you have done this logic and then do the changes and you might forget some places.
14:29:01
그래서 이 도시가 놀라운 이유입니다.
That's why the city is amazing. You can write the logic once and then you go and reuse it in different places.
14:29:08
이 기술, CTE를 쿼리 내에서 사용하는 장점입니다.
So these are the advantages of using this technique, the CTE, inside your queries.
14:29:17
클라이언트 사이트에 있으며 데이터 분석가입니다.
So again, you are at the client site and you are data analyst. You are writing a query where you are defining a CTE called details.
14:29:25
그리고 그 안에 일부 논리가 있습니다. 이제 메인 쿼리에서 주문 데이터 선택 중입니다.
And inside it, you have some logic. And now in the main query, you are selecting the data from the orders.
14:29:29
그리고 세부정보와 함께 조인하고 있습니다.
and as well you are joining it with the details with the
14:29:32
CTE를 여러 번 사용하여 여러 조건으로.
cte multiple times using multiple conditions now
14:29:36
이 쿼리를 실행하면 데이터베이스 엔진이
once you go and execute this query the database engine
14:29:39
쿼리를 읽고 CTE가 있다는 것을 알 수 있습니다.
can read the query and say aha we have here is cte and
14:29:42
주요 우선 순위를 가지고 있으므로 먼저 실행됩니다.
it has the main priority so that means it's gonna go
14:29:45
CTE를 먼저 실행하고 이제 도시에서
and execute the cte first and now let's say that
14:29:48
주문 테이블에서 데이터를 검색하고 있습니다.
in the city you are retrieving data from the table orders and
14:29:52
물론 사용자 내부의 디스크 저장소에 있는 주문 테이블입니다.
the table orders of course in the disk storage inside the user
14:29:55
데이터가 있으며 도시가 완전히 실행되면,
data and now once the city is is completely executed,
14:29:58
데이터베이스 엔진이 결과를 캐시에 배치할 수 있습니다.
the database engine can go and place the results in the
14:30:01
이 결과를 세부정보로 명명할 것입니다.
cache and it's gonna name this result as details it's
14:30:04
테이블 이름처럼 데이터베이스 엔진이 CTE를 완료했습니다.
like a table name so the database engine is done with the cte it's
14:30:08
이제 메인 쿼리를 가져오고 실행을 시작합니다.
gonna go now and grab the main query and it's gonna start executing
14:30:11
단계별로 첫 번째 단계는 데이터를 가져오는 것입니다.
it step by step so the first step is that to get the data
14:30:14
주문에서 데이터를 가져오는 것입니다. 주문이 존재하므로
from the orders so since the orders exist in the
14:30:17
디스크 저장소에서 데이터를 검색합니다. 이제 데이터베이스
disk storage it's gonna go and retrieve it from there now the database
14:30:21
엔진이 세부정보를 확인합니다. 캐시에 있습니다.
engine gonna check the details okay we have it in the cache
14:30:24
디스크 저장소에서 검색할 필요가 없다는 의미입니다.
that means we don't have to search for it in the disk storage and
14:30:27
세부정보에서 데이터를 고속으로 검색하기 시작합니다.
it's gonna start retrieving the data from the details with
14:30:30
이제 두 번째 단계로 넘어가서 조인합니다.
high speed and now it's gonna go to the second step as well joining
14:30:33
세부정보와 데이터를 조인합니다. 다시 데이터베이스 엔진이
the data with the details so again the database engine gonna go
14:30:36
캐시로 가서 테이블 세부정보를 보고
to the cache i'm gonna see the table details and retrieve the
14:30:39
다른 조건에 따라 데이터를 검색하고 세 번째로
data based maybe in different conditions and then to the third time
14:30:42
세부정보에 조인하여 캐시에서 데이터를 가져옵니다.
as well we are joining to the details and we're gonna get the data from the
14:30:45
캐시에서 데이터를 가져오고 있습니다.
cache so as you can see from the main query we are using the
14:30:49
cte의 결과를 여러 번 사용하고 있습니다.
results from the cte multiple times in different places
14:30:52
모든 정보를 빠르게 검색하고 있습니다.
and the retrieval of all those informations is happening
14:30:56
고속으로 데이터를 처리하는 큰 장점입니다.
in high speed so this is one big benefit of
14:30:59
캐시의 고속 메모리를 활용하는 것입니다.
using the cte is to utilize using the high
14:31:02
캐시에서 데이터를 가져오는 것이 훨씬 빠릅니다.
speed memory of the cache so that means retrieving the data
14:31:05
주문에서 디스크 저장소로부터 데이터를 검색하는 것보다.
from the cache from the details is way faster than
14:31:08
주 쿼리가 완전히 실행되면,
retrieving the data from the disk storage from the orders
14:31:11
결과가 데이터베이스 엔진으로 반환됩니다.
now once the main query is completely executed the
14:31:14
클라이언트 측으로 다시 전송되고 결과를 확인할 수 있습니다.
result gonna be returned to the database engine and
14:31:17
도시에는 여러 종류가 있습니다. 비재귀적 도시와 재귀적 도시가 있습니다.
then it's gonna send it back to the client side and we will see the results in the output so that's it it's amazing right this is how the database server execute the amazing technique the cte behind the scenes
14:31:33
비재귀적 CTE에는 두 가지 하위 유형이 있습니다.
all right so now for the city we don't have only one city we have different types of cities so mainly there are like two types of city we have the non-recursive city and recursive city
14:31:45
첫 번째 유형은 독립형 CTE입니다.
And we can say for the non-recursive CTE, we have two subtypes. The first type is the standalone CTE.
14:31:52
두 번째는 중첩 CTE입니다. 각 유형을 자세히 살펴보겠습니다.
And the second one is the nested CTE. And now what we're going to do, we're going to deep dive into each type.
14:31:58
독립형 CTE는 쿼리에서 독립적으로 정의되고 사용됩니다.
And we will start with the easiest form of the CTE, the standalone CTE. It is the simplest form.
14:32:09
즉, 자급자족하며 다른 것에 의존하지 않습니다.
So what is standalone CTE? It is a CTE query that is defined and used independently in the query.
14:32:16
쿼리 내부의 어떤 것에도 의존하지 않고 독립적으로 실행할 수 있습니다.
So this means it is self-contained and it doesn't depend on anything. It doesn't depend on any other CTE or queries.
14:32:23
CTE가 데이터베이스 테이블을 쿼리합니다.
So this means we can run the standalone query independently from anything inside our query. So let's understand what this means.
14:32:31
출력에서 중간 결과를 얻을 수 있습니다.
We have our CTE. It's going to go and query the database tables. And in the output, we will get an intermediate result.
14:32:38
주 쿼리가 중간 결과를 쿼리합니다.
and then the output can be used from the main query so
14:32:41
최종 결과를 출력합니다.
the main query gonna query the intermediate results and present in
14:32:44
CTE는 다른 것과 완전히 독립적입니다.
the output the final results so now if you check our cte it
14:32:47
데이터베이스를 쿼리하고 하나의 출력을 생성합니다.
is completely independent from anything else so
14:32:50
이 CTE는 독립적이므로,
it simply queries the database and it has one output
14:32:53
독립형 CTE라고 부릅니다.
so since this cte is independent from anything
14:32:56
그래서 이 CTE는 다른 것과 독립적이기 때문에
else we call it a standalone cte now
14:33:00
우리는 이제 이것을 독립형 CTE라고 부릅니다.
if you compare this city with the main query you can see that the main query cannot be executed alone and that's because it
14:33:06
첫 번째 쿼리의 결과가 필요하므로 우리는 할 수 없습니다.
needs the result from the first query so we cannot
14:33:09
주 쿼리는 독립적이라고 말할 수 없으며 실행될 수 없습니다.
say the main query is independent cannot be executed
14:33:13
혼자서는 항상 도시 쿼리에 의존합니다.
alone it always depends on the city query
14:33:16
즉, 도시 쿼리를 먼저 실행해야 한다는 의미입니다.
so that means city first need to be executed then
14:33:19
그 후에 주 쿼리를 실행할 수 있습니다. 이것이 우리가 의미하는 바입니다.
the main query can be executed so this is what we mean with
14:33:23
독립적인 도시 쿼리는 다른 것에 의존하지 않습니다.
the standalone city it doesn't depend on anything
14:33:26
이제 도시 쿼리의 구문을 이해할 수 있습니다.
else so now we can understand the syntax of the city so
14:33:29
우리는 매우 간단한 쿼리인 select from where를 가지고 있습니다.
we have a very simple query select from where so
14:33:32
매우 간단한 select 문입니다. 이제 CTE 안에 넣기 위해
it is a very simple select statements now in order
14:33:35
with 절을 사용할 수 있습니다. 그래서 with라는 키워드로 시작합니다.
to put it inside a CTE we can go and use
14:33:39
그 다음 CTE 이름이 테이블 이름처럼 됩니다.
the with clause so it starts with the keyword with
14:33:42
그리고 우리는 이것을 말하기 위해 as라는 키워드를 가지고 있습니다.
then the CTE name it's like a table name
14:33:45
CTE가 다음과 같이 정의된다고 말합니다.
and then we have the keyword as in order to say this
14:33:49
이것이 CTE의 정의이며, 시작과 끝의 두 개의 괄호가 있습니다.
CTE is defined like the following so this
14:33:52
이것으로 당신은 스케일에 대해 이야기하고 있습니다. 이제 우리는 CTE에 대해 이야기하고 있으며, 이름이 있습니다.
is the definition of the CTE and it has two parentheses the starting and the ending so with this you are telling a scale okay now we are talking about CTE and it It has a name.
14:34:01
따라서 with 절 안에 쿼리를 사용하고 있다면, 우리는 이것을 CTE 쿼리라고 부릅니다.
So if you are using a query inside a with clause, we call this a CTE query.
14:34:06
여기에서 CTE를 정의합니다. 물론 우리는 CTE를 정의하는 것만 원하지 않습니다. 우리는 그것을 사용하고 싶습니다.
It is where you define the CTE. Now of course we don't want only to define a CTE, we want to use it.
14:34:12
따라서 이 정의 외부에서 우리는 이렇게 사용할 수 있습니다.
So outside of this definition, we can go and use it like this.
14:34:16
우리는 CTE 이름에서 선택한다고 말하고 있습니다.
So we are saying select from the CTE name.
14:34:20
즉, CTE의 결과에서 데이터를 선택하고 싶다는 의미입니다.
So that means we want to select the data from the result of the CTE.
14:34:24
여기에서 with 절에 정의한 것과 정확히 같은 이름을 사용하는 것이 매우 중요합니다.
And here it's very important to use exactly the same name as you define it in the with clause.
14:34:30
이렇게 두면 우리는 이것을 주 쿼리라고 부를 수 있습니다. CTE를 사용하는 곳입니다.
So if you leave it like this, we can call this the main query. It is the place where we use the CTE.
14:34:36
이것이 SQL에서 매우 간단한 CTE의 구문입니다.
So this is the syntax of a very simple CTE in SQL.
14:34:40
좋아요, 이제 우리가 할 것은 이 섹션을 계속 진행할 작업을 만드는 것입니다.
Okay, so now what we're going to do, we're going to have like a task that's going to keep progressing through this section.
14:34:46
그래서 우리는 첫 번째 단계부터 시작할 것이고 CTE에서 진행하면서 계속 단계를 추가할 것입니다.
So we're going to start with the first step and we will keep adding steps as we progress in the CTE.
14:34:50
이 작업의 첫 번째 단계는 고객당 총 판매량을 찾는 것입니다.
So now the first step in this task says find the total sales per customer.
14:34:56
물론 우리는 단계가 하나뿐이기 때문에 CTE를 사용할 필요가 없습니다.
And now of course since we have only one step it makes no sense to use the
14:34:59
하지만 나중에 다른 단계가 있을 것이기 때문에 우리는 CTE를 사용할 것입니다.
CTE but we will use it since we know that there will
14:35:02
나중에 다른 단계가 있을 것이기 때문에 지금 시작합시다.
be different steps later so let's start doing that now
14:35:06
CTE를 사용하기 전에 먼저 쿼리를 작성하고 싶습니다.
before I use any CTE I would like just to write our query first
14:35:09
각 고객의 총 판매량이 필요합니다. 매우 간단합니다.
so we need the total sales for each customers it's very
14:35:12
그래서 우리는 선택하고 무엇을 해야 할지 가봅시다.
simple so we're gonna go and select and what do we
14:35:15
고객 ID를 가져오고 판매에 대한 집계를 해야 하므로 판매를 요약하고
need let's go and get the customer id and we need to do aggregations on the sales so summarize the sales and we're gonna
14:35:24
총 판매량이라고 부를 것입니다.
call it total sales from
14:35:28
테이블에서 총 판매량이라고 부를 것입니다.
the table and now since this is our first query we have to get the
14:35:31
이것이 우리의 첫 번째 쿼리이기 때문에 데이터베이스에서 데이터를 가져와야 합니다.
data from our database so we don't have any other
14:35:34
우리에게 다른 옵션이 없기 때문에 데이터는 판매 주문에 있을 것입니다.
option our data going to be in the sales orders so
14:35:37
그것을 가져가고 그룹화하는 것을 잊지 마세요.
let's go and get it and don't forget to group
14:35:40
집계를 위해 고객 ID로 그룹화하고 있습니다.
by for the aggregation we are grouping by the customer id
14:35:43
그게 다입니다. 이제 실행해 봅시다.
that's it let's go and execute it and
14:35:46
출력에서 보시다시피 특별한 것은 없습니다. 우리는 단순히 고객별로 집계하고 있습니다.
as you can see in the output nothing is fancy we are just aggregating the
14:35:50
그래서 그로 인해 작업을 해결했습니다.
sales by the customers so with that you have solved the task but
14:35:53
이제 쿼리를 CTE에 넣고 싶습니다.
now i would like to put my query in a cte and
14:35:56
그것은 나중에 더 많은 단계를 추가할 것이기 때문입니다.
that's because later we're going to add more steps so let's put
14:35:59
우리의 쿼리를 CTE에 넣고 그렇게 하려면 WITH 키워드로 시작해야 합니다.
our query in a cte and in order to do that we're going to start with the with keyword and now we have to define the name of the cte so i'm going to call it city underscore total
14:36:11
CTE의 이름을 정의해야 하므로 city_total이라고 부를 것입니다.
sales like this and then afterward we're going to say us
14:36:14
이렇게 판매하고 나중에 우리라고 말할 것입니다.
and then we have to go and add the parentheses at the start and as well at the end and with that you are telling sql this query is
14:36:23
시퀀스 쿼리이므로 SQL이 이 쿼리의 결과를 저장해야 합니다.
a city query so that means the sql should
14:36:26
이 쿼리의 결과를
store the result of this query in a
14:36:29
메모리에 캐시하여 나중에 메인 쿼리에서 사용합니다.
cache in memory to be used later in the main query
14:36:32
우리 도시와 물론 누락된 것은 메인
our city and of course what is missing is the main
14:36:35
쿼리이며 정의 후 정확히 수행해야 합니다.
query and you have to do it exactly after the definition
14:36:38
도시에 대한 정의 후 작은 코멘트를 하겠습니다.
of the city i will just make here a small comment about the
14:36:42
메인 쿼리이며 이걸 더 작게 만들겠습니다.
main query and let me just make this smaller like
14:36:45
이제 매우 간단한 선택을 해야 합니다.
this and now we have to go and have a very simple select
14:36:48
고객 테이블에서 더 많은 세부정보를 얻고 싶습니다.
statements from and now i would like to
14:36:51
이제 고객으로 가겠습니다.
get more details from the customers table so i will
14:36:54
이제 우리는 도시를 쿼리하고 있지 않습니다.
just go now to the customers so
14:36:58
우리는 단지 데이터베이스 테이블을 쿼리하고 있습니다.
now we are not querying the city right we are just querying
14:37:02
고객으로부터 고객 ID와
the database table that we have and i would like to get from
14:37:05
이름을 가져오고 싶습니다.
the customer the customer id and the
14:37:09
이름과 함께 성도 가져가겠습니다.
first name and let's go and get as well
14:37:12
이제 쿼리하면 출력에서 무슨 일이 일어날까요?
the last name so now if
14:37:15
우리는 실제로 데이터를 완전히 가져오고 있습니다.
we go and query this what happens in the output we
14:37:18
고객 데이터베이스 테이블에서 그리고 물론
are getting the data actually completely from
14:37:21
우리는 메인 쿼리에서 cte를 전혀 사용하지 않고 있습니다.
the database table the customers and of course
14:37:24
물론 그렇게 할 수 있지만 공간 낭비입니다.
we are not using at all the cte inside our main query
14:37:28
메모리에서 SQL이 이를 실행했기 때문에
of course we can do that but it's just waste of like space
14:37:31
메모리에 저장하고 데이터베이스 메모리에 저장했습니다.
in the memory because sql did execute this and
14:37:34
물론 우리는 메인 쿼리에서 도시를 사용하고 싶습니다.
stored it in the database memory and of course we would like to
14:37:37
그래서 조인을 하겠습니다.
use the city in our main query so let's go and do that
14:37:40
지금 우리가 하고 있는 것은 고객의 물리적 테이블과
so let's go and do a join but this time we're gonna join the data from the cte so So let's go and get the name and I will just call it CTS.
14:37:50
우리 쿼리에만 존재하는 도시로 만든 가상 테이블을 조인하는 것입니다.
So what we are doing now, we are joining the physical table that customers with the virtual table that we have created with the city that exists only in our query.
14:38:01
물론, 테이블을 조인하는 것뿐만 아니라 도시의 정보도 얻고 싶습니다.
And of course, not only you are joining the tables, we would like to get the information from the city.
14:38:07
그래서 CTS와 우리는 총 판매량만 필요합니다.
So CTS and we need only that total sales total sales.
14:38:14
즉, 세 개의 열은 고객 데이터베이스 테이블에서 가져오고, 이 열은 도시에서 가져옵니다.
So that means those three columns comes from our database table customers and only this column, the total sales comes from our city.
14:38:21
이제 전체를 실행해 보겠습니다. 출력에서 모든 것이 작동하는 것을 볼 수 있습니다.
So let's go and execute the whole thing. Now, as you can see, in the output, everything is working.
14:38:26
고객 테이블에서 세 개의 열을 가져왔고 각 고객에 대한 총 판매량이 있습니다.
We have the three columns from the table customers and we have the total sales for each customer.
14:38:32
그리고 이 총 판매량은 우리 도시에서 나옵니다. 마지막 고객은 여기서 null입니다.
And this total sales comes from our city. Now, as you can see, the last customer has a null over here.
14:38:37
주문 테이블에 고객 5가 없기 때문입니다.
And that's because in the table orders, we don't have the customer five.
14:38:42
그리고 이제 중간 결과를 보고 싶다고 할 수 있습니다.
and now you might say you know what i would like to see the intermediate result
14:38:45
CTE에서 현재 출력에서 보고 있는 것은
from the cte because what we are seeing now in the output is
14:38:48
주 쿼리의 최종 결과입니다.
the final result from the main query so
14:38:51
이제 도시의 결과를 보기 위해 할 수 있는 것은
now what we can do in order to see the result of the city
14:38:54
쿼리를 도시의
we're gonna mark the query in the city of
14:38:58
괄호 없이 실행하고, 그러면 출력에서 볼 수 있습니다.
course without any parentheses or the will so just the query
14:39:01
우리가 주 쿼리에 전달하는 중간 결과입니다.
and execute it and with that you can see in the output the
14:39:04
주 쿼리에 전달하는 중간 결과입니다.
intermediate results that we are passing to the main
14:39:07
여기 고객 번호 5가 없다는 것을 알 수 있습니다.
query and as you can see we don't have here customer number
14:39:10
그래서 최종 결과에서 null을 얻고 있습니다.
five that's why in the final results we are
14:39:13
왼쪽 조인을 사용하고 있기 때문입니다.
getting null and that's of course because we are using the
14:39:16
전체를 실행하면 고객 5가 여기 null로 표시됩니다.
left join so if i execute the whole thing you can see
14:39:19
CTE는 매우 간단합니다. 일반 데이터베이스처럼 다룹니다.
we are getting the customer five over here with the null so as you can see
14:39:22
하지만 이 테이블은 우리의 쿼리에서 생성됩니다.
cte is very simple we just treat it as any normal database
14:39:26
테이블이지만 이 테이블은 우리의 쿼리에서 생성되었습니다.
table but this table is created from our query that
14:39:29
우리가 여기 도시에서 정의한 것입니다. 물론 도시에서는 select from과 같은 모든 종류의 절을 사용할 수 있습니다.
we have defined in the city over here now of course in the city you can use any kind of clauses like select from
14:39:36
join, group by, having, 원하는 모든 것, window
join group by having everything that you want window
14:39:39
함수, 모든 집계 함수가 있지만 오직 하나만 있습니다.
functions all aggregate functions but there is only
14:39:42
하나의 제한이 있습니다.
one restriction you cannot go and use the
14:39:45
정렬할 수 없습니다.
order by clause so you cannot sort the
14:39:49
데이터를 정렬할 수 없습니다.
data in the city so let's go and try it out let's go and say order by and let's say i want to sort by the order id for example so let's go and execute it you can
14:40:00
정렬할 수 없습니다.
see here is clearly saying okay i cannot do it for you because
14:40:03
뷰나 서브쿼리에서 사용할 수 없습니다.
order by is not allowed in many things so you
14:40:06
공통 테이블 표현식에서 사용할 수 없습니다.
cannot use it in views in sub queries in
14:40:09
CTE에서 ORDER BY를 사용할 수 없습니다.
common table expressions the cte over here so it
14:40:12
물론 데이터는 정렬할 수 있습니다.
is not allowed you cannot use order by in the cte but
14:40:15
주 쿼리에서 정렬할 수 있습니다.
of course you can go and sort the data in the
14:40:19
고객 ID로 정렬할 수 있습니다.
main query so if you go over here and say order
14:40:22
실행하면 작동할 수 있습니다.
by customer id so
14:40:26
주 쿼리에서 ORDER BY를 사용할 수 있습니다.
if we execute it it can be working so in the main
14:40:29
도시에서는 사용할 수 없습니다.
query you can use order by but in the city this is
14:40:32
이것이 도시에서 사용할 수 없는 유일한 것입니다.
the only thing that you cannot use inside the city so
14:40:35
이것이 이 섹션의 첫 번째 도시입니다.
that's it this is our first city in this section
14:40:38
이것이 도시의 가장 간단한 형태입니다.
all right so this is the simplest form of the city
14:40:41
독립형입니다.
is a standalone now we can have not only one
14:40:44
여러 도시를 가질 수 있습니다.
city we can have multiple cities so
14:40:51
여러 도시가 있습니다.
it's gonna look like this we have our database and this time we don't have only
14:40:55
각 CTE가 데이터베이스로 직접 가고 있습니다.
one cte we have multiple cities in
14:40:58
데이터베이스를 쿼리할 것입니다.
our query and each cte is going directly to
14:41:01
중간 결과를 준비합니다.
the database and it will query the database in order to
14:41:05
네 개의 CTE가 데이터베이스로 가고 있습니다.
prepare the intermediate results so in this example
14:41:08
서로 다른 중간 결과를 준비합니다.
four ctes is going to the database and preparing four
14:41:11
SQL이 위에서 아래로 실행됩니다.
different intermediate results and of course sql
14:41:15
맨 위에서 아래로 실행할 거예요. 그래서 먼저 도시 하나부터 시작합니다.
gonna execute it from the top to the bottom so first the city one
14:41:18
그 다음 두, 세, 네 개가 있지만 서로 관련이 없습니다.
then two three four but they have nothing to do with each other's
14:41:21
이제 네 개의 중간 결과를 모두 얻었으니
so now once we have all the four intermediate results the
14:41:24
주 쿼리가 모든 정보를 검색하고
main query gonna go and retrieve all those informations and
14:41:27
최종 결과를 준비하기 위해 마법을 부릴 거예요.
do some magic in order to prepare the final result for the
14:41:30
최종 결과를 준비하기 위해 마법을 부릴 거예요. 이제 이 스케치를 보면
end user so now by looking to this sketch you can understand all
14:41:34
이 도시들은 서로 독립적이므로
those cities are independent from each other's so there
14:41:37
중첩이 없고 각 도시는 독립적으로 실행될 수 있습니다.
is no nesting or something each city is self-contained and
14:41:41
다른 도시나 다른 결과에 의존하지 않고
it could be executed on its own without depending
14:41:44
다른 쿼리와 관계없이 직접 데이터베이스에 접근합니다.
on any other results from any other city or any
14:41:48
데이터를 가져옵니다. 그래서 모든 것이 독립적입니다.
other query so it goes directly to the database and
14:41:51
도시들이고 여러 도시가 있으니
get the data so that's why all of them are standalone
14:41:54
독립적인 여러 도시입니다. 그게 전부입니다.
cities and since we have multiple cities then it
14:41:57
간단하니 이제 여러 독립적인 도시의 문법을 확인해 봅시다.
is standalone multiple cities that's it it's
14:42:00
독립적인 여러 도시입니다. 그게 전부입니다. 간단하니
simple so now let's check the syntax of the multiple standalone cities
14:42:03
우리의 첫 번째 도시를 작성하기 시작할 거예요. 그래서
so we're gonna start writing our first city so it
14:42:06
with 절로 시작하고 도시 이름이 있습니다.
starts with the with clause and then we have the city name
14:42:09
그리고 우리의 도시 논리가 있습니다. 새로운 것은 없습니다.
and then the logic of our city so nothing new this
14:42:13
이렇게 도시를 정의하고 사용하기 위해
is how we define the city and then in order to use it
14:42:16
주 쿼리를 작성할 거예요. 우리로부터 선택합니다.
we're gonna have our main query where we select from our
14:42:19
새로운 도시를 선택하고, 도시 이름을 사용합니다.
new city and we we make sure we are using the name of our
14:42:22
새로운 도시를 선택하고, 도시 이름을 사용합니다. 이제 다른
city so nothing new now in order to add another
14:42:25
도시를 쿼리에 추가하기 위해 할 수 있는 것은
city to our query what you can do we're gonna go after
14:42:28
도시 정의 뒤에 가서
the definition of the city and below it we're
14:42:32
도시를 정의하기 시작할 거예요. 하지만 이번에는 with 절을 사용하지 않고, 쉼표를 사용합니다.
gonna go and start defining the city too but this
14:42:35
이번에는 보시다시피 with 절을 사용하지 않고 쉼표를 사용하고 있습니다. 이는 첫 번째 도시만 with 절을 사용하여 SQL에 CTE에 대해 이야기하고 있음을 알리는 것입니다.
time as you can see we are not using the with clause we are using a comma so that means only the first city gonna be using the with clause in order to tell SQL we are talking about CTE.
14:42:47
모든 다른 CTE는 쉼표로 구분할 것입니다.
All the other CTEs you're going to separate it using the comma.
14:42:51
따라서 구문은 with 대신 쉼표가 될 것이고, 그 다음 CTE의 이름을 적고 다음 정의를 말할 것입니다.
So the syntax is going to be comma instead of with then the name of the CTE and then we're going to say as the following definition.
14:42:59
여기서 두 번째 CTE의 쿼리를 작성할 것입니다.
So we're going to write here the query of the second CTE.
14:43:02
물론 더 많은 CTE를 추가하고 싶다면 아래에 쉼표를 사용하고 세 번째 CTE를 정의할 수 있습니다.
So now of course if you want to go and add more CTEs you go and use the comma below it and as well you define the third CTE.
14:43:09
원하는 만큼 CTE를 가질 수 있으며 항상 쉼표로 구분해야 하지만
So you can have as much CTEs as you want and always separate it with comma but
14:43:14
첫 번째 도시는 width로 시작하고, 물론
only the first city start with the width and of course in the
14:43:17
주 쿼리에서 도시의 결과를 사용할 수 있습니다.
main query we can go and use the results from the city
14:43:20
여기서 예를 들어 데이터 간의 조인을 하고 있습니다.
2 where we are for example here joining the data between the
14:43:23
도시 1과 도시 2 사이에서, 여기서 주 쿼리에서 보시다시피
city 1 and city 2 so as you can see in the main query here we
14:43:26
이 다양한 도시에서 데이터를 수집하고 있습니다.
are like collecting the data from these different cities
14:43:30
주 쿼리에서 최종 단계를 수행하기 위해 시작합니다.
in order to do the final step in the main
14:43:33
쿼리는 width로 시작하므로 SQL은 이제 도시를 이야기하고 있음을 이해합니다.
query it starts with the width so sql understands okay now we are talking about city and once sql sees after the parentheses a comma sql can
14:43:41
SQL이 괄호 뒤에 쉼표를 보게 되면
understands okay now we are talking about another CTE and
14:43:44
SQL은 더 이상 CTE가 없음을 이해할 수 있습니다.
now if you don't go and use a comma after the parentheses SQL
14:43:47
다음 쿼리는 주 쿼리에 관한 것이므로 이렇게
can understand okay we don't have any more CTEs the next
14:43:51
여러 개의 독립적인 CTE를 생성하는 방법입니다.
query it's about the main query so this is how
14:43:54
이제 우리의 작업으로 돌아가서 보고서 단계를 생성하고 있습니다.
you create multiple standalone CTEs all right so
14:43:57
단계별로, 이제 작업에서 각 고객의 마지막 주문 날짜를 찾는 두 번째 단계가 있습니다.
now back to our task where we are creating like a report step
14:44:00
고객에 대한 추가 정보를 추가해야 합니다.
by step so now we have in the task a second step where it says find the last order date for each customer so now we have to go and add one more information
14:44:09
고객이 마지막으로 주문한 시점에 대한 정보입니다.
about our customer so when the last time the customer
14:44:12
이를 쿼리에 추가해야 하며 CTE도 사용하고 싶습니다.
did order so how we gonna do it now we have to add this
14:44:15
이 논리를 갖기 위해서입니다.
to our query and i would like to use as well the cte
14:44:18
첫 번째 작업에서 배운 대로, 이는
in order to have this logic so as we learned from the
14:44:21
각 고객의 총 매출을 찾기 위한 첫 번째 단계입니다.
first task this is the first step in
14:44:24
각 고객의 총 판매량을 찾기 위한 첫 단계입니다. 여기 주요 쿼리가 있습니다.
order to find the total sales for each customer and here we have the main query
14:44:28
이제 다른 CTE 사이에 'now'를 넣고 싶습니다. 문법에서 배운 대로 쉼표를 추가해야 합니다. 다시 'with'를 사용할 수 없습니다.
now i would like to put now in between another cte and as we learned from the syntax we have to go and add a comma we cannot go and use the with again
14:44:37
이름을 지정해야 하므로 CTE라고 부릅시다.
and we have to give it the name so let's call it cte and
14:44:40
마지막 주문을 가볍게 하고
last order so light it and
14:44:44
우리는 그것을 정의해야 하며, 그리고 두 개의 괄호를 추가해야 합니다.
we have to define it so as and then double parenthesis
14:44:47
이제 그 사이에 우리는 가서 우리의 논리를 추가해야 합니다.
now in between we have to go and add our logic so
14:44:50
이제 우리는 오직 이 논리에만 집중해야 하므로
now we have to focus only in this logic so forget about the
14:44:53
다른 ctes와 주요 쿼리는 잊어버리세요.
other ctes and the main query so we
14:44:56
각 고객의 마지막 주문 날짜를 찾아야 하므로 우리는 다시 테이블 orders를 쿼리할 것입니다. 필요한 것은 고객 ID와 주문 날짜입니다.
have to find the last order date for each customer so we're gonna go and query again the table orders so what do we need we need the customer id we need the order date
14:45:09
우리의 테이블 sales orders에서
from our table sales orders
14:45:12
지금은 이렇게 선택하고
so that's it for now we just select
14:45:15
실행하면 모든 고객과 모든 주문을 볼 수 있습니다. 하지만 우리는
it and execute it and now with that you can see all
14:45:19
각 고객의 가장 높은 주문을 원합니다.
the customers and as well all the orders but we would like
14:45:22
우리는 집계 함수인 max 함수를 사용할 수 있습니다.
to have the highest order for each customer and we
14:45:25
그래서 우리가 할 수 있는 것은 여기 위에서처럼
can go and use our aggregate function the max
14:45:28
max 함수를 사용하고 고객 ID로 그룹화해야 합니다.
function so what we can do it's like here on the top so
14:45:32
고객 ID로 그룹화하고 이렇게 이동시켜 보겠습니다. 이름을 주겠습니다.
we have to go and use the function max and group up
14:45:35
마지막 주문이라고 이렇게 하고, 보시다시피 저는 이제 제 쿼리만 선택하고 있습니다. 모든 것을 선택하지 않고
by the customer id so group up the customer id and let me just shift it like this and let's give it the name
14:45:45
계속 실행하여 결과를 확인합니다. 주요
last order so like this and as you can see i'm just selecting now only my query i'm not selecting
14:45:53
쿼리에 통합하기 전에
everything and i keep executing in order just to
14:45:56
이제 보시다시피 각 고객에 대해 한 행이 있습니다.
check the results before we integrate it in the main
14:45:59
각 고객에 대한 가장 높은 주문도 있습니다.
query so now as you can see we have for each customer one row
14:46:02
이로써 우리는 이 하위 작업을 해결했습니다. 보시다시피
and we have as well the highest order for each customer so
14:46:05
확장하는 것이 정말 쉽습니다. 저는 단지 또 다른 것을 만들고 있습니다.
with that we have solved this subtask so as you can
14:46:08
확장하기 정말 쉽습니다. 또 다른 상자를 만들고 그 안에 비즈니스 로직을 추가하고 있습니다.
see it's really easy to extend i'm just making like another
14:46:12
상자 안에 내가 원하는 비즈니스 로직을 추가하고 있습니다.
box and i'm adding inside it the business logic that
14:46:15
이것이 전체 작업에서 하나의 문제를 해결할 것입니다.
i want and this is going to solve one problem from the
14:46:18
이제 전체 작업의 힘을 느끼고 있습니다.
whole task so you feel now exactly the power of the
14:46:21
우리는 복잡한 로직을 만들고 있지만 여전히
CTE we are making complex logic but still it's
14:46:25
추가하기 쉽습니다. 이제 당신이 이것을 하지 않고 항상
easy to add now imagine you are not doing this you're always extending
14:46:28
하나의 큰 쿼리를 확장하고 있다면 정말 어렵습니다.
one big query it's gonna be really hard to extend and
14:46:31
그래서 많은 SQL 개발자들이 정말 좋아합니다.
that's why a lot of SQL developers really love
14:46:35
CTE를 사용하고 각 쿼리에서 사용하기를 좋아합니다.
using CTE and they like use it in each query
14:46:38
또는 그들이 가진 각 작업에서 우리는 이 작업을 해결했습니다.
or in each task that they have so we have solved this task and we have to go now integrate it in the main query it's gonna be very
14:46:45
이제 메인 쿼리에 통합해야 합니다. 매우
simple so we're gonna get over here and we
14:46:48
간단할 것입니다. 그래서 우리는 여기서
will go and just add another join so we're gonna join it
14:46:52
또 다른 조인을 추가할 것입니다. 그래서 우리는 그것을 조인할 것입니다.
with the cte and as you can see sql now is offering
14:46:55
CTE와 함께 사용하고 있으며, SQL이 지금 제공하는 것을 볼 수 있습니다.
it as a table even though it is not a physical table
14:46:58
물리적 테이블이 아니더라도 테이블로 제공됩니다.
that exists in our database it only lives inside
14:47:01
우리 데이터베이스에 존재하지 않는 테이블입니다.
our data but still sql treat it as a table and this is exactly what we are doing we treat those informations as table so city
14:47:08
우리 데이터 안에만 존재합니다. 그러나 SQL은 그것을 테이블로 취급합니다.
the last order and i will call it clo and then of course we have to go and do the same condition
14:47:16
그래서 도시의 정보를 테이블로 취급합니다.
like here so the cl o customer
14:47:19
마지막 주문을 호출하고, 물론 같은 조건을 적용해야 합니다.
id should be equal to the customer id from the first
14:47:22
여기서처럼 고객 ID는 첫 번째
table the customers and of course we have to go and add this
14:47:25
테이블의 고객 ID와 같아야 합니다.
new information to the main query so cl o the
14:47:29
이제 이 새로운 정보를 메인 쿼리에 추가해야 합니다.
last order so now what we're gonna do we're gonna go and
14:47:33
마지막 주문이므로 이제 우리가 할 일은
execute the whole thing so we have now two ctes and as well our main query so let's go and execute it now again let's check the data The first three columns comes from the physical table customers.
14:47:44
전체를 실행하는 것입니다. 이제 두 개의 CTE와 메인 쿼리가 있습니다.
The fourth one, the total sales, comes from our first CTE over here. So from here.
14:47:50
이제 다시 실행해 보겠습니다. 첫 세 개의 열은 물리적 테이블 고객에서 가져옵니다.
And the last order comes from our new CTE that we just defined, the CTE number two.
14:47:55
네 번째는 총 판매로, 여기 있는 첫 번째 CTE에서 가져옵니다.
So as you can see, guys, everything feels like organized and structured. And we have like flow.
14:48:01
물론, 이 CTE는 독립적인 CTE입니다. 그래서 우리는 항상 CTE를 선택하고 별도로 실행할 수 있습니다.
And of course, those CTEs are standalone CTEs. So we can go always and select the CTE and execute it separately.
14:48:08
이 쿼리 외부에서 다른 것이 필요하지 않습니다. 데이터베이스 내의 테이블만 필요합니다. 그러니 여러분, 다시 주목하세요.
It doesn't need anything else from outside this query. It just needs the tables inside your database. So guys, again, you pay attention.
14:48:16
더 많은 CTE를 추가하고 싶다면, 쉼표를 사용하세요. 예를 들어, 여기서 다른 너비를 가져올 수 없습니다. 그래서 실행하면 오류가 발생합니다.
If you want to add more CTEs, use the comma. You cannot go and use, for example, here I get another width. So if I execute it, I will get an error.
14:48:23
쉼표로 분리해야 하고, 제가 자주 하는 또 다른 실수는 마지막 CTE 쉼표에 추가하는 것을 잊는 것입니다.
So if you have to separate it to this comma and another mistake that I do frequently that I forget and go add here like to the last CTE comma.
14:48:32
많은 CTE를 사용하고 있다면 이런 일이 발생합니다. 이렇게 하면 오류가 발생합니다. 왜냐하면 주 쿼리는 쉼표가 필요하지 않기 때문입니다.
And this happens to me if I'm using a lot of CTEs. So if I go and do it like this, I will get as well an error because the main query doesn't need a comma.
14:48:42
마지막 CTE는 괄호 뒤에 쉼표가 없어야 합니다. 그래서 저는 그것을 제거하고 실행했습니다.
So the last CTE should not have a comma after the parentheses. So I just removed it and execute.
14:48:47
그래서 여러분, 이제 우리의 쿼리 안에 여러 CTE가 있습니다.
So guys, with that, we have now multiple CTEs inside our query.
14:48:55
좋습니다. 이제 중첩 CTE란 무엇인가요? 다른 CTE 안에 있는 CTE입니다.
All right. So now what is a nested CTE? It is a CTE inside another CTE.
14:49:00
그래서 서브쿼리와 비슷합니다. 쿼리 안에 있는 쿼리입니다.
So it's kind of like sub queries, a query inside another query.
14:49:04
주 쿼리만 CTE의 결과를 사용할 수 있는 것이 아니라, 다른 CTE도 CTE의 결과를 사용할 수 있습니다.
So not only a main query can use the result of CTE, another CTE can use the results from a CTE.
14:49:10
물론, 중첩 CTE는 주 쿼리가 다른 쿼리에 의존한다는 의미입니다.
And of course, the nested CTE is like a main query is depend on other queries.
14:49:15
즉, 선택하고 쿼리와 독립적으로 실행할 수 없다는 뜻입니다.
That means you cannot go and select it and run it independently from the query.
14:49:20
그래서 항상 중첩 CTE의 결과를 보기 전에 내부 CTE를 먼저 실행해야 합니다.
So always you have to run the CTE inside it first before seeing the result of the nested CTE.
14:49:26
좋습니다. 이제 이것이 의미하는 바를 이해해 봅시다. 다시 말해, 우리는 데이터베이스와 CTE 쿼리가 있습니다.
OK, so now let's understand what this means. Again, we have our database and we have a CTE query that goes directly to the database.
14:49:33
거기서 데이터를 쿼리하고 출력에서 우리는
and queries the data from there and in the output we will
14:49:36
중간 결과를 얻고, 이제 이 시나리오에서는
get the intermediate results and now in this scenario this
14:49:39
하나의 중간 결과만 있는 것이 아닙니다. 왜냐하면 우리는
time we will not have only one intermediate results because we
14:49:43
여러 가지 다른 단계가 필요하기 때문에 또 다른 중간 결과가 필요합니다.
have many different steps we need another intermediate
14:49:46
모든 것이 주 쿼리를 위해 준비되기 전에
results before everything is prepared for the main query
14:49:50
즉, 우리는 또 다른 단계가 필요하다는 뜻입니다.
so that means we have another step that's going to be built
14:49:53
첫 번째 중간 결과 위에
up on top of the first intermediate results
14:49:56
즉, 우리는 첫 번째 CTE의 결과를 쿼리하는 또 다른 CTE를 가질 수 있습니다.
so that means we can have another CTE that's
14:49:59
그 위에 또 다른 중간 결과를 구축할 것입니다.
going to be querying the results from the first CTE and
14:50:02
여기서 우리는 CTE1과 CTE2가 있습니다.
build on top of it another intermediate results so
14:50:06
그리고 이는 우리가 두 개의 중간 결과를 가지고 있다는 것을 의미합니다.
as you can see here we have CTE1 and CTE2
14:50:09
그리고 이는 우리가 두 개의 중간 결과를 가지고 있다는 것을 의미합니다.
and that means we now we have like two intermediate results
14:50:12
그리고 이제 물론 우리는 CTE3,4 등을 추가할 수 있지만 이제 CTE2가
and now of course we can go and add CTE3,4 and so on but now let's say that the CTE2 is going to prepare the
14:50:19
주 쿼리를 위한 최종 중간 결과를 준비할 것이라고 가정해 봅시다.
final intermediate result for the main query so
14:50:22
이제 주 쿼리가 두 번째 중간 결과를 쿼리할 것입니다.
now the main query gonna go and query the second intermediate
14:50:26
결과를 얻고 최종 단계로 진행할 것입니다.
results and it's gonna do the final step where
14:50:29
최종 결과는 사용자에게 표시될 수 있으며, 물론
the final result can be presented for the user and of course if
14:50:32
필요한 경우 주 쿼리는
it is needed the main query can access not only
14:50:35
두 번째 CTE의 두 번째 중간 결과뿐만 아니라
the second intermediate results from the second cte but
14:50:38
CTE1의 첫 번째 중간 결과도 액세스할 수 있습니다. 이제 우리는 첫 번째 CTE를 독립형 CTE라고 부릅니다.
also the first intermediate result from the cte1 now we call the first cte a standalone cte because it doesn't depend on any intermediate results
14:50:48
왜냐하면 그것은 어떤 중간 결과에도 의존하지 않기 때문입니다.
it goes directly to database and gets the data but now since the second cte is completely depending
14:50:55
cte1에서 이번에는 호출할 것입니다.
on the cte1 so this time we're gonna call
14:50:58
이 cte를 중첩 cte라고 부릅니다. 왜냐하면 우리는 갈 수 없기 때문입니다.
this cte a nested cte because we cannot go
14:51:01
그리고 그것을 독립적으로 실행할 수 있습니다. 항상 cte1에 의존합니다.
and execute it in its own it always depends on the city one
14:51:04
물론 주요 cte는 모든 것에 의존합니다. 그래서
and of course the main city is depending on everything so as
14:51:07
보시다시피 우리는 cte를 사용하고 있습니다. 우리는 체인처럼 구축할 것입니다. 이것이 우리가 독립형 cte와 중첩 cte로 의미하는 바입니다.
you can see we're using the ctes we're gonna go and build like a chain so this is what we mean with that standalone cte and nested cte okay so now let's understand the syntax of the nested cte
14:51:18
그래서 우리는 항상 WIS 절과 cte의 이름, 그리고 cte의 정의로 첫 번째 CTE를 정의하는 것으로 시작합니다.
So we start as usual with the definition of the first CTE using the WIS clause and then the name of the CTE and the definition of the CTE.
14:51:26
여기서는 새로운 것이 없습니다. 이제 우리는 배운 대로 쉼표를 사용하여 두 번째 CTE를 정의합니다. 그런 다음 cte의 이름과 정의입니다.
So here it's nothing new. Now we go and define the second CTE as we learned using the comma, then the name of the CTE and the definition.
14:51:35
이것이 우리의 CTE 번호 2입니다. 이제 두 번째 CTE는 첫 번째 CTE의 결과에 의존합니다.
So this is our CTE number two. So now the second CTE is depending on the results of the first CTE.
14:51:42
그럼 우리는 어떻게 할까요? 매우 간단합니다. 이제 cte 번호 2에 대해
So how are we going to do it? It's very simple. now for the cte
14:51:45
cte 번호 1에서 데이터를 선택할 것입니다.
number two we're going to select the data from the cte
14:51:48
그것으로 우리는 두 번째
number one and with that we are making the second
14:51:52
cte가 첫 번째 cte에 의존하도록 만들고 있습니다. 즉, 두 번째
cte depending on the first one so this means the second
14:51:55
cte는 첫 번째 cte에서 데이터를 가져오고 있으며
cte is getting the data from the first one and it's
14:51:58
두 번째 단계를 수행하기 위해 데이터를 쿼리하고 있습니다.
querying the data in order to do the second step and with
14:52:01
그것으로 우리는 하나의 cte를 다른 cte에 중첩하고 있으며 cte2는 완전히 첫 번째 cte에 의존하고 있습니다.
that we are nesting one cte in another and the cte2 is completely depending on the first one so again we
14:52:09
첫 번째 CTE는 독립형 CTE라고 부릅니다. 왜냐하면 아무것에도 의존하지 않기 때문입니다.
call the first CTE as standalone CTE because it doesn't depend on anything.
14:52:14
우리는 그것을 독립적으로 실행할 수 있으며, 데이터베이스에서 직접 데이터를 가져오기만 하면 됩니다.
We can execute it on its own and it just needs the data directly from the database.
14:52:19
하지만 두 번째 CTE는 첫 번째 CTE에 완전히 의존하기 때문에 우리는 그것을 중첩 CTE라고 부릅니다.
But the second CTE since it's completely depending on the CTE number one we call it a nested CTE.
14:52:25
그래서 매우 유사합니다. 우리는 단지 첫 번째 CTE에서 데이터를 선택하고 있습니다.
So they are very similar we are just selecting the data from the CTE number one.
14:52:30
이제 우리의 주요 쿼리가 시작되며, 물론 두 번째 단계의 데이터를 사용할 것입니다.
And now comes our main query and of course it's gonna go and use the data from the second step.
14:52:36
그래서 두 번째 CTE에서 데이터를 선택할 것입니다.
So it's gonna go and select the data from the CTE number two
14:52:39
하지만 여전히 규칙이 아니므로 접근할 수 있습니다.
but it's still of course it's not a rule it can go and
14:52:42
데이터에 접근하고 첫 번째 도시에서 데이터를 선택합니다.
access the data and select the data from the city number one
14:52:45
그래서 이렇게 중첩 도시를 만들 수 있습니다.
so this is how we can create a nested city in
14:52:48
SQL, 자 이제 우리 프로젝트로 돌아가서 고객에 대한 보고서를 생성하고 있습니다.
sql all right guys back to our project where we are creating
14:52:51
하나 더 추가하고 싶습니다.
a report about the customers and we would like to add one more
14:52:55
단계, 그래서 작업은 고객을 총 판매량에 따라 순위를 매기라고 합니다.
step so the task says rank the customers based
14:52:58
이 단계는 우리 프로젝트의 또 다른 단계이며, 도시를 사용하여 구현하고 싶습니다.
on total sales per customer so this is one more step inside our project and we would like to go and use as well the cities in order to implement
14:53:08
이 단계에서 우리는 고객을 순위 매겨야 합니다.
this step so now what do we need we need to rank the customers
14:53:11
각 고객의 총 판매량에 따라 두 단계가 필요합니다.
based on total sales for each customer so here like
14:53:14
첫 번째로 총 판매량을 계산해야 합니다.
we have two steps first we have to calculate the total sales
14:53:17
고객별로 그리고 나서 순위를 매겨야 합니다.
per customer and then we have to go and rank it
14:53:20
이 정보를 바탕으로, 그리고 물론 판매는 주문에 저장되어 있습니다.
based on this information and of course the sales are stores inside the orders so now let's go and start implementing the cte so we're gonna have a comma
14:53:30
이제 CTE를 구현하기 시작하겠습니다. 그래서 우리는 쉼표를 가질 것입니다.
and we're going to call it cte customer rank
14:53:33
그리고 우리는 그것을 CTE 고객 순위라고 부를 것입니다.
as and then we're gonna go have
14:53:36
괄호를 열고 그 안에서 이제 논리를 개발하겠습니다.
the parentheses and inside it we're gonna develop now the
14:53:40
먼저 데이터를 총 판매량에 따라 집계해야 합니다.
logic so first we have to go and aggregate the data by the
14:53:43
고객 ID를 선택하고 테이블 판매 주문에서 판매를 합산합니다.
total sales so select customer id and then sum the sales from the table sales orders
14:53:54
그리고 물론 고객으로 그룹화합니다.
and then of course group by the customer
14:53:58
이제 여러분이 '바라, 우리는 이미 이것을 했습니다.'라고 말하는 소리가 들립니다.
id and now i can hear you even telling me barra we
14:54:01
우리는 이미 이것을 했고 이미 이 논리를 가지고 있으니
have already done this we have already this logic so why
14:54:04
왜 반복하고 있는지
we are repeating if we go to the first cte
14:54:07
당신은 우리가 이미 그것을 했다는 것을 볼 수 있고 당신은 완전히 옳습니다
you can see we have already done that and you are totally right
14:54:10
우리는 이미 이 논리를 가지고 있으니 반복할 필요가 없습니다
we have already the logic so it makes no sense to repeat
14:54:14
다시 하고 만약 우리가 이렇게 한다면 우리는 이해하지 못한 것입니다
it again and if we do this then we didn't understood the
14:54:17
도시의 힘을 이해하지 못한 것이니 반복할 필요가 없습니다
power of the city so we don't have to repeat
14:54:20
같은 논리를 사용할 수 있고 도시를 재사용할 수 있습니다
the same logic and we can reuse the city
14:54:24
다른 도시 안에서 이제 우리는 모든 것을 필요로 하지 않습니다
inside another city so now we don't need all those
14:54:27
우리가 즉시 순위에 집중할 수 있도록
stuff we can go and focus immediately with ranking
14:54:30
고객 데이터를 선택하겠습니다
the customers so first let me just select the data from
14:54:33
첫 번째 도시에서 고객 ID와
the first city so i'm gonna go and select so
14:54:36
총 판매량을 선택할 것입니다
what do we have we have customer id and
14:54:40
이번에는 어떤 물리적 테이블에서가 아니라
we have total sales and we're gonna select it this time not from
14:54:46
우리의 CTE를 선택할 수 있습니다
any physical table we can select our CTE so
14:54:49
이렇게 하고 이제 우리가 할 것은 전체를 선택하고 실행하는 것입니다
like this and now what we're gonna do we're gonna go and select the
14:54:52
이것은 중첩 CTE의 문제입니다
whole thing and execute it well this is the
14:54:55
슬프게도 이 CTE는 첫 번째 CTE에 완전히 의존하므로 독립적으로 실행할 수 없습니다
issue of nesting CTEs sadly this CTE is completely depending on the first CTE, so we cannot go and execute it on its own.
14:55:05
물론 이것은 매우 성가신 일입니다
And this is of course very annoying, because each time I execute the query, by the end of the query, SQL gonna go and destroy all the CTEs.
14:55:15
메모리에서 CTE를 찾을 수 없습니다
So in the memory, we will not find the CTE.
14:55:18
그래서 내가 실행했을 때 SQL은 아무것도 모릅니다
And that's why once I executed it, SQL don't know anything
14:55:22
이 도시와 관련하여 이제 결과를 보려면
about this city and in order now to see the
14:55:25
항상 그것과 함께 실행해야 합니다
result of this we have always to execute as well with
14:55:28
내가 사용하는 도시와 함께
it the city that i'm using so what
14:55:31
나는 보통 여기에서 모든 것을 주석으로 처리합니다
i usually do i go over here and make
14:55:34
이제 전체를 실행할 수 있고 출력에서 이 중첩 도시의 결과를 볼 수 있습니다
everything in comment in the main query and
14:55:38
이제 전체를 실행할 수 있고, 이 중첩된 도시의 결과를 출력에서 볼 수 있습니다. 이것이 독립적인 도시와의 큰 차이점입니다.
now i can go and execute the whole thing and now i will see in the output the outcome of this nested city so this is the big difference between the standalone cities like here
14:55:48
이제 우리의 작업으로 돌아가서 순위를 매겨야 합니다.
and then listed so now let's go back to our task we have to rank
14:55:52
총 판매를 기준으로 이러한 판매를 정렬해야 합니다.
those sales based on the total sale so we
14:55:55
창 함수에서 순위 기능을 사용할 수 있습니다.
can go and use the rank function from
14:55:58
이제 데이터를 분할할 필요가 없고 정렬만 하면 됩니다.
the window function so rank over and
14:56:02
총 판매를 기준으로 데이터를 내림차순으로 정렬하고, 가장 높은 판매가 순위 1을 받게 됩니다. 고객이라는 이름을 부여합시다.
now we don't have to partition the data we just want to sort
14:56:05
이제 고객 순위를 볼 수 있습니다. 정말 멋진 순위가 있습니다.
the data by the total sales descending so like this the highest sales gonna get the rank number one so let's go and give it the name as customer
14:56:18
고객 3이 가장 높은 판매를 기록했습니다.
rank now as you can see we have a really nice rank beside
14:56:21
고객 2는 총 판매가 가장 낮습니다.
those informations customer three has the highest sales
14:56:24
보시다시피 우리는 반복하지 않았고, 우리는 단지
and customer two has the lowest total sales so with
14:56:27
현재 도시에서 다른 도시를 재사용했습니다.
that as you can see we didn't repeat ourselves we just
14:56:30
현재의 다른 도시를 재사용했습니다.
reused another city in our current
14:56:33
도시와 이 기술이 중복을 줄이고 복잡성을 줄이는 데 매우 놀라운 이유입니다.
city and this is exactly why this technique is very amazing in order to reduce redundancies and to reduce the complexity of the
14:56:41
전체 쿼리는 중첩이 실행하기 귀찮지만
whole query so nested are annoying to execute but
14:56:45
코드의 중복을 줄여줍니다.
they reduce the redundancies of our code now
14:56:48
이제 우리는 논리를 마쳤고 모든 것을 테스트했습니다. 그래서 우리가 할 것은
we are done with our logic we tested everything so what we're
14:56:51
주 쿼리에 통합하는 것입니다.
gonna do we're gonna go and integrate it in our main
14:56:54
여기서 주석을 제거하고 주 쿼리에 추가하겠습니다. 우리는 방금 만든 마지막 도시와 왼쪽 조인을 할 것입니다.
query so let me just remove the comments from here and let's go and add it in the main query so we will do the same thing we're gonna go and do a left join with the last city that we just created.
14:57:06
그래서 CCR이라고 부르겠습니다. 그리고 같은 조건입니다.
So let me just call it CCR and the same conditions.
14:57:10
우리는 항상 고객 ID로 조인하고 있지만 별칭 이름을 바꾸는 것을 잊지 마세요.
We are always joining on the customer ID, but don't forget to rename the alias.
14:57:16
따라서 CCR 고객 ID는 첫 번째 테이블의 고객 ID와 같습니다.
So it is CCR customer ID equal to the customer ID from the first table.
14:57:22
그리고 물론 새로운 정보를 선택해야 합니다. 그래서 CCR 점 고객 순위입니다.
And of course, we have to go and select the new information. So CCR dots customer rank.
14:57:30
이제 전체를 실행해 보겠습니다. 이제 결과에서
And now let's go and execute the whole thing. Now, as you can see
14:57:33
이 세 개의 열은 고객 테이블에서 오고 총 판매는
in the results those three columns comes from the customers table the total sales comes from the
14:57:39
첫 번째 도시에서, 마지막 주문은 두 번째 도시에서 왔습니다.
first city the last order from the second city
14:57:42
고객 등급은 우리의 중첩에서 나옵니다.
and the customer rank comes from our nested
14:57:46
우리가 방금 만든 도시이므로, 여러분, 이것은 간단한 작업이 아닙니다.
city that we just created so guys it is not a
14:57:49
이 보고서를 만드는 것은 간단한 작업이 아닙니다.
simple task creating such a report because
14:57:52
다양한 집계와 다양한 기능이 포함되지만, 우리의 작업은 잘 조직되어 있습니다.
it involves different aggregations and different functions but our work is organized as you can see it's very
14:57:59
매우 간단합니다. 우리는 단계 1, 단계 2, 단계 3과 주요 쿼리를 가지고 있습니다.
simple we have step one step two step three and the main
14:58:02
쿼리에 더 많은 구성 요소를 추가하는 것은 정말 쉽습니다.
query and it's really easy to add more components to
14:58:05
이 중첩 쿼리를 사용하여 계속 연습하고 싶습니다.
our query now i would like really to keep practicing using
14:58:09
우리는 보고서에 한 단계를 더 추가하고 싶습니다.
those nested queries so we have the following task we would
14:58:12
고객을 총 판매액에 따라 세분화하고 싶습니다.
like to add one more step in our report segment the
14:58:15
새로운 CTE를 추가하고 싶습니다. 그것은 CTE 고객 세그먼트가 될 것입니다.
customers based on their total sales so i would like to implement this as well using cte so let's go and solve it
14:58:23
그리고 우리는 우리의 논리를 정의해야 합니다.
we want to go and add a new cte it's going to be cte customer segments
14:58:30
우리의 작업을 확인하면 두 부분이 있습니다.
as and then we have to go and define our
14:58:33
총 판매액을 찾아야 하고, 그 다음에
logic now if you check our task it has two parts
14:58:36
이 정보를 바탕으로 고객을 세분화해야 합니다.
we have to find the total sales and then we have to
14:58:39
총 판매액을 다시 계산할 필요가 없습니다.
segment the customers based on this information so it is something very similar to what we have done in this step three so that means we don't
14:58:48
우리의 놀라운 첫 번째 도시를 사용해야 합니다.
have to go and calculate again the total sales we have to go and use
14:58:51
그럼 시작해 봅시다. 우리는 무엇이 필요합니까?
as well our amazing first city so
14:58:54
고객 ID가 필요합니다.
let's go and do it what do we need we need
14:58:57
기본 세분화를 위해 CASE WHEN을 사용합시다.
the customer id like this and
14:59:01
총 판매액이 이럴 때를 가정해 봅시다.
let's do basic segmentations using the case when so
14:59:04
100보다 높으면 고객은 높은 그룹에 속한다고 가정합시다.
let's say case when the total sales
14:59:08
100보다 높지 않으면 50보다 높으면 고객은 중간에 속합니다.
if it's higher than 100 then let's say the customer gonna belong to the group high and let's go and add another category
14:59:18
총 판매액이 50 이하이면, 그럼 어떻게 될까요?
If it's not higher than 100, if it is higher than 50, then the customer is going to belong to medium.
14:59:28
고객은 낮은 범주에 속합니다. 그래서 그게 전부입니다.
And if the total sales is less or equal to 50, so what's going to happen? We're going to say else.
14:59:34
고객은 낮은 범주에 속합니다. 그래서 그게 전부입니다.
The customer belongs to the low category. So that's it. We're going to have an end. And let's call it customer segments.
14:59:44
좋습니다. 하지만 물론 우리는 테이블에서 선택해야 하고, 그것이 우리의 도시가 될 것입니다.
All right. But of course we have to go and select it from a table and it's going to be our city.
14:59:49
총 판매량을 확인하고 우리의 새로운 도시에 넣어 봅시다.
So total sales and let's put it in our new city.
14:59:54
메인 쿼리에 넣기 전에 테스트해보고 싶습니다. 그래서 저는 넣을 것입니다.
And I would like to test it before like putting it inside our main query. That's why I will put.
15:00:00
모든 것을 제 메인 쿼리의 주석에 넣을 것입니다.
everything in comments in my main query since it is
15:00:03
안타깝게도 중첩된 도시이므로 우리는 그냥 가서
a nested city sadly and we will just go
15:00:06
우리의 새로운 중첩 도시를 선택합시다.
and select our new nested city like
15:00:10
우리가 이전에 했던 것처럼 실행해 봅시다.
we have done before so let's go and execute it
15:00:13
출력에서 두 명의 고객이 있습니다.
now as you can see in the output we have two customers with
15:00:16
고객 카테고리가 높고 두 명의 고객이 중간입니다.
the category high and two customers with the medium
15:00:19
모든 것이 완벽하게 작동하는지 확인하기 위해
but in order to make sure that everything working perfectly i would like
15:00:22
총 판매량을 추가해 보겠습니다. 숫자를 확인해 봅시다.
to go and add the total sales just to see the numbers so let's go and execute it well you can see everything is
15:00:29
모든 것이 맞습니다. 고객들은
correct so those customers having higher than
15:00:32
총 판매량이 100 이상이고 두 명은 50 이상입니다.
100 in the total sales and those two having higher than 50
15:00:36
주변을 바꿔 보겠습니다. 이렇게 하고 싶습니다.
but let's go and change stuff around i would like to have it like
15:00:39
중간으로 80을 설정하여 낮은 값을 가지도록 하겠습니다.
80 as a medium just in order to have a low so
15:00:42
그렇게 하면 고객 번호 2의 판매량이
with that the customer number two having a lower sales than
15:00:45
80보다 낮아지므로 우리는 저 카테고리를 얻고 있습니다.
80 that's why we are getting the segment low everything is
15:00:48
모든 것이 완료되었고 사용자를 다양한 카테고리로 분류했습니다.
done and we have segmented the users into different categories so i don't need to test anymore let's go integrate it in our main query so we're gonna do the same
15:00:58
더 이상 테스트할 필요가 없습니다. 메인 쿼리에 통합해 봅시다.
things over here we're gonna say left join and
15:01:01
여기서 왼쪽 조인을 말할 것입니다.
we're gonna get our new cte so
15:01:04
새로운 CTE를 가져올 것입니다.
ccs and we have to do
15:01:07
조인 조건을 잊지 마세요.
the join condition don't
15:01:11
변경해야 하고 새로운 것을 선택해야 합니다.
forget to change it and we have to select our new
15:01:14
좋은 정보입니다. 고객 세그먼트가 될 것입니다.
nice information it's gonna be the customer segments
15:01:17
이제 전체를 실행할 수 있습니다.
and now we can go and execute the whole thing
15:01:20
그래서 이제 우리는 네 개의 서로 다른 도시와 하나의 주요 쿼리를 가지고 있고, 출력에서 세 가지 모두를 볼 수 있습니다.
so we have now like four different cities and one main query and now we can see in the output we got all three
15:01:27
고객 테이블에서 첫 번째 도시의 정보입니다.
information from the table customers the first city second
15:01:30
세 번째 도시와 우리가 방금 생성한 새로운 열입니다.
third and this is our new column that we just created
15:01:33
다시 말해, 우리는 이렇게 필요에 의해 진행했습니다.
so again we have done this using a
15:01:36
이런 필요에 의해 추가하겠습니다.
necessity like this let me just add
15:01:39
그것과 그것은
it and it was
15:01:42
정말 쉽게 확장할 수 있었고 우리 보고서에 모든 것을 추가할 수 있었습니다.
really easy to extend and to add to our report all
15:01:45
좋아요, 여러분. 그래서 우리는 고객 정보를 다양한 측면에서 분석한 미니 프로젝트를 수행했습니다.
right guys so with that we have done like a mini project where we have analyzed the customer information based on different aspects
15:01:52
우리 데이터에서 단계별로 진행했습니다.
from our data and we have done it like step by step
15:01:55
이제 복잡한 SQL을 작성하는 방법에 대한 느낌을 가지게 되었습니다.
and now you have like a feeling on how to write complex SQL
15:01:58
CTE의 도움을 받아 쿼리를 작성하는 방법입니다.
queries using the help of the CTE and we have
15:02:01
단계별로 진행했으므로 스크립트를 살펴보면 알 수 있습니다.
done it like step by step so as you can see if you go
15:02:04
여러 단계로 나뉘어 있으며 각 블록은 전체 보고서의 특정 문제에 책임이 있습니다.
through the scripts you can understand okay it is divided into
15:02:08
이것이 바로 CTE의 힘입니다. 모듈성을 도입합니다.
multiple steps and each block is responsible for one specific problem of the whole report and this is exactly the power of the CTE, it introduces modularity.
15:02:18
각 CTE는 독립적이며 하나의 문제에 대해 이야기합니다.
So each CTE is self-contained and talks about one issue.
15:02:23
SQL을 사용하여 프로젝트를 조직하고 작업을 구조화하는 놀라운 방법입니다.
And this is an amazing way on how to organize your project using SQL and how to structure your work.
15:02:29
좋아요, 친구들. 이제 CTE에 대해 진지한 이야기를 나누기 위해 잠깐 쉬어봅시다.
All right, my friends, so now let's have a little break in order to have a real talk about the CTE.
15:02:37
하지만 먼저 커피 한 잔. 그리고 이제 저는 정말 오랫동안 SQL을 사용해왔습니다. 15년 이상입니다.
But first, some coffee. And now I can say that I'm working with SQL since a really long long time ago, over 15 years.
15:02:45
또한 다양한 프로젝트에서 많은 SQL 개발자를 만났다고 말할 수 있습니다.
And I can say as well, I have met a lot of SQL developers in different projects.
15:02:49
모든 SQL 개발자가 사랑하는 것이 있다면 그것은 CTE입니다. 그들은 어디서나 사용하기를 좋아합니다.
And if there is one thing that all those SQL developers love is the CTE. They love using it everywhere.
15:02:56
쿼리를 작성할 때마다 SQL CTE를 작성하게 될 것입니다. 물론 괜찮습니다. 나쁜 것이 아닙니다.
Like each time they write a query, they're going to be writing SQL CTE. And of course, it's fine. It's not a bad thing.
15:03:03
하지만 그 문제는 그들이 과도하게 사용하는 것입니다. 물론 모든 SQL 개발자가 그렇지는 않지만 많은 개발자가 CTE를 과도하게 사용합니다.
But the problem with that, they overuse it. Of course, not all of them passed a lot of SQL developers overuse using the CTE.
15:03:11
물론 CTE는 매우 강력하지만, 힘에는 큰 책임이 따릅니다.
Of course the CTE is very powerful but with power comes great responsibility.
15:03:16
큰 힘에는 큰 책임이 따른다는 것을 기억하세요.
Remember with great power comes great responsibility.
15:03:21
특히 CTE에 익숙하지 않은 경우 새로운 작업을 할 때마다 새로운 CTE를 추가하지 않도록 하세요.
So my advice for you especially if you are new to the CTE is that try to not add a new CTE each time you are doing something new.
15:03:29
특히 CTE에 익숙하지 않은 경우, 새로운 작업을 할 때마다 새로운 CTE를 추가하지 않도록 하세요.
And I saw it a lot like for each new calculation for each new column they jump immediately and create a new CTE.
15:03:35
결국에는 하나의 쿼리 안에 많은 CTE가 생길 수 있습니다.
And what happens at the end, we can have like massive number of CTEs inside one query.
15:03:40
개발자는 이제 모든 것이 정리되고 읽기 쉽다고 생각하지만, 믿으세요, 정반대입니다.
And the developer thinks now everything is organized and easy to read. But believe me, it's exactly the opposite.
15:03:47
코드를 열어보면 많은 CTE가 있고, 특히 중첩된 CTE가 있다면, 무슨 일이 일어나고 있는지 이해하기가 불가능합니다.
If you open any code and you have a lot of CTEs, and especially if there are nested CTEs, it is impossible to understand what is going on.
15:03:55
개발자가 각 CTE와 CTE의 작업을 설명하더라도 이해하고 읽기가 정말 어려울 것입니다.
Even if the developer like describe each CTE and the task of the CTE, it's going to be really hard to understand and as well to read.
15:04:02
모든 것이 중첩되어 있고, 하나의 쿼리에 20개의 도시가 있다면,
if everything is like nested and you have like i don't know 20 cities in one query
15:04:07
읽고 이해하기가 불가능할 것입니다.
so it's going to be impossible to read and to understand and as
15:04:10
메모리를 많이 사용하게 되고 성능이 나빠질 수 있습니다.
well you're going to be using a lot of memory and you might get
15:04:13
새로운 도시를 만들 때마다 어떻게 하면 좋을지 생각해보세요.
bad performance so my advice for you try always
15:04:16
두 도시를 하나로 합치는 것을 고려해보세요. 항상 도시 수를 줄이는 것이 중요합니다.
as you are creating new cities to think about how about to
15:04:19
하나의 쿼리에 몇 개의 CTE가 적당한지 물어보신다면, 마법의 숫자는 없습니다.
merge two cities in one so it is really always important to rethink and refactor your cities in order to merge it into one and to reduce the number of cities
15:04:30
보통 3개에서 5개의 CTE가 적당하다고 말합니다.
But now if you ask me how many CTEs are okay in one query? Well, I don't have a magic number for that.
15:04:35
그래야 이해하고 읽기가 쉬워집니다.
But normally I tend to say between three and five CTEs, it's fine.
15:04:40
하지만 5개 이상의 CTE가 생기면 코드를 다시 생각해야 합니다.
So it's going to be easy to understand and to read and so on.
15:04:43
모든 것을 하나의 쿼리에 넣지 않도록 다른 완전한 쿼리를 만들어야 할 수도 있습니다.
But once you get more than five CTEs, then you have to rethink your code.
15:04:48
프로젝트에서 CTE를 과도하게 사용하지 않도록 하세요. 각 단계마다 사용하지 마세요.
Maybe you have to create another complete query so you don't have to put everything in one query. So this is my advice for you.
15:04:54
항상 CTE를 리팩토링하고 통합하여 하나의 쿼리에 5개 이상의 CTE가 없도록 하세요.
Try to not overuse the CTEs in your project. Not for each step.
15:04:58
CTE를 책임감 있게 사용하고, 수업으로 돌아갑시다.
always refactor the CTEs, consolidate them, and try to not have more than five CTEs in one query.
15:05:05
독립형 CTE와 중첩 CTE를 배웠습니다. 두 가지 모두 비재귀 CTE라는 유형에 속합니다.
So that's my advice for you, be responsible using the CTEs, and let's go back to our course.
15:05:14
비재귀 CTE란 무엇인가요? 한 번만 실행되는 CTE를 의미합니다.
So with that, we have learned the standalone CTE and the nested CTE, and both of them belongs to a type called non-recursive CTE.
15:05:22
반복이나 루프가 없으므로 SQL은 한 번에 실행할 수 있습니다.
So what is a non-recursive CTE? It means it is a CTE that is executed only once.
15:05:27
반면에 재귀 CTE는 정반대입니다.
So there is no repetitions or looping or anything. So the SQL can execute it in one go and that's it.
15:05:33
재귀 CTE는 자기 참조 쿼리로, 특정 조건이 충족될 때까지 데이터를 반복적으로 처리합니다.
But in the other hand, the recursive CTE is exactly the opposite.
15:05:37
우리는 일반적으로 계층 구조가 있을 때 재귀 CTE를 사용하여 계층을 탐색합니다.
So a recursive CTE, it is a self referencing query that repeatedly processing the data until a certain condition is met.
15:05:46
이해하기 어려울 수 있지만 걱정하지 마세요. 아주 간단한 예를 들어볼 수 있습니다.
And we usually use the recursive CTE if we have like hierarchical structure and we want to navigate and travel through the hierarchy.
15:05:54
이것이 혼란스러울 수 있다는 것을 알지만 걱정하지 마세요. 우리는 매우 간단한 예를 가질 수 있습니다.
I know this might be confusing, but don't worry about it. We can have very simple examples.
15:05:58
이제 다시 데이터베이스에 테이블이 있고 CTE가 있습니다.
Now, again, we have our tables in the database and we have a CTE.
15:06:02
이제 CTE의 쿼리를 처음으로 실행할 수 있습니다.
Now the query of the CTE can be executed for the first time.
15:06:05
결과에는 CTE의 초기 데이터가 포함되지만 아직 모든 것이 아닙니다.
And in the results, we're going to have the initial data from the CTE, but it is not everything yet.
15:06:11
이제 이 중간 결과는 메인 쿼리에 사용할 준비가 되지 않았습니다.
Now, this intermediate result is not ready yet for the main query.
15:06:16
그 대신 CTE로 돌아갈 것입니다.
But instead of that, it's going to go back to the CTE
15:06:20
그리고 CTE는 현재 결과가 특정 조건을 충족하는지 확인할 것입니다.
and CTE gonna check whether the current results is meeting a specific condition.
15:06:25
이제 체크가 '아니오'라고 하면 조건을 충족하지 않는다면, 어떤 일이 발생할 수 있을까요?
So now if the check says no, it's not meeting the condition, what can happen?
15:06:30
CTE 쿼리는 두 번째로 실행될 수 있습니다. 보시다시피, 우리는 CTE를 반복하고 있습니다.
The CTE query can be executed for the second time. So as you can see, we are looping through the CTE.
15:06:36
이제 두 번째 반복의 결과, 두 번째 실행이 중간 결과에 추가될 것입니다.
Now the result of the second iteration, the second execution will be added to the intermediate results.
15:06:43
이제 중간 결과에 더 많은 데이터가 있습니다.
So now the intermediate result has more data.
15:06:47
그리고 다시, 메인 쿼리에서 사용하기 전에 CTE에서 확인할 수 있습니다. 결과가 조건을 충족합니까?
And again, before we can use it from the main query, it can be checked from the CTE. Does the result fulfill the condition?
15:06:55
아직 '아니오'라면, CTE를 다시 실행하십시오.
If it's still no, then go and execute the CTE again.
15:06:58
우리는 세 번째 반복을 가질 것이고 새로운 데이터가 중간 결과에 추가될 수 있습니다.
So we're going to have a third iteration and a new data can be added to the intermediate result.
15:07:04
이제 이것이 우리의 세 번째 반복입니다. 이제 CTE에서 다시 확인할 수 있습니다. 조건을 충족했습니까?
So this is our third iteration. Now it can be checked again from the CTE. Did we fulfill the condition?
15:07:10
답이 '예'라면, 루프를 종료하고 모든 것이 끝납니다. 따라서 CTE의 네 번째 반복은 없습니다.
If the answer is yes, then the loop can break and everything ends. So there will be no fourth iteration of the CTE.
15:07:17
그렇게 해서 CTE는 '좋아, 나는 끝났다. 이것이 중간 결과의 최종 결과다.'라고 말합니다.
So with that, the CTE says, OK, I'm done. This is the final result of the intermediate result.
15:07:24
그럼 루프가 종료되고 모든 것이 끝나며 CTE는 처음으로 실행되지 않을 것입니다.
Then the loop going to break and everything ends and the CTE will not be executed for the first time.
15:07:30
이제 CTE는 '좋아, 나는 끝났다. 이제 내 중간 결과가 메인 쿼리에서 사용될 준비가 되었다.'라고 말할 것입니다.
And now the CTE going to say, OK, I'm done. Now my intermediate result is ready to be used from the main query.
15:07:36
이제 새로운 일이 발생하지 않습니다. 메인 쿼리는 중간 결과에서 데이터를 검색하고 최종 결과를 준비하기 위해 마법을 부릴 것입니다.
And now nothing new happens. The main query going to go and retrieve the data from the intermediate results and do some magic in order to prepare the final results.
15:07:44
즉, 메인 쿼리 내부에서 반복이나 루프가 없을 것입니다. 루프는 오직 CTE에서만 발생할 것입니다.
So that means there will be no iterations or looping inside the main query. The looping is going to be happening only in the CTE.
15:07:51
그래서 우리는 이것을 재귀 CTE라고 부릅니다. 이제 다른 유형과 비교하면, 다른 모든 유형은 항상 한 방향으로만 진행됩니다.
And that's why we call it recursive CTE. So now if you compare it with the other types, all other types are always in one direction.
15:07:59
모든 CTE는 한 번만 실행될 것입니다.
And all the CTEs are going to be executed only once.
15:08:02
하지만 재귀 CTE는 조건이 충족될 때까지 계속 루프를 돌 것입니다.
But the recursive CTEs are going to keep looping until the condition is met.
15:08:07
그리고 그때만 메인 쿼리로 데이터를 전달할 것입니다.
And only then it's going to forward the data to the main query.
15:08:10
일반적으로 계층 구조를 탐색할 때 재귀 CTE를 사용합니다.
And normally we use the recursive CTEs if you are navigating through hierarchical structure.
15:08:15
데이터에 계층 구조가 있다면 재귀 CTE를 사용하여 탐색할 수 있습니다.
So if you have in your data like hierarchical structures, you can go and use the recursive CTEs in order to navigate through it.
15:08:22
이제 재귀 CTE의 구문을 확인해 보겠습니다.
So this is the recursive CTE. Okay, so now let's check the syntax of the recursive CTE.
15:08:27
조금 복잡하지만 단계별로 진행할 것입니다. 우리는 쿼리를 가지고 있으며 CTE에 넣고 싶습니다.
It's a little bit complicated, but we're going to do it step by step. So what do we have? We have a query and we would like to put it in a CTE.
15:08:34
일반적인 내용과 CTE의 이름, 쿼리를 포함해야 합니다.
So we're going to have the usual stuff with clause, the name of the CTE and as and then the query.
15:08:40
이제 CTE의 정의가 있습니다. 하지만 이렇게 두면 SQL은 한 번만 실행할 수 있습니다.
So this is the definition of our CTE. But now if you leave it like this, SQL can execute it only once. But we would like to make a loop iteration.
15:08:48
루프 반복을 만들고 싶습니다.
So in order to do that, we have to go and define a second select statement inside our CTE like this.
15:08:55
따라서 CTE 내부에 두 번째 SELECT 문을 정의해야 합니다.
So we are selecting the data and here we have to define a breaking condition.
15:09:00
여기서 데이터를 선택하고 중단 조건을 정의해야 합니다.
So here in the second query, we are defining a condition in order to break the loop.
15:09:05
여기서 두 번째 쿼리에서 루프를 중단할 조건을 정의합니다.
Otherwise, it's going to loop for infinite or the system going to break.
15:09:08
그렇지 않으면 무한 루프가 발생하거나 시스템이 중단됩니다.
You could use it in the where clause or you can use it even in an inner join because both of them are filtering the data and you can use it in order to break the condition.
15:09:16
WHERE 절이나 INNER JOIN에서도 사용할 수 있습니다.
All right. So now still there is something missing. How are we going to make like things looping? Well, we have to reference this CTE to itself.
15:09:23
두 쿼리 모두 데이터를 필터링하므로 조건을 중단하는 데 사용할 수 있습니다.
So what we're going to do, we're going to say the second query going to select the data from the same CTE.
15:09:29
자, 이제 여전히 뭔가 빠져 있습니다.
So that means we have now a query that is querying itself. And this is of course what we want.
15:09:34
우리는 이 CTE를 자기 자신에게 참조해야 합니다.
We want to make iterations and we want to make a loop. That's why we have to go and reference it to itself.
15:09:40
두 번째 쿼리는 같은 CTE에서 데이터를 선택할 것입니다.
And now in SQL you cannot have it like this. You cannot have like two select statements in one query. You have to connect it somehow.
15:09:47
즉, 자기 자신을 쿼리하는 쿼리가 생깁니다.
That's why we can go and use the union all or union. Depends if you want to have duplicates or not.
15:09:52
우리는 반복을 만들고 루프를 만들고 싶습니다.
So now we call the first query the anchor query.
15:09:55
이제 SQL에서는 이렇게 할 수 없습니다.
The anchor query is going to be the first query that interacts with
15:09:59
하나의 쿼리에서 두 개의 SELECT 문을 가질 수 없습니다.
database and provide us the initial intermediate
15:10:02
어떻게든 연결해야 합니다.
results so it is the starting point of the iteration
15:10:06
그래서 UNION ALL 또는 UNION을 사용할 수 있습니다.
and we can say it is the first step in the process
15:10:09
중복을 원하느냐에 따라 다릅니다.
so this is going to be executed only once and it's
15:10:12
이제 첫 번째 쿼리를 앵커 쿼리라고 부릅니다.
going to provide us the initial step the first step in the process now
15:10:16
앵커 쿼리는 데이터베이스와 상호 작용하는 첫 번째 쿼리가 될 것입니다.
we call the second step as a recursive query and we call it like this because this query going to be executed multiple times and it will
15:10:24
계속 반복하고 중간 결과에 데이터를 추가합니다
keep repeating and add data to the intermediate results
15:10:27
조건이 충족될 때까지
until the condition is met or
15:10:30
더 이상 처리할 수 있는 데이터가 없다고 가정해 봅시다
let's say there will be no more data that's available to
15:10:34
이것이 CTE 쿼리의 구문입니다
be processed so this is the syntax of the cte query for
15:10:37
메인 쿼리에서 아무것도 변경되지 않으므로
the main query nothing is changed so we have to go and use the city name in the main query so this is the syntax of the recursive city so think about it like this is going to go and execute
15:10:49
앵커 쿼리는 한 번만 실행되고
the anchor query only once and then after
15:10:52
그 후 재귀 쿼리를 거치게 됩니다
that is going to go through the recursive query and
15:10:56
특정 조건이 충족될 때까지 계속 반복합니다
keep looping and looping and iterating until
15:10:59
그 후 CTE에서 나가게 됩니다
a certain condition is met and then is going to go out
15:11:02
앵커와 재귀 쿼리에 대해 이야기하는 것입니다
from the cte so this is actually what we mean with the anchor
15:11:05
이제 재귀적 도시를 이해하기 위해 간단한 작업을 해봅시다
and recursive queries all right so now let's have a simple task in order to understand the recursive city so the task says generate a sequence of numbers from 1 to 20.
15:11:16
1부터 20까지의 숫자 시퀀스를 생성하라고 합니다
so now let's do it step by step so that means we have to create a loop
15:11:19
이제 단계별로 진행해 보겠습니다
from 1 to 20 and after 20 the loop
15:11:22
1부터 20까지의 숫자 시퀀스를 생성하라고 합니다
should stop so let's go and do it now the first step
15:11:26
20 이후에 루프는 멈춰야 합니다
of the recursive cte is to build the anchor query
15:11:29
이제 첫 번째 단계를 진행해 봅시다
so the anchor query is responsible for the first iteration so
15:11:33
재귀 CTE의 첫 번째 단계는 앵커 쿼리를 구축하는 것입니다
this means the first row of the output so what is the
15:11:36
앵커 쿼리는 첫 번째 반복을 담당합니다
first value between 1 and 20 it is the 1 so
15:11:39
이것은 출력의 첫 번째 행을 의미합니다
let's go and write a query that generate the value 1 so select and we're gonna say 1 as i'm
15:11:47
1과 20 사이의 첫 번째 값은 1입니다
gonna give it the name my number so
15:11:50
이제 1을 생성하는 쿼리를 작성해 보겠습니다
that's it let's go and execute it now you can see in
15:11:53
선택하고 1을 '내 숫자'라고 하겠습니다
the output we have the first member of our sequence
15:11:56
그게 다입니다, 이제 실행해 봅시다
and this is exactly the task of the anchor query it
15:12:00
출력에서 시퀀스의 첫 번째 항목을 볼 수 있습니다
retrieves the first step in the iteration so
15:12:03
앵커 쿼리의 정확한 작업입니다
let's go and call it anchor
15:12:06
다음 단계에 대해 쿼리하세요
query now the next step that's
15:12:10
우리는 반복을 구축해야 하므로 CTE가 필요합니다
we have to go and build the iteration so we need a cte so
15:12:13
이제 CTE를 구축할 것입니다
i will build now the cte so i'm going to say with
15:12:17
우리는 이를 심각하게 부를 것입니다
we're going to call it serious and then we're
15:12:20
모든 것을 괄호 안에 넣을 것입니다
going to put everything in parentheses and then we're
15:12:23
주 쿼리로 가야 합니다
going to go to the main query so this is the main query and
15:12:26
우리는 모든 것을 선택할 것입니다
we will go and select everything from the
15:12:30
도시를 실행해 보겠습니다
serious the city so let's go and execute it just to make sure that everything is working fine so we didn't create any loop or anything we have just created a city
15:12:40
주 쿼리에서 호출할 것입니다
on top on the anchor query and we just call it from the
15:12:44
재귀 도시를 구축하는 두 번째 단계입니다
main query so now we come to the second step of building
15:12:47
재귀 쿼리를 구축해야 합니다
the recursive city we have to build the recursive
15:12:50
이제 쿼리를 작성하기 전에
query so let's do it i will just make this a little bit smaller
15:12:53
모든 쿼리를 연결해야 합니다
and now before we start writing the query we have to go and
15:12:56
이것이 재귀 쿼리입니다
use union all in order to go and connect the anchor query with the recursive query and let me say
15:13:03
이것은 재귀 쿼리입니다.
this is the recursive query
15:13:07
그럼 어떻게 만들 건지 시작해 봅시다. 선택부터 시작하죠.
so how we're gonna build it let's go and start with the select
15:13:10
그리고 다음에 제가 보통 하는 것은 우리가
and now next what i usually do i just make sure that we
15:13:13
재귀 도시를 만들고 있다는 것을 확인하는 것입니다. 그래서 선택하는 것으로 시작합니다.
are making a recursive city so i go with selecting
15:13:16
그리고 나서 우리는
from and then we're going to use the name of the
15:13:19
현재 도시의 이름을 사용할 것입니다. 이렇게 하면 도시가 자기 자신을 참조하여 재귀적으로 만들고 루프를 수행할 수 있습니다. 이제 여기서
current city so that we are referencing the city to itself in order to make the city recursive and to do the looping now here comes
15:13:28
어려운 부분이 나옵니다. 우리는
the tricky part so we need to create like
15:13:31
시퀀스를 만들어야 합니다. 현재 값은
the sequence now what is the current value the current value
15:13:34
지금 하나입니다. 우리는 두 번째 값이 필요합니다.
is one right now what do we need we need the second value
15:13:37
시퀀스에서 두 번째 값은 두입니다. 그래서 우리는 이렇게 할 수 있습니다.
in the sequence which is two so we can do it
15:13:40
하나 더하기 하나로, 이렇게 하면 됩니다.
by one plus one so if you do it like this you
15:13:43
출력값은 2가 될 것이지만, 실제로 우리가 여기서 하고 있는 것은
will get the output two but actually what we are doing here we
15:13:46
현재 값을 항상 가져오고 있다는 것입니다.
are always taking the current value and we are saying
15:13:49
다음 값을 생성하기 위해 1을 더한다고 말하고 있습니다.
plus one in order to generate the next value
15:13:53
그렇게 하기 위해서 1이라고 말하는 대신
so in order to do that instead of saying one we're
15:13:56
현재 값인 내 숫자를 가져올 것입니다.
going to take the my number the current value and we
15:13:59
그것에 1을 더하여
can add to it plus one in order to generate the
15:14:02
수열의 두 번째 값을 생성할 수 있습니다.
second value in the sequence so that means my number
15:14:05
내 숫자는 항상 현재 값을 유지하고
always holds the current value and
15:14:08
다음 수열을 생성하기 위해 1을 더하는 작업을 수행합니다.
we do the operation plus one in order to generate the
15:14:12
이렇게 하면 현재 수열을 생성하고 있습니다.
next sequence so having it like this what you are doing
15:14:15
이렇게 실행하면, 제가 실행해 보겠습니다.
we are generating the sequence of numbers now
15:14:18
이렇게 실행하면 어떤 일이 발생할까요? SQL이
if you go and execute it like this let me just execute it
15:14:21
허용하지 않기 때문에 오류가 발생할 것입니다.
what will happen it gonna breaks because sql will not
15:14:24
SQL은 100번의 반복으로 설정되어 있습니다.
allow it and sql set it to 100 iterations
15:14:27
100번 이상이면 SQL이 쿼리를 중단합니다.
so more than 100 sql gonna break the query so
15:14:30
무한 루프가 없도록 하기 위해서입니다.
that we don't have infinite number of looping so
15:14:33
이것은 나쁜 것입니다. 우리는 중단 메커니즘을 정의하지 않았습니다.
this is bad because we didn't define the breaking mechanism
15:14:37
이제 우리는 재귀 쿼리에서 어떻게 루프가 끝나는지를 정의해야 합니다.
of the looping so now we have to define as well in the recursive
15:14:40
우리는 일반적으로 조건을 사용합니다. 예를 들어, WHERE를 사용할 수 있습니다.
query how the loop gonna ends and we usually
15:14:43
조건을 사용하여 계속 루프를 돌고
use a condition for example we can go and use the where
15:14:46
생성을 계속하되, 항상 값이
clause and we can say okay keep looping and keep
15:14:49
내 숫자가 작거나 같은지 확인해야 합니다.
generating but always check whether the value of
15:14:52
내 숫자는 20보다 적습니다
the my number is less
15:14:56
20보다 적어야 한다고 물어볼 수 있습니다
than 20 and you might ask okay it should
15:14:59
20보다 작거나 같아야 하죠, 맞나요? 하지만 아니요, 왜냐하면
be less or equal to 20 right well no because
15:15:02
20 이하로 만들면 어떤 일이 발생할 수 있을까요?
if you are making less and equal to 20 what can happen
15:15:05
내 숫자가 20과 같아지면 하나를 허용합니다.
once the my number is equal to 20 you are allowing one
15:15:09
출력에서 21을 얻기 위해 더 많은 반복을 합니다.
more iterations where you will get in the output 21
15:15:12
그래서 우리는 20으로 만들고 있습니다. 이제 실행해 보겠습니다. 시퀀스는 1, 2, 3, 4, 5로 시작하여 20에 도달할 때까지입니다.
so that's why we are making it with 20 so now let's go and execute it and let's check the sequence it starts with 1 2 3 4 5 and until reach the 20.
15:15:23
그래서 이를 통해 작업을 해결했습니다. 다시 말하지만, 여기서는 그렇게 어렵지 않죠? 우리는 단지 초기 단계를 제공하고 있습니다.
So with that, you have solved the task. Again, here, it's not that hard, right? We are just providing the initial step.
15:15:29
그리고 우리는 루프를 제공하고 있으며, 그 안에서 루프가 어떻게 끝날 수 있는지를 정의하고 있습니다.
And then we are providing the loop where we are defining inside it how the loop can ends.
15:15:35
이제 재귀 CTE로 할 수 있는 또 다른 것이 반복의 한계를 정의하는 것입니다.
Now there is one more thing that you can do with the recursive CTE is to define the limit of iterations.
15:15:40
예를 들어, 코드에서 이렇게 말할 수 있습니다. 만약 이 반복이 10회 이상 발생하면 SQL이 중단되어야 합니다.
So for example, in your code, if you say, okay, if this iterates more than 10 times, then the SQL should breaks and stops.
15:15:49
그래서 SQL에 대해 최대 개수를 정의할 수 있습니다.
So you can define for the SQL, the maximum number of
15:15:52
재귀 호출을 어떻게 할 수 있는지, 메인 쿼리에서 할 수 있습니다. 여기로 가서 옵션을 선택한 다음 두 개의 괄호를 열고 최대 재귀를 입력합니다.
recursions so how we can do that we can do that in the main query so if you go over here and say option then two parentheses and then max recursion
15:16:03
그 후에 한계를 정의할 수 있습니다. 예를 들어 10으로 가봅시다.
and after that you can define the limit so for example let's go with the 10.
15:16:08
물론 이제 우리 코드는 20회 이상 반복되고 있지만, 여기서는 10회 이상 거래하지 않아야 한다는 규칙을 만들고 있습니다.
now of course we are iterating in our code now more than 20 but here we are making the rule it should not trade more than 10.
15:16:15
이제 실행해 보겠습니다. 이제 SQL이 중단되고 최대 재귀가 10이라고 말하는 것을 볼 수 있습니다.
so let's go and execute it so now we can see that our sql breaks and it says the maximum recursion is 10.
15:16:21
출력에서 보시다시피, 10회 이상의 반복이 허용되지 않는 오류가 발생하고 있습니다.
So as you can see now in the output, we are getting the error of having more than 10 iterations, which is not allowed.
15:16:27
이를 통해 몇 번의 재귀를 가질 수 있는지 제어할 수 있습니다. 예를 들어 1,000회의 반복을 원한다고 가정해 보겠습니다.
So with that, you can control how many recursions you can have. Let's say that you would like to have like 1,000 iteration.
15:16:33
여기로 가서 1,000의 시퀀스를 원한다고 말하면, 이 주석을 달아보겠습니다.
So if you go over here and say, you know what, I would like to have a sequence of 1,000. If you, let me just comment this out.
15:16:40
실행하면 오류가 발생할 것입니다. 기본값은 100이기 때문입니다. 하지만 물론 최대 재귀를 늘릴 수 있습니다.
So if you execute it, you will get an error because the default is 100. But of course, you can go and increase the maximum recursion.
15:16:48
예를 들어 5,000으로 가봅시다.
for example let's go with five thousands in the output
15:16:51
작동할 것이고 1,000의 시퀀스를 얻을 수 있습니다.
it will work and you will get a sequence of one thousand so
15:16:54
이를 통해 쿼리에서 허용되는 반복 수를 제어할 수 있습니다.
with this you can control how many iterations are allowed in your query
15:16:57
그래서 이에 대한 제어가 가능합니다. 이제 우리는
so that you have like a control on it okay so now we
15:17:00
SQL이 재귀 쿼리를 어떻게 실행했는지 단계별로 이해할 수 있습니다.
can understand step by step how sql executed the recursive
15:17:04
여기에는 재귀 쿼리를 실행하는 과정의 단계를 이해하기 위한 흐름도 있습니다. 이제 시작해 보겠습니다. 첫 번째 단계는
query and here we have like flow diagram in order to understand the process the steps of executing the recursive query so let's go and do it now in the start we have the first step is
15:17:15
앵커 쿼리를 실행하는 것입니다. 우리의 앵커 쿼리는
to run the anchor query so our anchor query is
15:17:18
값 1을 선택하는 것입니다. 출력에서
just to select for the value one so in the output
15:17:21
우리는 내 숫자에서 값 1을 얻을 것입니다.
we will get the value one in my number and
15:17:24
앵커 쿼리는 한 번만 실행될 수 있습니다.
as you can see the anchor query can be executed only once
15:17:27
따라서 반복이나 SQL과 같은 것은 없습니다.
so there is no iterations or anything sql
15:17:31
한 번 실행된 후 다음 단계로 넘어갑니다.
executed once and then goes to the next step so
15:17:34
다음 단계는 재귀 쿼리를 실행하는 것입니다.
what is the next step is going to execute the recursive query so it's going to go over here and now what can happen we will get the current value of my number the current value is one
15:17:44
그런 다음 우리는 1을 추가할 수 있습니다.
and then we can add to it one so one plus one we will get from the recursive query
15:17:50
추가된 2는 이제 조건을 확인할 것입니다.
that two which is added to our results now is going to check the condition is my number now smaller than 20.
15:17:58
네, 20보다 작습니다.
well yes it's smaller than 20 and what's going to happen since it's true
15:18:03
재귀를 다시 실행할 것입니다.
it's going to go and re-execute the recursive
15:18:06
이제 두 번째 반복을 하고 있습니다.
query so now we are doing the second iteration so
15:18:09
현재 내 숫자의 값은 2입니다.
again it's going to go to the recursive query and i'm going to say
15:18:12
2 더하기 1, 두 번째 반복이 될 것입니다.
okay what is the current value of my number it is 2 so
15:18:16
값 3을 제공합니다.
2 plus 1 the second iteration will
15:18:19
재귀 쿼리가 실행될 때마다 더해집니다.
give us the value 3 so as you can see each time the
15:18:22
결과에 더 많은 값을 추가하고 있습니다.
recursive query is executed it is adding more
15:18:25
이제 내 숫자가 20보다 작은지 물어볼 수 있습니다.
values to our results so the same question
15:18:29
네, 작습니다.
could be asked is now my number smaller than
15:18:32
재귀 쿼리를 다시 실행할 것입니다.
20 well yes it is smaller well what's
15:18:35
이제 20이 내 숫자인지 물어볼 것입니다.
gonna happen is gonna re-execute the recursive query so it's gonna keep looping and iterating and adding values to the output until we reach the value 20.
15:18:47
20보다 작지 않으므로
so now is going to ask is 20 my number now
15:18:50
거짓입니다.
smaller than 20 well no so
15:18:53
체인이 끊어질 것입니다.
it is false and what can happen the chain will break and
15:18:57
더 이상 반복하지 않을 것입니다.
we will let loop anymore so it's gonna be the end of the city and this is gonna be the final results that's gonna be used from the main query so this is how sql executed this recursive city
15:19:09
이제 재귀 CDE에 대한 또 다른 작업을 해보겠습니다.
okay so now let's have another task for the recursive cde this
15:19:13
이번에는 조금 더 발전된 작업이 될 것입니다.
time it's going to be a little bit more advanced so the task says show
15:19:16
직원의 수준을 표시하여 직원 계층 구조를 보여줍니다.
the employee hierarchy by displaying each employee's level
15:19:20
조직 내에서 각 직원에 대해 각 행의 수준을 보여줘야 합니다.
within the organization so that means we have to show for each employee for each row a level that tells us the hierarchy of the employee so first let's go and explore the table employees
15:19:32
그럼 이제 판매 직원의 모든 것을 선택해 보겠습니다. 자, 실행해 보겠습니다.
So let's go and select everything from sales employees. Okay, let's go execute it.
15:19:38
결과를 보면 직원에 대한 몇 가지 정보가 있습니다.
So now by looking to the results, we have like few informations about the employee.
15:19:42
어느 부서인지, 성별 급여에 대한 정보가 있습니다. 그러나 여기서 키가 있습니다. 그것은 관리자 ID입니다.
We have information about which department, the gender salaries. But here we have the key. It is the manager ID.
15:19:48
이것은 같은 테이블을 자기 참조하는 것입니다. 예를 들어, 첫 번째 직원의 값은 null입니다.
So this is like self referencing to the same table. So for example, the first employee, the value is null.
15:19:55
이것은 이 직원에게 관리자가 없다는 것을 의미하며, 이 직원은
That means this employee has no manager, which makes this employee
15:20:00
큰 보스, CEO와 같습니다. 이제 다음 두 직원의 관리자가 ID 1을 가지고 있습니다.
Like the big boss, the CEO. Then now by looking to the next two employees, they have a manager ID one.
15:20:06
그 두 사람의 관리자는 누구인가요? 첫 번째 행, 관리자 ID 번호 1입니다.
So who is the manager of those two? It's going to be the first row, the manager ID number one.
15:20:12
관리자 ID 번호 1은 그 두 직원의 상사입니다.
So the manager ID number one is the boss of those two employees.
15:20:16
그리고 네 번째 직원의 경우, 관리자 ID 번호 2를 볼 수 있습니다. 그러니까 마이클의 관리자는 실제로 케빈입니다.
And then for the fourth one, we can see the manager ID number two. So the manager of Michael is actually Kevin.
15:20:23
두 번째 행. 그리고 캐롤의 경우, 관리자 ID는 3입니다. 즉, 메리가 캐롤의 관리자입니다.
The second row. And for Carol, the manager ID is three. That means Mary is the manager of Carol.
15:20:30
이것이 바로 우리가 재귀 CTE로 할 수 있는 것입니다. 이러한 정보를 사용하여 루프를 생성할 수 있습니다.
And this is exactly what we can do with the recursive CTEs. We can use such informations in order to create like a loop.
15:20:36
그럼 이제 단계별로 진행해 보겠습니다. 먼저, 평소처럼 앵커 쿼리로 시작할 수 있습니다.
So let's go and do it step by step. First, we can start with the anchor query as usual.
15:20:42
이것이 앵커 쿼리입니다.
So this is the anchor query.
15:20:46
그리고 첫 번째 단계 또는 첫 번째 레코드는 가장 높은 관리자, 즉 CEO가 될 것입니다.
And here's the first step or the first record going to be the highest manager, which is the CEO, right? The first record.
15:20:53
따라서 이제 첫 번째 레코드만 선택하려면 관리자 ID가 null인 것을 선택할 수 있습니다.
So in order to select now the only the first record what you can say we can say where manager ID is null.
15:21:03
그럼 이제 실행해 보겠습니다. 이제 첫 번째 행이 생겼고 이를 반복의 첫 단계로 사용할 수 있습니다.
So let's go and execute it and with that we have now the first row and we can use this as the first step in our iteration.
15:21:10
이제 선택에서 직원 ID와 이름, 그리고 관리자 ID를 가져와야 합니다. 이제 수준을 생성해야 합니다.
So now let's go and pick few informations in the selects like the employee ID and the first name and as well let's go and get the manager ID and now we have to start creating the levels right.
15:21:22
이것이 첫 번째 수준입니다. 그래서 나는 값을 1로 가질 것입니다.
So this is the first level. So I'm going to have the value one as let's have it like level.
15:21:28
우리 CEO는 수준 1을 가지고 있습니다. 자, 실행해 보겠습니다.
So our CEO has the level number one. So let's go and excuse it.
15:21:33
이제 프랭크가 CEO이고 그는 수준 1에 있다는 것을 알 수 있습니다.
So now as you can see, Frank is the CEO and he is in the level number one.
15:21:38
이것이 우리의 앵커 쿼리입니다. 이제 반복을 해야 합니다.
So this is our anchor query. Now we have to do the iteration, right? So we have to go and start creating the city.
15:21:46
CTE 직원 계층 구조로 호출해 보겠습니다. 그리고 이것이 우리의 정의입니다.
So let's call it with CTE employee hierarchy and then as and then this is the definition of our city.
15:21:56
이렇게 만들겠습니다. 그리고 물론, 우리가 필요한 것은 메인 쿼리입니다.
So let me just make it like this. And of course, what do we need? We need that main query.
15:22:01
그래서 메인 쿼리에서는 이렇게 새로운 도시에서 모든 것을 선택할 것입니다.
So main query, we will select everything from our new city like this.
15:22:10
자, 이제 테스트해 보겠습니다. 이제 CTE와 메인 쿼리를 준비했습니다.
So let's go and test it. All right, so now we have prepared the CTE and the main query.
15:22:16
물론 다음 단계는 재귀 쿼리를 구축하는 것입니다.
And of course, the next step is that we're going to go and build that recursive query.
15:22:20
하지만 먼저 두 쿼리와 재귀 쿼리를 연결하기 위해 union all이 필요합니다.
But first, we need that union all in order to connect the two queries and recursive query.
15:22:29
이제 논리를 구축할 수 있습니다. 이제 매니저가 직원 ID 번호 1인 모든 직원을 찾고자 합니다.
And now we can start building the logic. So now we want to find all the employees where their manager is the employee ID number one, right?
15:22:36
그들은 계층에서 두 번째 수준을 가질 수 있기 때문입니다. 그래서 우리가 할 것은 선택하는 것입니다.
Because they can have the second level in the hierarchy. So what we're going to do, we're going to go and select.
15:22:42
우리는 같은 정보를 필요로 하므로 직원 ID,
and we need the same stuff so we would like to get the employee id the
15:22:46
이름과 매니저 ID가 필요하며 레벨도 필요합니다.
first name and the manager id and we need the level so
15:22:49
이것은 레벨 2가 될 것이며 아직 정확하지 않습니다.
this is going to be the level number two it's not correct yet
15:22:52
하지만 이것이 의미하는 바를 보여주고 싶습니다.
but i just want to show what this means because
15:22:55
우리는 직원 ID와 이름 등을 가져와야 합니다.
we need to get the employee id and the first name and so on we
15:22:58
아직 도시에서 가져올 수 없습니다. 도시에는 직원이 한 명만 있기 때문에 데이터베이스에 가서 다음 직원을 가져와야 합니다. 이제 이것을 별칭으로 지정하겠습니다.
cannot get it yet from the city because in the city we have only one employee so we still have to go to the database and grab the next employees so now we'll give this as an alias
15:23:09
E와 같이 이 직원들로부터 선택하겠습니다.
like E and I will select it as well from those employees.
15:23:14
지금까지 우리는 재귀를 사용하고 있지 않습니다. 재귀 쿼리에서 여전히 데이터베이스를 쿼리하고 있습니다.
So, so far we are not doing any recursive yet, right? In the recursive query, we're still querying the database.
15:23:20
하지만 이제 이 테이블의 모든 직원이 필요하지 않습니다. 매니저 ID가 1인 모든 직원이 필요합니다.
But now we don't need all the employees from this table. We need all the employees where the manager ID equal to one, right?
15:23:28
이제 매니저가 1인 직원을 가져오기 위해, 예를 들어, 매니저 ID가 1이라고 말할 수 있습니다.
Now, of course, in order to get those employees where the manager equal to one, so we can do it with the word clouds, for example, and say manager ID equal to one.
15:23:38
이렇게 선택하고 쿼리하겠습니다. 이제 매니저가 CEO인 두 직원을 가져올 것입니다.
Let me just select this and query it. Now we will get those two employees where their manager is the CEO, the top manager.
15:23:46
하지만 물론 이렇게 할 수는 없습니다. 우리가 할 것은 이 테이블을 현재 CTE와 조인하여 루프를 만드는 것입니다.
But of course, we cannot do it like this. What we're going to do, we're going to join this table with our current CTE in order to make a loop.
15:23:54
제가 무슨 뜻인지 보여드리겠습니다. 이 부분을 제거하겠습니다. 우리는 내부 조인을 사용할 것이며 CTE에서 참조할 것입니다.
So let me show you what I mean. We will remove this. We're going to use the inner join and we're going to reference it from the CTE.
15:24:03
이름을 C-E-H로 지정하겠습니다. 이렇게 연결합니다.
And let's give this a name, C-E-H. And we connect it like this.
15:24:07
이제 직원의 매니저 ID가 직원 ID와 같아야 한다고 말할 것입니다.
So on we're going to say the manager ID of the employee should be equal to the employee ID.
15:24:15
시작할 때 직원 ID는 1일 수 있습니다. 그래서 이렇게 직원 ID가 될 것입니다.
So the employee ID at the start can be the number one. So it's going to be like this employee ID.
15:24:22
이제 매니저 ID와 직원 ID를 연결하고 있습니다.
Now we are connecting the manager ID with the employee ID.
15:24:26
그리고 우리는 반복을 만들기 위해 도시를 내부에서 재사용하고 있습니다.
And we are as well reusing the city inside itself in order to make the iterations.
15:24:32
여기서는 where 절이 필요하지 않습니다. 내부 조인이 데이터를 자동으로 필터링할 수 있기 때문입니다.
And here we don't need the where clause because the inner join can filter the data automatically.
15:24:37
우리가 배운 대로, 내부 조인은 왼쪽과 오른쪽에서 일치하는 행만 표시합니다. 즉, 필터링이 이루어질 것입니다.
As we learned, the inner join is going to show only the matching rows from the left and to the right. So that means there will be filtering.
15:24:44
우리는 거의 다 왔지만, 물론 2로 표시하고 싶지는 않습니다. 우리가 할 것은 이렇게 표시하는 것입니다.
So we are almost there, but of course we don't want to show it as a 2. What we're going to do, we're going to show it like this.
15:24:50
레벨 플러스 1. 현재 레벨은 1입니다. 두 번째 반복은 2가 될 것이고, 세 번째 반복은 3이 될 것입니다.
Level plus 1. So the current level is 1. The second iteration is going to be 2. And the third iteration is going to be 3.
15:24:57
그래서 우리는 반복을 위한 모든 것을 갖춘 것 같습니다. 잠시 확인하고 더 작게 만들어 보겠습니다.
So I think we have everything for our iteration. Let me just check and make this smaller.
15:25:03
다시 말해, 여기 우리의 앵커 쿼리가 있습니다. 이것은 최상위 관리자만을 위한 것입니다.
Now again, we have here our anchor query. This is only for the top level manager.
15:25:08
그리고 여기에서 우리는 관리자와 직원을 연결하고, 루프 효과를 만들기 위해 도시를 재사용하고 있습니다.
And then here we are just connecting the managers with the employees and we are reusing the city in order to make the effect of the loop.
15:25:17
또한, 우리는 더 이상 처리할 행이 없을 때 루프를 종료하기 위해 내부 조인을 사용하고 있습니다.
And as well, we are using the inner join in order to break the loop once there are no more rows to process.
15:25:23
그래서 실행해 보겠습니다. 이제 출력을 확인해 보겠습니다. 이것이 우리의 최상위 관리자입니다.
So let's go and execute it. Now let's check the output. This is our top manager.
15:25:28
레벨 1, 이 정보는 앵커 쿼리에서 옵니다.
So level one, this information comes from the anchor query.
15:25:32
그런 다음 두 번째 반복은 관리자 ID가 1인 직원들입니다.
Then the second iteration, it is the employees where the manager ID equal to one.
15:25:38
그래서 그 두 직원이 될 것입니다. 우리 계층에서 이 직원들은 조직의 두 번째 레벨입니다.
So it's going to be those two employees. So those employees in our hierarchy are the second level in our organization.
15:25:45
그런 다음 우리는 관리자 ID가 2 또는 3인 직원을 검색할 것입니다.
And then we're going to search for employees where their manager ID is equal to either two or three.
15:25:51
이 두 직원은 캐롤과 마이클이 될 것입니다. 이제 세 번째 반복을 위해 모든 직원을 검색할 것입니다.
And this is going to be those two employees Carol and Michael. And now to the third iteration we're going to search for all employees.
15:25:58
관리자 ID가 2 또는 3인 직원을 검색할 것입니다. 그리고 이 결과는 이 두 직원을 포함할 것입니다.
Where their manager ID equal to either 2 or 3. And now to the third iteration we're going to search for all employees.
15:26:06
관리자 ID가 2 또는 3입니다. 그리고 그들은 레벨 3을 받을 것입니다.
Where their manager ID equal to either 2 or 3. And this is going to results having those two employees.
15:26:12
관리자 ID가 2 또는 3입니다. 그리고 그들은 레벨 3을 받을 것입니다.
Because their manager ID is equal to 3 or 2. And they're going to get the level of 3.
15:26:17
그런 다음 SQL은 관리자 ID가 5와 4인 직원을 검색하려고 할 것입니다.
And then after that, SQL is going to try to search for employees where their manager ID equal to 5 and 4.
15:26:24
SQL은 아무것도 찾지 못할 것입니다. 그래서 이렇게 중단되는 것입니다. 그래서 우리는 이 작업을 해결했습니다. 알겠습니다.
And SQL will not find anything. And that's why it kind of breaks. So with that, we have solved the task. All right.
15:26:29
이것이 복잡하다면 완전히 이해합니다. 하지만 이제 우리는 SQL이 이것을 어떻게 실행했는지, 그리고 왜 이렇게 했는지 단계별로 진행할 것입니다.
I totally understand if this is complicated. But now we're going to do it step by step in order to understand how SQL executed this and why we have done it in this way.
15:26:38
다시 말해, 우리는 흐름 다이어그램이 있습니다. 우리는 앵커 쿼리를 실행한 다음 재귀 쿼리를 실행합니다.
So again, we have our flow diagram. We start by running the anchor query, then the recursive query.
15:26:45
그리고 나서 확인이 있습니다. 확인이 실패하면 반복하고 그렇지 않으면
And then we have a check. if the check fails we iterate otherwise
15:26:48
우리는 종료합니다. 그러니 여기서 단계별로 진행합시다.
we end so let's do it step by step here we have
15:26:51
직원 테이블이 있고 그 아래에 결과가 있습니다.
the table employees and beneath it we have the result of
15:26:55
CTE입니다. 첫 번째 단계는 앵커 쿼리를 실행한다고 말합니다.
the cte so the first step it says we run the anchor query
15:26:58
우리는 그것을 한 번만 실행합니다. 그래서 SQL은
and we run it only once so sql gonna go to the
15:27:01
우리는 직원 테이블에서 선택하고 있지만, 매니저 ID에 필터를 적용하고 있습니다. 매니저 ID는 null이어야 합니다.
anchor query and start executing it so here we are selecting from the table employees but we are making a filter on the manager id so the manager ID should be null.
15:27:10
즉, 우리는 프랭크의 기록을 가져올 것이고, 프랭크가 출력에 나타날 것입니다.
So that means we will get the record of Frank and Frank going to be at the output.
15:27:17
이 직원의 수준은 1이라고 말하고 있습니다. 그래서 우리는 여기에서 수준 1을 가질 것입니다.
And we are saying the level of this employee is one. So we will have here at the level one.
15:27:22
이것이 앵커 쿼리의 출력입니다. 이건 실행되지 않을 것입니다. 이제 다음 단계로 넘어갑니다.
So this is the output of the anchor query. And that's it. This will never be executed. Now we go to the next step.
15:27:30
이제 재귀 쿼리를 실행할 것입니다. 무슨 일이 일어날까요?
Now we will run the recursive query. So what's going to happen?
15:27:34
재귀 쿼리에서 우리는 직원 데이터도 선택하고 싶다고 말하고 있습니다.
In the recursive query, we are saying, OK, I would like to select as well data from the employees
15:27:38
CTE 결과와 조인할 것입니다. 하지만
and join it with the CTE results but
15:27:41
조인은 내부 조인이 되어야 하므로 일치하는 데이터만
the join should be an inner join so only the matching data
15:27:44
CTE와 직원 간의 조인 조건이 이제 이 반복의 핵심입니다.
between the CTE and the employees and now comes the
15:27:47
우리는 직원의 매니저 ID가
join condition and this is the key for this iteration
15:27:50
우리는 직원의 관리자 ID가
we are saying the manager id of the employee should
15:27:54
CTE의 직원 ID와 일치해야 한다고 말하고 있으므로 SQL은 테이블을 CTE와 조인할 것입니다. 그래서 여기에는 직원만 있습니다.
be matching to the employee id from the CTE so SQL gonna go and join the table with the CTE so now we have here only employee
15:28:02
번호 ID 하나이므로 단계별로 검색을 진행할 것입니다.
number ID one so it's going to do it step by step searching
15:28:05
일치하는 항목을 찾기 위해서입니다. 첫 번째 항목에 대해서는 일치하지 않습니다.
for any matches so for the first one we don't
15:28:09
매치가 없기 때문에 관리자 ID가
have a match because the manager ID is not equal to
15:28:12
하나와 같지 않으므로 결과에 포함되지 않을 것입니다.
one so that's why it will not be included in the result that
15:28:15
두 번째 행에서 관리자 ID는 하나와 같고, 이는 직원 ID와 일치하므로 이를 가져와서 출력에 넣을 것입니다. 뿐만 아니라 레벨을 증가시킬 것입니다.
the second row here the manager ID is equal to one and this is a match with the employee ID so it's going to take it and put it at the output not only that it's going to increase
15:28:27
현재 값은 하나이므로
the level so we have here the current value is one so
15:28:30
레벨 플러스 하나가 발생할 수 있습니다. 우리는
level plus one what can happen we will get the
15:28:33
값이 두 개가 될 것입니다. 우리는 여전히 같은 반복 안에 있습니다. 우리는 아직 반복하고 있지 않습니다.
value two we are still in the same iteration we are not iterating
15:28:37
그래서 이것은 재귀 쿼리의 첫 번째 반복입니다.
yet so this is the first iteration of the recursive
15:28:40
전체 조인이 완료될 때까지
query so until the whole join is done to
15:28:44
다음 행에서도 일치하는 항목이 있습니다. 왜냐하면
the next row we have a match as well because
15:28:47
관리자 ID가 하나와 같고, 레벨도 마찬가지일 것입니다. 레벨의 값이 변하지 않았기 때문에 여전히 현재 값입니다.
the manager id is equal to one and we're going to have the same thing the level going to be as well too because the value of the level didn't change it's still the current value
15:28:56
하나는 여전히 같고 계속 진행될 것입니다. 두, 셋은 일치하는 항목이 없으며, 그와 함께
is equal to one and it's going to keep going so two three we don't have any matches and with that
15:29:02
SQL 실행이 완료되었습니다.
sql is done executing the recursive query all
15:29:05
이제 SQL이 모든 것을 처리했는지 확인할 것입니다.
right so now the sql gonna say okay did we process everything
15:29:09
아니요, 여전히 출력이 누락되었습니다.
well no we still have missing output we
15:29:12
여전히 누락된 직원이 있습니다. 그래서 조건을 충족하지 못했습니다.
still have missing employees that's why we didn't fulfill
15:29:15
조건을 충족하지 못했기 때문에 다시 실행할 것입니다.
the condition and we're gonna run this again so now
15:29:18
두 번째 반복에서는 도시 결과와 직원들을 매니저 ID로 연결할 것입니다.
in the second iteration is going to join as well again the city result with the employees by matching the manager id and the
15:29:26
직원 ID에만 집중할 것입니다.
employee ID but this time it's going to focus only on those two
15:29:29
두 개의 ID를 찾을 것입니다.
IDs so the two and three so it's
15:29:32
매니저 ID가 2 또는 3인 경우를 찾을 것입니다.
going to go and find any matching where the manager
15:29:35
단계별로 진행할 것입니다. 첫 번째는 아닙니다.
ID equal to two or three so it's
15:29:38
두 번째도 아닙니다.
going to do it step by step the first one is not the second one
15:29:41
세 번째도 아닙니다. 매니저 ID가 1입니다.
is as well not the third one is not because the
15:29:45
직원 번호 4와 일치하므로 이를 출력에 추가할 것입니다.
manager ID is one but now to the employee number four we have a match so it's going to take this one and put it in the output like this.
15:29:55
이번 반복에서 현재 레벨은 무엇인가요?
And now in this iteration, what is the current level?
15:29:58
2입니다. 여기에 1을 추가합니다.
It is two, but we add to it one that's
15:30:01
그래서 출력에서 3을 얻을 것입니다.
why we will get in the output three and then it's
15:30:04
계속 진행할 것입니다. 직원 번호 5가 있습니다.
going to keep going so we have here the employee number five
15:30:08
매니저 ID가 3과 같으므로 결과에 추가됩니다.
and the manager id is equal to three so what happens
15:30:11
현재 레벨은 2 + 1입니다.
is scale takes it as well and put it in the output as the result of the cte and as well the current level is two plus one we We can have as well three.
15:30:21
그래서 SQL이 테이블을 조인하는 작업이 완료되었습니다.
So with that, SQL done joining the tables. And you're going to ask again, did we process all employees?
15:30:28
그렇습니다. 더 이상 반복할 필요가 없습니다.
Well, yes, it's true. That means we don't have to do any more iterations.
15:30:33
반복하면 SQL이 아무것도 찾지 못합니다.
Because if you do any iterations, SQL will not find anything. So for example, if you go over here, let me just remove this.
15:30:40
4와 5와 조인한다고 가정해봅시다.
And let's say we are joining with the four and five. So what can happen is SQL going to search in the manager's ID for four and five.
15:30:47
아무것도 찾지 못할 것입니다. 그래서 CTE에 추가하지 않습니다.
And it will not find anything. So that means we will not be adding anything to the CTE. That's why SQL stops.
15:30:53
모든 결과가 완전하며, 직원 데이터가 출력에 있습니다.
So we have a complete results and we have now all the data from the employees in the output.
15:30:58
이 결과는 메인 쿼리에 전달될 것입니다. 그래서 이렇게 한 이유입니다.
And this result is going to be passed to the main query. So this is why we have done it like this.
15:31:03
이것이 SQL이 이 재귀 쿼리를 실행한 방법입니다.
And this is how SQL executed this recursive query.
15:31:06
조직의 수준이나 구조가 무엇을 의미하는지 시각적으로 보여드리고 싶습니다. 계층 구조는 이렇게 생겼습니다.
I would like to visual for you what this means, the level or the structure of the organization. So the hierarchy looks like this.
15:31:13
1단계, 최고 관리자는 프랭크입니다. 그래서 이것이 1단계입니다.
The level one, the top manager is Frank. So this is the level number one.
15:31:19
그리고 우리는 2단계로 넘어갑니다. 그래서 두 명의 직원이 있습니다. 케빈이 있습니다.
And then we go to the level number two. So we have those two employees. So we have Kevin.
15:31:24
그래서 이것이 1단계입니다. 그리고 2단계에는 두 명의 직원, 케빈과 메리가 있습니다.
So this is the level number one. And then we have two employees, Kevin and Mary at the level two.
15:31:31
그들은 함께 일하고 그들의 상사는 프랭크입니다. 그래서 이렇게 보일 것입니다.
So they work together and their boss is Frank. So it's going to look like this.
15:31:38
그들은 2단계에 있습니다.
And they are at the level two.
15:31:41
그런 다음 마이클이 케빈에게 직접 보고합니다. 여기 직원 ID 2가 있습니다.
We have then Michael that directly reports to Kevin because here we have the employee ID 2 and 2.
15:31:49
여기 한 명의 직원이 있고, 캐롤도 3단계에 있으며, 그녀는 메리에게 보고합니다.
So we have one employee here and as well, Carol is as well at the level 3 and she reports to Mari.
15:31:57
마이클과 캐롤은 모두 3단계에 있습니다. 이것이 우리가 수준이라고 부르는 것입니다.
And both Michael and Carol are at the level 3. So this is what we mean with the level.
15:32:02
이것은 조직 내에서 어떤 직원이 어떤 수준에 있는지를 식별하는 데 도움이 될 수 있습니다.
It can help us to identify which employee at which level in the organization.
15:32:07
데이터에 계층 구조가 있는 경우
if you have like hierarchy in your data and
15:32:10
하나의 테이블에서 서로 참조하는 것을 볼 수 있습니다.
you can see in one table things are referencing each other's
15:32:14
여기서 관리자의 ID는 실제로 직원의 ID입니다.
like here the manager id is actually the employee id
15:32:17
우리는 이러한 ID를 서로 참조하고 있습니다. 이는 계층 구조가 있음을 의미합니다.
so it's like we are referencing those id to
15:32:20
서로 참조하고 있다는 것은 이 테이블에 구조가 있다는 것을 의미하며, 재귀적
each other's this means there is hierarchy and there
15:32:23
구성을 사용하여 이러한 수준을 구축할 수 있습니다.
is a structure in this table and you can use the recursive
15:32:26
그 수준을 쌓기 위해 도시
city in order to build those levels and
15:32:30
계층을 통해 탐색하는 것도 마찬가지입니다. 자, 이것이 재귀적 도시를 위한 모든 것이고, 이를 통해 SQL에서 우리가 가진 다양한 유형의 CTE를 모두 다루었습니다.
to navigate as well through the hierarchy all right so that's all for the recursive city and with that we have covered all the different types of CTEs that we have in SQL.
15:32:43
자, 이제 간단히 요약해 보겠습니다. 우리는 CTE, 즉 공통 테이블 표현식이 임시로 명명된 결과, 즉 쿼리의 여러 곳에서 사용할 수 있는 가상 테이블이라는 것을 배웠습니다.
So now let's have a quick recap. So we have learned that the CTE, the common table expression is a temporary named result, like a virtual table that could be used from different places in the query.
15:32:55
CTE의 많은 장점이 있습니다. 주요 장점은 쿼리의 복잡성을 작고 여러 조각으로 나누어 준다는 것입니다.
And we have a lot of advantages for the CTE. The main one is it breaks the complexity of query into small multiple pieces,
15:33:03
이로 인해 우리의 쿼리는 훨씬 더 읽기 쉽고 이해하기도 쉬워집니다. 따라서 가독성이 향상됩니다.
which makes our query much easier to read and as well to understand. So it improves readability.
15:33:08
CTE의 또 다른 장점은 이러한 작은 여러 조각들이 정말 관리하고 개발하기 쉽다는 것입니다.
Another advantage of the CTE is that those small multiple pieces, they are really easy to manage and to develop.
15:33:15
따라서 이러한 조각들은 자급자족 형태로, 우리의 쿼리를 더 모듈화하게 만듭니다.
So those pieces are like self-contained, which makes our queries more modular.
15:33:20
그래서 쿼리 내부에 모듈성을 도입합니다.
So it introduces modularity inside our queries.
15:33:23
그리고 CTE가 쿼리 내부의 중복성을 줄이는 데 도움이 된다는 것도 배웠습니다.
And we also learned that the CTE help us to reduce the redundancy inside our queries, where it makes the result of one query usable in multiple places inside our query.
15:33:35
그래서 코드가 더 작아지고 중복성이 줄어듭니다.
So it makes our code smaller and reduce redundancy.
15:33:38
그리고 CTE의 또 다른 장점은 재귀 CTE를 사용하여 SQL에서 반복 및 반복 작업을 수행하는 데 도움이 된다는 것입니다.
And one more advantage of the CTE is that it helps us to do looping and iterating in SQL by using the recursive CTE.
15:33:46
우리는 CTE 결과를 데이터베이스 내의 다른 물리적 테이블처럼 취급할 수 있다는 것도 이해했습니다.
And we have understood as well that we can treat the CTE result as any other physical table inside our database.
15:33:52
그래서 우리는 그것을 다른 테이블처럼 다룰 수 있습니다.
So we can treat it and handle it like any other tables.
15:33:55
이 테이블은 오직 하나의 쿼리에서만 존재한다는 단 하나의 예외가 있습니다.
only one exception that this table lives only
15:33:59
하나의 쿼리에서만 존재하므로 외부 쿼리에서 CTE를 쿼리할 수 없습니다.
in one query so we cannot query the cte from
15:34:02
이제 우리는 CTE의 결과를 메인 쿼리에서 사용할 수 있다는 것을 배웠습니다.
an external query now we have learned that the
15:34:05
이것은 고전적인 예입니다. 메인 쿼리에서 사용할 수 있을 뿐만 아니라 다른 CTE 쿼리에서도 사용할 수 있습니다.
result of the cte could be used from the main query this
15:34:08
도시 결과를 자기 자신 내에서 사용할 수 있습니다.
is the classical one but not only we can use it in the main query but also we can use it in another cte query which leads to having nested cities and of course we have learned as well
15:34:20
이로 인해 도시는 재귀적이 되어 반복이 가능해집니다.
we can use the result of the city within itself
15:34:24
그리고 반복이 가능하며, 다섯 개 이상의 도시를 한 쿼리에서 사용하지 않도록 권장합니다.
which makes the city recursive and allows for looping
15:34:27
그렇지 않으면 정반대의 결과를 얻을 것입니다.
and iterating and i can only keep recommending to
15:34:30
당신의 코드는 정말 이해하기 어렵고 읽기 힘들어질 것입니다.
not use more than five cities in one query otherwise
15:34:34
당신은 도시에서 정반대의 것과 이점을 얻게 될 것입니다.
you're gonna get the exact opposite and benefits from cities
15:34:37
이제 다음 단계에서는 새로운
where your code gonna be really hard to understand and to read and even to extend okay my friends so with that you have covered this amazing and very important technique in sql the common table expressions
15:34:48
데이터베이스에서 사용할 수 있는 객체 유형에 대해 이야기할 것입니다.
the city now in the next step we're going to talk about a new
15:34:51
이제 뷰에 대해 이야기해 보겠습니다. 뷰는 SQL에서 사용할 수 있는 쿼리와는 다릅니다.
type of objects that you can use in databases we don't have only tables we have as well views and views are amazing in order to give you dynamic and flexibility in your project.
15:35:00
데이터베이스에서 찾을 수 있는 객체입니다.
So let's talk about views. Now a view is not like a query that we can use in SQL.
15:35:10
그래서 뷰로 바로 넘어가기 전에 데이터베이스의 전체 구조를 알려드리고 싶습니다.
It is an object that we can find in the database.
15:35:13
SQL 서버는 이 계층 구조의 가장 높은 수준입니다.
So before we jump immediately to the view, I would like to give you the big picture, the whole structure of the database.
15:35:20
SQL 서버는 여러 데이터베이스를 관리합니다.
So let's go. like hierarchy structure and the highest level of this hierarchy is the SQL server.
15:35:27
이제 SQL 서버 내부에는 여러 데이터베이스가 있습니다.
The SQL server manages multiple databases. It's like the control center that keep everything running and accessible.
15:35:34
데이터베이스는 구조적으로 저장된 정보의 모음입니다.
Now inside the SQL server we have multiple databases.
15:35:38
데이터베이스는 구조화된 방식으로 저장된 정보의 모음입니다.
So a database is collection of informations that are stored in structure way.
15:35:43
모든 데이터가 보관되고 다양한 테이블과 객체로 조직됩니다.
It's where all your data is kept and organized in different tables and objects and each database is separated from others and it has its own data.
15:35:51
각 데이터베이스 안에는 여러 스키마가 있습니다.
Now inside each database we can find multiple schemas.
15:35:55
스키마는 관련된 객체를 그룹화하는 논리적인 방법입니다.
A schema is like a logical way on how you group up related objects like tables and views together within a database.
15:36:03
예를 들어, 판매라는 데이터베이스가 있다면, 주문에 대한 다양한 테이블을 스키마 주문 아래에 그룹화할 수 있습니다.
Like for example if you have a database called sales. We can group up different tables about the orders underneath the schema orders.
15:36:10
고객에 대한 여러 뷰와 테이블을 스키마 고객에 넣을 수 있습니다.
And maybe we have like multiple views and tables about the customers where we can put it in the schema customers.
15:36:17
같은 주제를 설명하는 여러 테이블과 뷰를 하나의 스키마 아래에 모읍니다.
So if you find like multiple tables and views that are describing the same object, the same topic, we put them all together underneath one schema.
15:36:25
판매 데이터베이스와 인사 데이터베이스는 완전히 다른 데이터 유형입니다.
So again, a database could be like the sales database and the HR database. They are completely different types of data.
15:36:32
판매 아래에는 주문과 고객에 대한 섹션이 있습니다.
And underneath the sales, we can have like different sections. We have sections about the orders and sections about the customers.
15:36:39
스키마 안에는 테이블이 있습니다. 테이블은 데이터가 실제로 저장되는 곳입니다.
And now moving on, what we can find inside the schema, we can find tables. A table is where actually your data is stored.
15:36:46
테이블은 여러 열과 행을 포함합니다.
It contains multiple columns and rows. So it is where the data physically lives.
15:36:51
스키마 안에는 뷰라는 또 다른 유형의 객체가 있습니다.
And now inside the schemas, we have another type of object. We call it view. And of course, in this section, we are focusing on the views.
15:36:58
뷰는 구조를 가진 가상 테이블입니다.
So a view is like a virtual table that has a structure and everything. But inside it, we don't have any data.
15:37:04
뷰는 데이터를 저장하지 않으며, 데이터를 보려면 쿼리를 실행해야 합니다.
So the view does not store any data. And in order to see the data, we have to execute the query behind the view.
15:37:12
그 후에 데이터를 볼 수 있습니다. 그러나 테이블과는 다릅니다.
And only after that, we can see some data. But it is not like the tables. it doesn't store the data permanently.
15:37:18
테이블 안에서는 열과 키를 정의할 수 있습니다.
Now inside the tables we can define multiple stuff like columns
15:37:21
뷰 안에서도 마찬가지로 여러 열을 정의할 수 있습니다.
and as well keys and the same thing for the views inside
15:37:24
각 열에 대해 이름과 데이터 유형을 정의할 수 있습니다.
the views we can define multiple columns and one last
15:37:27
데이터베이스는 매우 조직적입니다.
level for each column we have like a name and a
15:37:31
최상위 노드는 SQL 서버이고, 최하위 노드는 열과 행입니다.
data type so as you can see the databases are really organized and
15:37:34
데이터베이스 구조를 관리하기 위해 DDL이라는 명령어 세트를 사용합니다.
we have like hierarchy where the top node is the SQL server and the lowest node is the columns and rows so this is what we call the database structure.
15:37:44
DDL은 데이터베이스 구조를 정의하고 관리할 수 있는 명령어 세트입니다.
Now Now in order for you to build and manage this structure, we have set of commands, we call it DDL, the shortcut of data definition language.
15:37:53
데이터베이스, 스키마, 테이블, 뷰를 생성하는 명령어가 있습니다.
So the DDL is a set of commands that allow us to define and manage the structure of the database.
15:38:00
무언가를 생성한 후에는 변경 및 업데이트를 원할 수 있습니다.
So we have commands like create, where it helps us to create databases, schemas, tables, views, another command called alter.
15:38:08
데이터베이스 객체를 제거하기 위한 드롭 명령어도 있습니다.
Of course, after you create something, you would like maybe later to do changes and updates.
15:38:13
물론, 무언가를 만든 후에는 나중에 변경 및 업데이트를 하고 싶을 것입니다.
And of course, we have the drop in order to remove any database object like dropping a schema, dropping a database, tables, views.
15:38:20
그래서 보시다시피, DDL 명령은 데이터베이스 구조를 관리하는 데 도움이 될 수 있습니다.
So as you can see, the DDL commands can help us to manage the database structure.
15:38:25
이 그림에서 우리는 데이터베이스 내의 스키마 안에 뷰를 생성할 수 있다는 것을 이해했습니다.
So from this picture, we have understood that we can create views inside schemas in the database.
15:38:31
클라이언트와 객체 탐색기를 확인하면 정확한 계층 구조를 찾을 수 있습니다. SQL 서버로 시작합니다.
So now if you check the client and the object explorer, you can find the exact hierarchy. So it starts with the SQL server.
15:38:37
이것은 우리 머신에서 실행되는 로컬 서버입니다. 그 안에는 여러 데이터베이스가 있습니다.
This is our local server that's run at our machine. And then we can find inside it multiple databases.
15:38:43
그 중 하나는 여러분이 AdventureWorks와 함께 설치한 판매 데이터베이스입니다.
And one of them is our sales DB that you have installed together with other database like the AdventureWorks.
15:38:49
이곳의 판매 데이터베이스로 가면 다음 단계로 들어갈 수 있습니다. 여기에는 많은 객체가 있습니다.
So now if you go to the sales DB over here, you can go and drill to the next level. And now we can find here a lot of objects.
15:38:55
우리가 알고 있는 것 중 하나는 테이블과 뷰가 있다는 것입니다. 데이터베이스와 테이블 사이에는 스키마가 있습니다.
And one of them that we know, we have tables and views. And now you might say, okay, but between the database and tables, we have schemas.
15:39:03
스키마는 어디에 있나요? 사실, 테이블 안으로 들어가면 고객, 직원 등의 테이블을 찾을 수 있습니다.
So where are the schemas? Well, actually, if you go inside the tables, you can find our tables, customers, employees, so on.
15:39:10
하지만 그 전에 sales.customers라는 이름이 있습니다.
But before it, we have a name called sales dot customers.
15:39:14
그리고 sales, 고객, 직원 등에서 이를 어디서나 찾을 수 있습니다.
And you can find it everywhere sales, those customers sales, those employees and so on.
15:39:18
판매는 모든 테이블을 하나의 논리적 스키마 아래에 모으는 스키마입니다.
The sales is the schema that bring all those tables together underneath one logical schema.
15:39:25
우리는 sales DB라는 데이터베이스와 sales라는 스키마, 그리고 customers라는 테이블이 있습니다.
So we have a database called sales DB, we have a schema called sales, and we have a table called customers.
15:39:32
이 데이터베이스 내의 모든 스키마를 보려면, 보안으로 가면 됩니다.
And now if we would like to see all the schemas inside this database, what you can do, you can go to the securities over here.
15:39:37
여기에는 schemas라는 폴더가 있습니다. 그곳으로 가면 이 데이터베이스에 있는 모든 스키마 목록을 찾을 수 있습니다.
And then here we have like a folder called schemas. If you go over there, you will find the list of all schemas that we have in this database.
15:39:44
하지만 우리는 모든 것을 만들지 않았다고 말할 수 있습니다. 우리는 알고 있는 셀만 있습니다.
You might say, but we didn't create all those stuff. We have only the cells that we know.
15:39:48
SQL 서버에서 데이터베이스를 생성하면 서버가 생성할 수 있는 많은 시스템 기본 스키마를 얻게 됩니다.
Well, as you create a database in SQL server, you will get a lot of other system default schemas that the server can create.
15:39:56
그 중 하나는 많은 정보를 담고 있는 정보 스키마입니다.
One of them is the information schema where it holds a lot
15:40:00
그 카탈로그에 대한 뷰와 메타데이터가 있습니다.
the views about that catalog and the metadata where
15:40:03
여기에서 우리는 사용자를 위해 생성한 하나의 스키마, 즉 sales가 있습니다.
you can find the list of columns tables views and so on so here we have only one schema that we have created for the user it is the sales
15:40:10
이제 다시 돌아가서 하나의 테이블 안으로 들어가면
so let's go back now if you go inside one
15:40:13
여기에서 여러 가지 항목을 찾을 수 있습니다.
of those tables you will find here multiple stuff like we
15:40:16
열에는 키 제약 조건 등이 있으며, 만약
have columns keys constraints and so on and if
15:40:19
열로 가면 계층의 가장 낮은 수준에 도달하게 되고, 여기에는 고객 ID와 같은 열이 있으며 데이터 유형, 길이 등의 추가 정보가 있습니다.
you go to the columns you will end up at the lowest level of the hierarchy and here we have the columns like the customer ID and we have some extra information like the data type, length and so on.
15:40:30
그래서 이것이 데이터베이스의 구조와 계층입니다.
So this is the structure and hierarchy of databases.
15:40:37
이제 데이터베이스의 기본 개념을 이해해야 합니다.
Now I would like you to understand a fundamental concept on the database in order to understand the views, the three level architecture of the database.
15:40:45
이 아키텍처는 데이터베이스의 다양한 데이터 추상화 수준을 설명할 수 있습니다.
This architecture can describe the different levels of data abstractions in a database.
15:40:51
이 아키텍처는 세 가지 수준으로 나뉩니다. 첫 번째 수준은 물리적 수준입니다.
So let's see what this means. So the architecture is divided into three levels. The first level is the physical level.
15:40:57
그 다음은 논리적 수준입니다. 세 번째는 뷰 수준입니다.
Then we have the logical level. And the third one is the view level. Now let's understand each level what it means.
15:41:04
이제 물리적 수준에 대해 알아보겠습니다. 이는 실제 데이터가 물리적 저장소에 저장되는 데이터베이스의 가장 낮은 수준입니다.
So now the physical level. It is the lowest level of the database where the actual data is stored in a physical storage.
15:41:11
이 계층에 접근할 수 있는 사람은 데이터베이스 관리자입니다.
And usually who has access to this layer are the database administrators because they are the experts and they have to manage the access and the security of this layer.
15:41:22
그들은 성능 최적화, 보안 관리, 백업 및 복구 관리 등 많은 작업을 관리해야 합니다.
they are the experts that have to manage a lot of stuff like optimizing the performance, making sure that everything is secure, and managing the backup and recovery, and to do all the configurations and many other tasks.
15:41:34
그래서 물리적 계층에서는 많은 것들을 처리해야 합니다.
So at the physical layer, we have to deal with a lot of stuff like
15:41:38
데이터 파일, 파티션, 로그, 카탈로그, 블록 및 캐시와 같이 각 데이터베이스가 데이터를 저장하기 위해 필요한 많은 것들입니다.
the data files, partitions, logs, catalogs, blocks and caches, and many other stuff that each database needs in order to store your data.
15:41:47
보시다시피, 이 계층은 매우 복잡하며, 모든 것을 관리하려면 데이터베이스의 전문가가 되어야 합니다.
So as you can see, this layer is very complicated and you need to be really an expert of databases in order to be able to manage all those stuff.
15:41:56
그래서 우리는 이 계층을 물리적 계층이라고 부르거나 때때로 내부 계층이라고 부릅니다. 이제 다음 단계로 넘어갑시다.
So we call this layer a physical layer or sometimes we call it an internal layer. So now let's move to the next level.
15:42:03
논리적 수준이 있습니다. 논리적 계층은 물리적 계층보다 덜 복잡합니다.
We have the logical level. So the logical layer, it is less complicated than the physical layer.
15:42:08
이 수준에서는 데이터를 어떻게 조직할 것인지에 대해 다뤄야 합니다.
Here at this level, you have to deal on how to organize your data.
15:42:12
보통 여기에는 애플리케이션 개발자나 데이터 엔지니어가 있어 논리적 수준에 접근하여 데이터 구조를 정의합니다.
And normally we have here like an application developer or we have like data engineers that access the logical level in order to define the structure of your data.
15:42:22
그래서 이러한 개발자들은 데이터가 물리적으로 저장되는 방식보다는 데이터를 구조화하는 데 집중할 수 있습니다.
So those developers can focus on how to structure your data rather than how the data is exactly storing the data physically at the storage.
15:42:30
그들은 모든 세부 사항을 처리할 필요가 없습니다. 그들은 데이터베이스 관리자에게 맡기고 데이터 구조화에만 집중할 수 있습니다.
So they don't have to deal with all those details. They leave it for the database administrator and they can focus only on how to structure the data.
15:42:38
그래서 이러한 역할을 위해 필요합니다.
that's why we need for this kind of role an
15:42:41
그들에게는 논리적 수준의 추상화 계층이 필요합니다.
abstraction level for them which is the logical level
15:42:45
그렇다면 실제로 개발자들이 이 수준에서 무엇을 하고 있는지
so now what actually the developers are doing at this level
15:42:48
그들은 테이블을 생성하고 정의하고 있습니다.
well they are like creating tables and defining
15:42:51
그 테이블 간의 관계를 정의하거나
the relationships between those tables or they
15:42:54
뷰를 정의하고 인덱스를 생성할 수 있습니다.
can go and define views they can create indexes
15:42:57
테이블의 성능을 최적화하기 위해 테이블에 인덱스를 생성하거나, 저장 프로시저와 함수 및 기타 코드를 생성하여 이러한 테이블을 관리합니다.
on the tables in order to optimize the performance of the tables or maybe they are creating stored procedures and functions and some other codes in order to manage those tables.
15:43:08
보시다시피, 그들은 데이터 모델을 구축하고 있습니다. 그들은 데이터를 구조화하고 있지만, 데이터가 데이터베이스에 물리적으로 어디에 저장되는지는 전혀 신경 쓰지 않습니다.
So as you can see, they are building the data model. They are structuring your data, but they don't care at all where are those data stored physically in the database.
15:43:17
보시다시피, 여기서는 물리적 계층보다 덜 복잡하며, 개발자들이 프로젝트를 구축하기에 완벽한 추상화입니다.
So as you can see here, things are less complicated than the physical layer, and it is perfect abstraction for developers to build projects.
15:43:25
그래서 우리는 이것을 논리적 계층이라고 부르거나 때때로 개념적 계층이라고 부릅니다.
So we call this the logical layer, or sometimes we call it the conceptual layer.
15:43:30
좋아요, 이제 또 다른 추상화 수준으로 넘어가면, 우리는 뷰가 있습니다.
Okay, so now moving on to another level of abstraction, we have the view
15:43:34
뷰 수준은 가장 높은 수준입니다.
level so the view level is the highest level
15:43:37
데이터베이스에서의 추상화이며, 이는
of abstraction in the database and it is
15:43:40
최종 사용자와 애플리케이션이 접근할 수 있는 것입니다.
what the end users and applications can access
15:43:44
예를 들어 하나의 뷰를 가질 수 있습니다.
and can see so for example you could have like one view
15:43:47
비즈니스 분석가를 위해 적합한 뷰를 준비하고 사용자 정의합니다.
for business analysts so you prepare and customize
15:43:50
비즈니스 분석가에게만 적합한 뷰입니다.
views that are suitable only for
15:43:53
데이터 시각화 및 보고를 위해 적합한 다른 뷰 세트를 준비하자고 할 수 있습니다.
the business analysts and you might say you know what let's prepare another set of views that are suitable for
15:44:00
예를 들어 Power BI에 연결하여 대시보드를 생성할 수 있습니다.
data visualizations and reporting like you can
15:44:03
완전히 사용자 정의되고 준비된 뷰를 연결하기 위해서입니다.
go and connect for example a power bi in order to create dashboards so they are fully customized and prepared views in order to be connected with the
15:44:13
특정 목적과 사용 사례에 적합한 여러 세트의 뷰를 생성할 수 있습니다.
rbi reports and you can keep doing that by creating
15:44:17
뷰 수준에서 다뤄야 할 것은 무엇인가요?
multiple set of views that are suitable for specific purpose and use case so as you can see at this level we are exposing our data for multiple users and multiple applications.
15:44:28
사용 사례나 사용자에게 관련된 정보만 포함된 뷰가 있습니다.
So now the question is what do we have to deal at the view level?
15:44:31
이 수준의 사용자에게는 오직 뷰만 있습니다.
Well you have their only views that holds only the relevant information for the use case or users.
15:44:38
이것은 가장 높은 추상화 수준입니다.
So the users at this level have only views. They don't have to deal with the tables, indexes, source procedures, any files, logs, partitions or anything.
15:44:48
이 계층은 최종 사용자에게 친숙하고 소비하기 쉽게 만드는 데 초점을 맞추고 있습니다.
This is the highest level of abstraction because the focus of this layer is to make it friendly for the end users and easy to consume.
15:44:56
이 계층을 뷰 계층이라고 부르거나 때때로 외부 계층이라고 부릅니다.
So we call this layer the view layer or sometimes we call it an external layer.
15:45:01
이것은 데이터베이스의 세 가지 수준 아키텍처입니다.
So this is the three level architecture of the databases or we call it the three abstraction levels of the database.
15:45:08
물리적 계층은 가장 높은 복잡성과 가장 낮은 추상화를 가지고 있습니다.
So the physical layer has the highest complexity, the lowest abstraction and the view layer has the highest abstraction.
15:45:15
뷰 계층은 가장 높은 추상화를 가지고 있습니다.
So this is one more reason why the views are very important concept in SQL databases.
15:45:25
그래서 뷰가 SQL 데이터베이스에서 매우 중요한 개념인 이유입니다.
Okay, so with that we have enough fundamentals in order to start talking about the views. So the question is, what are views?
15:45:31
뷰는 실제로 데이터를 데이터베이스에 저장하지 않고 쿼리 결과를 기반으로 하는 SQL의 가상 테이블입니다.
A view is a virtual table in SQL that is based on the result of a query without actually storing the data in the database.
15:45:40
간단히 말해, 이는 뷰가 데이터베이스에 저장되거나 지속되는 SQL 쿼리라는 의미입니다.
So in short, this means views are stored or persisted SQL query in the database.
15:45:47
이것이 정확히 무엇을 의미하는지 이해해 봅시다.
So let's understand what this exactly means. Now, so far what you have learned, we have like a database table.
15:45:52
그리고 당신이 한 모든 작업으로 우리는 이 테이블에서 데이터를 검색하기 위해 선택 쿼리를 생성합니다.
and all what you have done we create a select query in order to retrieve the data from this table.
15:45:57
쿼리를 실행하면 결과를 다시 얻을 수 있습니다.
So once we execute our query we will get the result back.
15:46:00
이제 뷰에 대해 이야기하면, 뷰는 테이블의 구조를 가지고 있지만 내부에 데이터가 없습니다. 각 뷰에는 쿼리가 연결되어 있습니다.
Now if we are talking about views they have as well like the structure of the table but without any data inside it and for each view there is like a query attached to it.
15:46:12
데이터는 없지만 데이터를 가져오기 위한 쿼리가 있습니다.
So there is no data but we have like a query in order to get data.
15:46:15
정상 테이블을 물리적 테이블이라고 하고, 뷰는 가상 테이블이라고 부릅니다.
We call the normal table as a physical table and the view we call it a virtual table.
15:46:21
그렇다면 데이터를 어떻게 가져올 것인지, 이제 가서
So now how exactly we're gonna get the data so now if you go and
15:46:24
뷰에서 데이터를 선택하여 쿼리를 작성합니다.
write query by selecting data from the view not
15:46:27
테이블에서가 아니라 뷰에서 쿼리를 작성하면
from the table from the view what can happen is
15:46:30
테이블에서 뷰로, 발생할 수 있는 것은
ql gonna go and trigger the queue that is attached
15:46:33
연결된 큐를 트리거하게 됩니다.
to the view and this query is responsible to
15:46:37
물리적 테이블을 쿼리하고 결과는 뷰의 구조를 채우게 됩니다.
query the physical table and then the result gonna fill the structure of the view and we will get back of course the results so we are directly
15:46:45
뷰를 쿼리하지만 실제로는
querying a view but actually we are indirectly querying
15:46:49
물리적 테이블을 간접적으로 쿼리하는 것입니다.
a physical table so the view is like between us and
15:46:52
데이터는 데이터베이스 테이블에 저장되어 있으며, 뷰는 추상화입니다.
the data so that means my real data is stored inside
15:46:55
내 실제 데이터와의 사이에 있는 레이어입니다.
the database tables and the views are like an abstraction
15:46:58
물리적 테이블에 데이터가 저장되지 않으며,
layer between me and my real data and of
15:47:02
뷰를 쿼리할 때마다 뷰 뒤의 SQL 쿼리가 다시 실행될 수 있습니다.
course the data will not be stored inside the view each
15:47:05
이것이 우리가 SQL 뷰로 의미하는 것입니다.
time i'm querying the view what's gonna happen the sql query behind the view can be executed again so it's gonna go and retrieve the data and get it back to the view and then I will see it in the output.
15:47:16
이제 테이블과 뷰를 간단히 비교해 보겠습니다.
So this is what we mean with SQL view. So now let's have a quick comparison between tables and views.
15:47:25
테이블은 데이터베이스에 실제 데이터를 물리적으로 저장합니다.
Tables stores the actual data physically at a database.
15:47:29
데이터가 유지되는 테이블과는 달리, 뷰는 가상 테이블이며 데이터베이스에 데이터를 저장하지 않습니다.
So the tables where the data is persisted with, on the other hand, the views, they are virtual tables and they do not store any data inside the database, but they present the data from the underlying tables.
15:47:41
즉, 뷰는 물리적으로 데이터를 유지하지 않습니다.
So that means views don't persist any data physically
15:47:44
이제 테이블은 유지 관리가 어렵고
now the tables are hard to maintain and as well hard to
15:47:47
변경하기도 어렵습니다.
change so it needs a lot of efforts in order to do
15:47:50
열을 추가하고 이동하는 것과 같은 모든 변경은 많은 노력을 요구합니다.
any change like adding columns and moving columns always
15:47:53
마이그레이션에는 많은 노력이 필요합니다 특히
requires a lot of efforts for the migration especially
15:47:56
대규모 테이블이 있는 경우 하지만 반면에 뷰는
if you have large tables but in the other hand the views
15:47:59
유지 관리가 훨씬 쉽고 변경하기 매우 유연합니다. 당신이 해야 할 일은 뷰의 쿼리만 변경하는 것입니다. 즉, 테이블에 비해 뷰에서 빠르게 변경할 수 있습니다.
are way easier to maintain and very flexible to change all what you have to do is only to change the query of the view so that means you can very quickly change stuff in the views compared to the tables.
15:48:11
성능에 대해 이야기한다면, 테이블이 뷰보다 빠릅니다.
But if you are talking about performance, tables are faster than views.
15:48:15
예를 들어, 테이블에서 간단한 선택을 하면 데이터베이스가 데이터를 제공하는 즉시 데이터를 받을 수 있습니다.
For example, if you go and do a simple select on the table, you will get the data back as soon as the database features the data.
15:48:22
하지만 뷰에서 무언가를 선택하면 실제로 두 개의 쿼리가 있습니다.
But if you are selecting something from the view, it is actually two queries.
15:48:26
사용자로부터 오는 쿼리와 두 번째 쿼리는 뷰 쿼리입니다.
The query that comes from the user and as well the second query is the view query.
15:48:31
뷰의 쿼리는 기본 테이블에서 데이터를 추출하기 위해 매우 복잡할 수 있습니다.
And the query of the view could be very complicated in order to extract the data from the underlying table.
15:48:37
따라서 뷰에서 무언가를 선택하는 것은 항상 테이블에서 선택하는 것보다 느립니다.
So selecting something from the view is always slower than selecting something from a table.
15:48:42
이제 테이블이 있으면 테이블에서 읽을 수 있고 테이블에 쓸 수도 있습니다.
Now if you have a table you can read from the table and as well you can write to a table.
15:48:46
하지만 뷰는 읽기 전용입니다. 이름에서 알 수 있듯이 단지 뷰일 뿐입니다.
But the views are read only as the name says it is only a view.
15:48:51
뷰를 사용하여 데이터베이스에 무언가를 쓸 수 없습니다. 자, 이것이 뷰와 테이블 간의 큰 차이점입니다.
You cannot go and write something to the database using the view. Okay so those are the big differences between views and tables.
15:49:02
자, 이제 우리는 뷰가 무엇인지 명확히 이해했습니다. 하지만 이제 여러분은 왜 뷰가 필요한지 물어볼 수 있습니다.
All right so with that we have a clear understanding what are views. But now you might ask me why do we need views?
15:49:08
그래서 이제 우리가 할 일은 SQL 프로젝트에서 마주칠 수 있는 여러 시나리오와 사용 사례를 깊이 파고드는 것입니다.
That's why now what we're gonna do we're gonna deep dive into multiple scenarios and use cases that you might encounter in your SQL projects.
15:49:15
자, 첫 번째 사용 사례부터 시작해 보겠습니다. 첫 번째 사용 사례와 핵심
So let's start with the first use case. The first use case and the core
15:49:19
우리가 데이터 프로젝트에서 뷰를 사용하는 이유는
reason why we use views in our data projects is
15:49:22
복잡한 쿼리에서 중앙 논리를 저장하기 위해
to store central logic from a complex query
15:49:25
데이터베이스에 저장하여 모든 사람이 접근할 수 있도록 하고, 이를 통해 여러 쿼리 간의 재사용성을 개선하며 전체 프로젝트의 복잡성도 줄입니다.
in the database so that everyone can access it and with that we improve reusability between multiple queries and we reduce as well the complexity of the overall projects.
15:49:36
이게 무슨 뜻인지 이해해 봅시다. 이제 우리의 프로젝트에는 데이터베이스에 두 개의 테이블, 즉 주문과 고객이 있습니다.
So let's understand what this means. So now in our projects, we have like two tables in the database, orders and customers.
15:49:42
우리는 이전에 복잡한 쿼리가 있을 경우 도시를 사용할 수 있다고 배웠습니다.
And we have learned previously that if we have like a complex query, we can go and use the city.
15:49:47
예를 들어, 우리 도시에서는 테이블을 조인하고 합계를 사용하여 일부 집계를 수행하며, 도시는 중간 결과에 데이터를 저장할 수 있습니다.
So for example, in our city, we are joining tables and doing some aggregations using the sum and the city can store the data in an intermediate results.
15:49:56
그리고 우리는 주요 쿼리를 가지고 있습니다. 예를 들어, 우리는 2단계를 수행하고 있습니다.
And then we have the main query. For example, we are doing the step two where
15:50:00
데이터를 순위 매기고 있으므로 전체 과정이 하나의 쿼리에 있습니다.
we are ranking the data so the whole thing is in one query
15:50:03
그리고 재무 분석가가 이
and let's say that a financial analyst was doing
15:50:06
유형의 분석을 수행하고 있다고 가정해 봅시다. 그렇다면 어떤 일이 발생할 수 있을까요?
this type of analysis now what could happen if that you
15:50:09
예를 들어 예산 분석가가 있을 수 있습니다.
might have another user for example a budget
15:50:12
그는 정확히 같은 첫 번째 단계를 수행하고 있습니다.
analyst where he is doing exactly the same first step
15:50:15
그는 먼저 도시 쿼리를 가지고 있습니다.
so he has as well a city query where first
15:50:18
데이터를 결합한 다음 합계를 사용하여 집계합니다.
the data are joined and then aggregated using the sum
15:50:21
그는 메인 쿼리의 마지막 단계에서 순위를 매기지 않습니다.
but the last step in the main query he is not doing ranking
15:50:24
그는 최대값과 최소값만 계산하고 있습니다.
he's just doing like max and min and not only
15:50:28
우리는 세 번째 사용자인 위험 분석가가 있습니다.
that we have a third user the risk analyst were as
15:50:31
그는 CTE를 사용하여 같은 초기 단계를 수행하고 있습니다.
well doing the same initial step using the cte
15:50:34
테이블을 결합하고 요약을 수행하고 있습니다.
joining the tables and doing the summarization but
15:50:37
이 시나리오에서 위험 분석가는 단지 비교하고 있습니다.
here the risk analyst in this scenario he's just comparing
15:50:40
메인 쿼리의 마지막 단계에서 데이터를 비교하고 있습니다.
the data at the last step in the main query so now if you sit back and look to this you can see all those three data workers all of them are doing the same first step so all of them are doing the same CTE.
15:50:51
그들은 데이터를 결합하고 요약을 수행하고 있습니다.
They are joining the data and then doing summarization. And of course, this is a complete waste of time that each one of them has to create first the CTE from the scratch in order to do some analysis.
15:51:02
그래서 이것은 완전한 중복이며 의미가 없습니다.
So it is complete redundancy and makes no sense.
15:51:05
그래서 이것은 프로젝트에서 CTE만 사용하는 단점입니다.
So this is exactly the disadvantage of only using CTEs in the projects.
15:51:09
그 대신에 할 수 있는 것은 세 명의 데이터 작업자가 첫 번째 단계를 뷰로 만들기로 결정하는 것입니다.
Now, what we can do instead of that, those three data workers gonna decide to say, you know what, let's put the first step as a view in
15:51:17
데이터베이스에서 CTE를 매번 사용하는 대신에
database so instead of using cte each time
15:51:21
우리는 이 스크립트를 데이터베이스에 넣을 것입니다.
we're gonna take this script and put it in the database so
15:51:24
이제 모든 사람이 사용할 수 있는 중앙 로직이 저장됩니다.
we have now a central logic that is stored
15:51:27
이 로직을 한 번만 쿼리하면 됩니다.
in the database where everyone can use it so we have this
15:51:31
모두가 이로부터 혜택을 받을 수 있습니다.
query this logic only once and everyone
15:51:34
재무 분석가는 물리적 테이블에 직접 가지 않고 뷰로 갈 수 있습니다.
can benefit from it so now the financial analyst instead of going directly to the physical tables they can go to the view so that means she needs
15:51:43
그녀는 단 하나의 스크립트만 작성하면 됩니다.
only to write one script the rank scripts same
15:51:46
예산 분석가도 쿼리만 작성하면 됩니다.
thing goes for the budget analyst he has only to write the query
15:51:49
최대값과 최소값을 위해서입니다.
for the max and min and as well for the risk analyst you
15:51:52
데이터를 비교하기만 하면 됩니다.
just need to compare the data so as you can see all those queries
15:51:55
데이터를 비교해야 하므로 모든 쿼리가
are reduced and they can only focus on the analyzes so
15:51:59
축소되고 분석에만 집중할 수 있습니다.
this is exactly the magic of views in data analytics this logic this knowledge can be centralized in the database and this is way faster and better than having this logic written each time
15:52:11
이것이 데이터 분석에서 뷰의 마법입니다.
someone want to do any analyzes. So this is why we need views in data projects.
15:52:20
CTE와 뷰를 비교하면 CTE는 단일 쿼리 내의 중복을 줄이는 데 사용됩니다.
So now if you compare views with CTEs, the CTEs are used in order to reduce the redundancy within one single query.
15:52:28
따라서 하나의 쿼리 내에서 재사용성을 개선합니다.
So it improves the reusability within one query, where in the other hand in the views, we are reducing the redundancies from multiple queries.
15:52:38
전체 프로젝트의 복잡성을 줄이고 있습니다.
So we are reducing the complexity of the whole project.
15:52:41
뷰는 여러 쿼리에서 재사용성을 개선합니다.
So the views are improving the reusability in multiple queries. Now think about it like this.
15:52:47
로직을 데이터베이스에 지속하기 위해 뷰를 사용합니다.
We use views in order to persist a logic in the database.
15:52:52
로직이 매우 중요하므로 데이터베이스에 지속하고자 합니다.
So the logic is so important that we want to persist it in the database.
15:52:56
테이블에서는 데이터를 지속하지만 뷰에서는 로직을 지속합니다.
It's like in the tables we persist data but with the views we are persisting logic.
15:53:01
CTE에서는 로직이 지속되지 않습니다.
But in the other hand in the CTE the logic is not persisted.
15:53:05
로직은 임시적이며 오직
it is temporary and gonna be calculated only on
15:53:08
하나의 쿼리 범위 내에서만 계산됩니다.
the fly within the scope of one query so
15:53:11
이 로직은 이 시나리오에서만 중요합니다.
this logic is important only in this scenario and
15:53:14
다른 쿼리에는 중요하지 않으므로
it is not important for any other queries that's why
15:53:17
뷰를 사용하여 지속하는 것은 의미가 없습니다.
it makes no sense to persist it using the views
15:53:20
이 로직이 매우 중요하다면
so you have to decide is this logic is very important then
15:53:24
시티에서 빼내어 뷰에 넣어야 합니다.
take it away from the city and put it in the view but if
15:53:27
이 로직이 정말 중요하지 않다면
you think you know what this logic is not really important and
15:53:31
이 쿼리에서만 중요하므로 시티에 남아야 합니다.
only important in this one query then stay with the city
15:53:34
뷰를 생성하는 데는 항상 추가적인
because creating views always needs some extra
15:53:37
단계를 필요로 합니다.
steps in order to maintain the view you have to
15:53:40
뷰를 유지하려면 뷰를 생성해야 합니다.
create the view you have to drop the view if you don't need it
15:53:43
필요하지 않으면 뷰를 삭제해야 합니다.
but the city there is almost no maintenance for it the
15:53:46
시티는 거의 유지 관리가 필요 없으며
database is going to do automatically the cleanup once the query is
15:53:49
데이터베이스는 쿼리가 완료되면 자동으로 정리를 수행하므로 도시를 삭제하는 추가 작업이 필요하지 않습니다. 그래서 도시가 뷰보다 사용하기 더 쉽습니다. 이것이 뷰와 CTE의 큰 차이점입니다.
done so there is no extra activity to drop a city or something that's why city is easier to use than views so those are the big difference between the views and CTEs.
15:54:04
좋습니다. 이제 뷰의 구문을 빠르게 확인해 보겠습니다. 이제 select from where와 같은 쿼리가 있습니다.
Okay, so now let's check quickly the syntax of a view. So now we have a query like select from where.
15:54:09
이것은 쿼리입니다. 간단한 select 문입니다.
So this is a query, a simple select statement.
15:54:12
하지만 이제 데이터베이스에서 뷰와 객체를 생성하려면 DDL 명령어 create를 사용해야 합니다.
But now in order to create a view and object in database, we have to go and use a DDL command create.
15:54:19
그래서 우리는 create view라고 말할 것입니다. 왜냐하면
So we're gonna say create view because we
15:54:22
뷰를 생성하고 싶기 때문입니다. 그런 다음 뷰의 이름과
want to create a view then the name of the view and
15:54:25
그런 다음 CTE처럼 as를 사용하고 두 개의
then it's like the cte we say as and then double
15:54:28
괄호를 사용합니다. 보시다시피 매우 간단하며 우리는 이것을
parentheses so as you can see it's very simple and we call this
15:54:31
DDL 명령어라고 부릅니다. 데이터베이스에 가서
a ddl command where we are telling the database go
15:54:35
뷰를 생성하라고 지시하고 뷰의 논리는
and create a view and the logic of the view comes from
15:54:38
이 쿼리에서 나오므로 매우 간단합니다. 이것이 뷰를 생성하는 방법입니다.
this query so it's very simple this is how you can create views
15:54:41
데이터베이스에서. 이제 다음 작업을 수행해 보겠습니다. 각 월의 판매 누적 합계를 찾으라고 합니다. 이 작업을 CTE를 사용하여 해결하겠습니다.
in database okay so now let's have the following task and it says find the running total of sales for each month i'm gonna start this task by solving it using the CTE.
15:54:50
먼저 월별로 몇 가지 집계를 수행하겠습니다. 이제 선택해 보겠습니다. 이제 무엇이 필요할까요?
So first I'm going to go and do a few aggregations on the top of the month. So let's go and select. So now what do we need?
15:54:56
주문 날짜가 필요하지만 월별로 필요합니다.
We need the order dates, but we need it as a month.
15:55:00
이렇게 날짜를 잘라내는 함수를 사용하고, 월별로 날짜를 원한다고 말하겠습니다.
I'm going to go and use the date truncate like this and say, okay, I would like to have the date as the granularity of month.
15:55:08
그래서 주문 월이라고 부르겠습니다. 그 후에 몇 가지 집계를 수행할 것입니다.
So let's go and call it order month. And now after that, we're going to do a few aggregations.
15:55:14
예를 들어, 판매의 합계를 가져오고 이를 총 판매라고 부르겠습니다.
Like for example, let's go and get the sum of sales and we're going to call it total sales.
15:55:20
그게 시작입니다. 이제 sales orders 테이블에서 호출하고 그룹화하여 월별로 그룹화하겠습니다.
And that's it for the start. So now let's go and call it from the table sales orders and group by and we are grouping a by by the month.
15:55:31
이런 식으로 실행해 보겠습니다. 이제 각 월의 총 판매를 얻습니다.
So something like this. Let's go and execute it. And now for this, we get for each month the total sales.
15:55:36
이제 다음 단계는 판매의 누적 합계를 계산하는 것입니다. 물론 이것은 누적 합계가 아닙니다.
And now the next step that we have to go and calculate the running total for the sales. This is, of course, not the running total.
15:55:42
즉, 서브 쿼리를 사용할 수 있습니다. 이것은 우리의 첫 번째 단계이며 두 번째 단계가 필요합니다. 쿼리나 CTE를 사용해야 합니다.
So that means either we can go and use sub queries. So this means this is our first step and we need a second step. So either use queries or cities.
15:55:50
여기서 CTE를 사용할 것입니다. 그래서 CTE와 월별 요약이라고 말할 것이며, 이렇게 정의하겠습니다.
I will go with the city over here. So I'm going to say with city and monthly summary, and we're going to define it like this.
15:56:01
이제 우리가 할 것은 메인 쿼리를 정의하는 것입니다. 메인 쿼리는 간단할 수 있습니다.
And now what we're going to do, we're going to go and define the main query. So the main query can be simple.
15:56:05
그래서 선택하고 주문 월을 가져오겠습니다. 이제 누적 합계를 구축해야 합니다.
So selects and let's go and get the order month. And now we have to build the running total.
15:56:11
그래서 우리는 윈도우 함수를 사용할 것입니다. 총 판매의 합계를 구하고, 그 다음에 over라고 말하겠습니다.
So we're going to go and use the window function. So sum total sales. And then we're going to say over.
15:56:19
데이터를 파티션할 필요가 없습니다. 우리는 단순히 주문 월별로 정렬하고 오름차순으로 두면 됩니다. 이것이 누적 합계입니다.
We don't have to partition the data. we will just sort it by the order month and we can leave it ascending so this is the running total
15:56:31
물론 우리의 CTE를 선택해야 합니다.
and we have to go and select of course our cte from
15:56:34
여기서 실행해 보겠습니다.
here so let's go and execute it and with
15:56:37
출력에서 결과를 이해하기 위해 총 판매를 추가할 수 있습니다.
that we are getting running total of course we can go and add the total sales
15:56:40
결과를 이해하기 위해 출력에서 누적 판매를 구축하고 있습니다.
in the output in order to understand the results so
15:56:43
이 범위에서는 모든 것이 괜찮습니다. 우리는 CTE를 사용하고 있습니다.
here in the output we are just building a cumulative sales
15:56:47
하지만 이제 이 논리가 중요하다고 상상해 보세요.
so for this scope everything is fine we are using the cte
15:56:50
여러 쿼리에서 매우 유용합니다.
but now imagine that this logic is important
15:56:53
데이터를 집계하는 보고서를 갖는 것이 정말 좋습니다.
for multiple queries so it's really nice to have
15:56:56
월별 데이터 집계 보고서를 생성할 수 있습니다.
such a report where we are aggregating the data at the level
15:56:59
이것을 여러 사용자와 쿼리에서 사용할 수 있습니다.
of the month and this could be used from different users and
15:57:02
모두가 접근할 수 있도록 이 논리를 하나의 뷰에 넣는 것은 어떨까요?
different queries so now we say how about to put this logic
15:57:05
하나의 집계를 더 추가하는 것은 어떨까요?
in one view so that everyone can access it and we don't have to repeat the same aggregations over and over and now before we put it in view someone comes and say
15:57:14
총 판매 외에도 정렬할 수 있습니다.
how about to add one more aggregation so that not
15:57:17
어떤 다른 사용자가 이렇게 말할 수도 있습니다.
only the total sales we can order so now before we put it as
15:57:20
총 판매 외에도 하나의 집계를 더 추가해 보겠습니다.
view maybe some other user says you know what we would like to have
15:57:23
모두가 혜택을 볼 수 있도록 범위를 조금 더 넓혀 보겠습니다.
one more aggregation not only the total sales let's make the scope
15:57:26
여기에서 총 주문 수를 추가해 보겠습니다.
a little bit bigger so that everyone can benefit so for example we can
15:57:29
또는 다른 사용자가 수량도 가져오자고 할 수 있습니다.
go over here and say you know what let's go and add the total number of orders so we can go over here and say count and let's get the order id and say this is the total orders
15:57:41
이렇게 하면 총 수량이라고 부릅니다.
or maybe some other says let's get the quantities as well so we can go and summarize the quantity
15:57:48
이렇게 하면 많은 집계를 수행하고 있습니다.
like this and we call it total quantities
15:57:51
월별로 집계를 수행하고 있습니다.
so with that we are like doing a lot of
15:57:54
이제 CTE를 실행해 보겠습니다.
aggregations on the month level let's go and execute only the
15:57:58
이것을 뷰에 넣고 선택해 보겠습니다.
cte so now we have really nice report that is based on the month's and can be used from many different queries so now what we're gonna do we're gonna take
15:58:06
이 논리를 사용하여 새 쿼리를 생성해 보겠습니다.
this and put it in a view let's go and select only
15:58:09
이 논리를 사용하여 새로운 쿼리를 만들고 이제 무엇을 할까요
this logic and create a new query and now what
15:58:12
여기에서 쿼리를 넣을 수 있고 이제 ddl을 만들어야 합니다
we can do we can put our query here and we have to create now the
15:58:16
뷰를 만들기 위한 ddl이 될 것입니다
ddl in order to create a view so it's
15:58:19
이렇게 될 것입니다. 뷰를 만들고 이름을 정해봅시다
gonna be like this create view let's give it the name maybe starts
15:58:22
v 언더스코어로 시작하고 이것은 월간
with the v underscore and this can be the monthly
15:58:26
요약이 될 수 있습니다. 이것이 뷰의 이름이고 우리는 모든 것을 넣습니다
summary so this is the name of the view and us then we put everything
15:58:32
괄호 안에 넣는 것은 cte를 만드는 것과 같습니다
in parentheses it's like you are building a cte
15:58:35
여기에서 우리의 논리가 있고 여기에
so we have here our logic and here is
15:58:38
뷰를 만들기 위한 ddl 쿼리가 있습니다
our ddl query in order to create the view so
15:58:41
이제 실행해 보겠습니다. 출력에서 볼 수 있듯이
now let's go and execute it now as you can see in the output it
15:58:45
명령이 완료되었다고만 합니다. 왜냐하면 이것은
says only that the command is completed because this is not a
15:58:48
선택 쿼리가 아니라 ddl 명령이기 때문입니다. sql은 성공적으로 생성했는지 여부를 알려줍니다
select query this is a ddl command so the sql gonna tell you okay either i created it successfully or not so now the question is where Where do I find now my view?
15:58:58
객체 탐색기로 가면 여기에서 우리 데이터베이스 sales DB 아래에
Well, if you go to the object explorer, you can see over here underneath our database sales DB.
15:59:03
테이블이라는 것이 있습니다. 우리는 그 테이블을 쿼리하는 데 사용합니다
We have here something called tables where we are used to query those tables.
15:59:08
하지만 그 아래에 우리의 뷰도 있습니다. 뷰를 확인하고 확장하면
But beneath it, we have as well our views. So if you check the views and expand it, now we are not seeing a view because we just created the view here.
15:59:17
여기에서 새로 생성된 뷰를 볼 수 있습니다
So go over here and refresh. And once you do that, you will see the newly created view.
15:59:23
이것이 우리가 방금 생성한 것입니다. 이제 우리는 새로운 쿼리를 만들고 뷰를 쿼리할 수 있습니다
So this is the one that we just created. So now what we can do, we can go and create a new query and let's go and just query the view.
15:59:30
그래서 소 V 월간 요약에서 스타를 선택하세요.
So select star from so V monthly summary.
15:59:38
가서 실행해 봅시다. 그리고 이제, 보시다시피, 우리는 뷰의 결과를 얻고 있으며, 지금 이 로직에 완전히 외부 쿼리에서 접근하고 있습니다.
Let's go and execute it. And now, as you can see, we are getting now the result of the view and I'm accessing now this logic from completely external query.
15:59:46
이제 저는 뷰를 데이터베이스에 있는 다른 테이블처럼 생각할 수 있습니다.
So now I can think about the view as any other table that you have in the database.
15:59:51
그리고 다시 말하지만, 뷰와 테이블 간의 큰 차이점은 테이블에는 데이터가 있고, 실제 데이터가 있으며, 모든 것이 지속됩니다.
And again, the big differences between the views and the tables, the tables has data, has actual data, and everything there is persisted.
16:00:00
저에게는 단지 추상화일 뿐이며 그 뒤에는
is just an abstraction for me and behind it there is
16:00:03
테이블로 가서 쿼리하는 쿼리가 있습니다.
like a query that goes to the table and query the
16:00:06
결과를 제시하기 위해 테이블을 쿼리하지만, 저에게는 그 모든 세부사항이 중요하지 않습니다.
tables in order to present the results but for me i don't care
16:00:09
저는 즉시 쿼리로 갈 수 있습니다.
about all those details i can go immediately to the query
16:00:12
여기서 쿼리를 시작할 수 있습니다.
over here and start querying so now in order to create the
16:00:15
총 실행 매출을 생성하기 위해 CTE를 만들 필요가 없습니다.
total running sales i don't have to create the cte as
16:00:19
업 쿼리를 가져올 수 있습니다.
up queries i just go and get for example our
16:00:22
메인 쿼리로 돌아가겠습니다.
main query let's go back over here
16:00:25
이제 CTE를 사용하는 대신
so now instead of using the cte i can go
16:00:28
직접 뷰에 접근할 수 있습니다.
directly and access the view so as
16:00:32
이제 제 쿼리는 매우 간단합니다.
you can see now my query is very simple i'm doing immediately
16:00:35
데이터를 미리 준비할 필요 없이 두 번째 단계로 진행할 수 있습니다.
the step two without having to prepare the data first
16:00:38
그래서 실행하면 정확한 결과를 얻을 수 있습니다.
so if i go and execute it i will get exact results
16:00:42
이제 뷰 위의 쿼리를 비교하면
and now if you compare the query on top of the view like this
16:00:45
도시 쿼리는 더 많은 단계가 필요하고 조금 더 복잡합니다.
with the city query you can see that the
16:00:48
도시 쿼리는 더 많은 단계가 필요하고 조금 더 복잡합니다.
city has more steps and it is like little bit more complicated
16:00:52
뷰 위의 쿼리보다 복잡성을 줄이는 것이 바로 이점입니다.
than the query on top of the view and this is
16:00:55
사용자의 관점에서 소비하기 매우 쉽습니다.
exactly the benefit of the view we reduce the complexity and
16:00:58
이렇게 중앙에 논리를 배치할 수 있습니다.
it is very easy to consume from the point of view of users
16:01:01
뷰를 사용하여 이 방법으로 논리를 중앙에 배치할 수 있습니다.
so this is how you can put your logic in central
16:01:04
뷰를 생성하는 방법을 배웠습니다.
place using views and with that we have learned how we
16:01:07
스키마에 대한 한 가지 더 말씀드리겠습니다.
create a view now one more thing about the schemas if
16:01:11
여기서 테이블을 확인하면 모두 하나의 스키마가 있습니다.
you check our tables over here they have all one
16:01:14
그래서 sales.customers, sales.employees, orders가 있습니다.
schema so we have sales.customers sales.employees orders
16:01:18
새로운 뷰는 dbo 스키마를 가지고 있습니다.
and so on our new view has the scheme of dbo if you create any object whether it's table
16:01:24
테이블이든 뷰든 스키마를 지정하지 않으면
or view and you don't specify schema in a
16:01:27
기본 스키마인 dbo로 설정됩니다.
default schema called dbo and now let's go back to our ddl
16:01:31
여기서 스크립트를 보시면 스키마를 지정하지 않았습니다.
script so as you can see over here we didn't specify
16:01:34
이것이 뷰 이름이라고 말했습니다.
any schema we just said okay this is the view name
16:01:37
이제 우리의 뷰를 올바른 스키마에 넣기 위해
and now in order to put our view in the correct schema we
16:01:40
기본값에 두고 싶지 않다면 스키마 이름을 지정해야 합니다.
don't want it to be in the default you have to go and specify the
16:01:43
DDL에서 스키마 이름을 지정해야 합니다. 이제 그렇게 하려면
schema name in the ddl and now in order to do that we
16:01:46
뷰의 이름으로 가서 스키마를 작성합니다.
go to the name of the view and we write the schema
16:01:49
이름과 점으로 구분하여
name and then separated with a dot so the
16:01:52
첫 번째는 스키마 이름이고 두 번째는
first one is the schema name and the second one is the
16:01:56
뷰 이름입니다. 이제 실행해 보겠습니다. 이제 확인해 보면
view name so now let's go and execute it now if you check over
16:01:59
여기서는 새로운 것이 보이지 않지만 새로 고치면
here you don't see anything new but if you refresh you
16:02:02
올바른 스키마에 또 다른 뷰가 있을 것입니다. 그래서 우리는
will find another view in the correct schema so we have
16:02:05
sales.v_monthly_summary가 있습니다.
sales dot v monthly summary and
16:02:08
이것이 우리가 원하는 것입니다. 이것이 스키마에 뷰나 테이블을 할당하는 방법입니다.
this is exactly what we want so this is how you can assign a
16:02:11
기본값을 사용하고 싶지 않다면 DPU입니다. 자, 이제 다음
view or even a table to the correct schema if
16:02:15
단계는 정리하고 싶다는 것입니다. 그들은 필요하지 않습니다.
you don't want to use the default one the dpu all right so now the next
16:02:18
내 데이터베이스에 있는 두 개의 뷰입니다. 뷰를 삭제하는 방법은
step is that you say you know what i would like to clean up i don't need those
16:02:21
명령어 드롭을 사용하면 매우 간단합니다.
two views in my database so how to delete a view we
16:02:24
새 쿼리를 만들고 드롭이라고 말하면
can go and use the command drop it is very simple if
16:02:27
무엇을 드롭할지 말해야 합니다. 뷰를 드롭하고
you go and create a new query and you say drop and
16:02:30
뷰의 이름과 스키마를 지정해야 합니다. 하지만 기본 스키마 DPU이므로
then you say what you want to drop you want to drop a view and then you have
16:02:33
즉시 시작할 수 있습니다. 뷰 이름은 v_monthly_summary입니다.
to specify the name and schema of the view but now since it is the default schema dpu i don't have to write it down so we can start immediately
16:02:42
그래서 그게 전부입니다. 매우 간단합니다. 이제 우리는
with the view name so v monthly summary
16:02:46
실행하러 가고 완료되었다고 나옵니다. 하지만
so that's it it's very simple so now we
16:02:49
아무것도 변경되지 않았음을 알 수 있습니다. 새로 고치고 이제
go and execute it it says it's completed but as
16:02:52
데이터베이스가 뷰를 제거했음을 볼 수 있습니다.
you can see nothing is changed we go and refresh and now we
16:02:55
스키마 dbo와 함께. 매우 간단합니다. 이것이
can see that the database did remove the view with
16:02:58
SQL에서 뷰를 드롭하는 방법입니다. 자, 이제 다음 단계로 넘어가서 뷰를 생성하는 DDL로 돌아갑니다.
the schema dbo so it's very simple this is how you can
16:03:02
SQL에서 뷰를 삭제하는 방법입니다. 자, 이제 다음 단계로 넘어가서 뷰를 생성하는 DDL로 돌아가겠습니다.
drop a view in sql okay so now to the next step let's go back to our ddl of creating the view
16:03:08
판매 월별 요약, 이제 당신은 알고 싶어합니다.
sales monthly summary and now you say you know what i would
16:03:11
뷰 내부의 논리를 변경하고 싶습니다.
like to change the logic inside the view so
16:03:14
이 내용을 업데이트하는 방법, 내 쿼리를 업데이트하는 방법입니다.
how we can update this content how i can update my
16:03:17
예를 들어 이 열을 삭제하자고 하면, 저는 세 개의 열만 필요합니다.
query if you say let's go and for example delete
16:03:20
그렇게 실행하면 데이터베이스가 이렇게 말합니다. 할 수 없습니다.
this column i need only three columns so and you go
16:03:23
이미 그런 뷰가 있기 때문에 SQL은
execute it the database say i cannot do it for you because
16:03:27
가서 내용을 교체할 수 없습니다. 여전히 안 된다고 할 것입니다.
we have already such a view so sql will not
16:03:30
같은 이름을 가지고 있어서 아무것도 할 수 없습니다.
go and replace stuff is still gonna say no they
16:03:33
그렇다면 뷰를 어떻게 업데이트할 수 있을까요? 다른 데이터베이스에서는
we have the same name and i cannot do anything for it
16:03:36
예를 들어 PostgreSQL에서는 매우 간단합니다. 여기로 가서
so how we can update the view well in other databases like
16:03:39
뷰를 생성하거나 교체하라고 말할 수 있습니다.
postgres for example it's very simple you can go over here
16:03:42
즉, 데이터베이스에 이 뷰를 생성하라고 말하는 것입니다.
and say create or replace view
16:03:46
뷰를 생성하거나 이미 존재하면 교체하라고 말하는 것입니다.
so it's like you are telling the database create this
16:03:49
PostgreSQL에서는 오류가 발생하지 않지만 SQL에서는
view or if it already exists then replace it and
16:03:52
서버에서는 조금 더 복잡합니다. 이 명령이 없습니다.
you will not get error in the postgres but in the sql
16:03:55
여기에는 두 가지 방법이 있습니다. 여기로 가서 먼저 뷰를 삭제하자고 말할 수 있습니다.
server it is a little bit more complicated we don't have this command
16:03:59
그리고 나서 당신이 할 일은 뷰 삭제를 표시하는 것입니다.
so here you have two ways either you go over here and say you know what let's first drop the view so you go with the same name over here
16:04:09
이렇게 실행하면 뷰가 삭제되고
and then what you're gonna do you're gonna go and mark the drop view so
16:04:12
이렇게 뷰를 다시 생성합니다. 우리가 한 일입니다.
if you execute it like this the view gonna be dropped and then
16:04:15
뷰를 파괴하고 다시 생성합니다.
we recreate the view like this so what we have done
16:04:19
새로운 논리로 다시 생성합니다. 모든 것을 한 번에 하고 싶습니다.
we destroy the view and then we recreate it using the
16:04:22
두 단계로 하고 싶지 않습니다. 모든 것을 한 번에 하고 싶습니다.
new logic or you say you know what i would like to have everything in one go
16:04:25
그 명령을 위해 SQL 서버에서 T-SQL을 사용해야 합니다.
like i don't want to do it in two steps i would like to have everything in one
16:04:28
트랜잭트 SQL은 확장 기능과 같습니다.
command and for that you have to use in sql server the tsql
16:04:32
트랜잭트 SQL은
the transact sql it is like an extension for
16:04:35
SQL 서버에서만 사용할 수 있는 프로그래밍과 같습니다.
sql only in sql server well it's like programming
16:04:38
변수를 추가하거나
where you can go and add variables or you can all go and add
16:04:41
이 언어에 대해 깊이 파고들지는 않겠지만, 보여드리고 싶습니다.
checks we will not do a deep dive in this language but i would like
16:04:44
뷰를 위한 방법을 보여드리겠습니다. 따라서 저를 따라오세요.
to show you how to do it for the views so just follow me with that i'm gonna go and replace the whole thing and then we're gonna say if and now we are checking the system catalog if the object id
16:04:57
이제 뷰 이름을 지정하겠습니다. 가시죠.
and now we go and specify the view name. So let's go
16:05:00
스키마와 함께 전체를 복사하고
and copy the whole thing with the schema as well and then we're
16:05:03
이것은 뷰라고 말할 것입니다.
gonna say for a skill this is a view so
16:05:07
이 객체가 존재하는지 확인합니다.
if this object exists so we are saying is not
16:05:10
이 객체가 존재한다는 것은 카탈로그에 존재한다는 뜻입니다.
null so that means it exists in the catalog then what a skill should do should drop this view so i'm gonna say drop view and it's like we have done it first
16:05:21
그럼 이 뷰를 삭제해야 합니다.
and then semicolon and then we say for sql go and
16:05:24
SQL을 위해 세미콜론을 추가하고
with that we are saying for sql that tskl is done so
16:05:28
논리가 완료되었습니다.
the logic is done and after that we have
16:05:31
뷰를 생성하기 전에 확인하고 있습니다.
the ddl for our view so again what we are doing we
16:05:34
뷰가 존재하는지 확인합니다.
are checking before creating the view whether the view exists if it exists then we are telling sql go and drop it and if it doesn't exist that means we haven't created this view yet
16:05:46
완전히 새로운 뷰입니다.
it is completely brand new view then this step going
16:05:49
따라서 이 단계는 건너뛰어야 합니다.
to be skipped so there is nothing to drop so now if you go
16:05:52
전체를 실행하면 작동할 것입니다.
and execute the whole thing it will work and of course if you go and
16:05:55
여기에서 새로 고침하면 여전히 뷰가 보입니다.
refresh over here you still see the view so sql
16:05:58
테이블을 먼저 삭제한 후 재생성했습니다.
did destroy the table first and then recreated
16:06:02
다시 실행하면 이렇게 됩니다.
so if you execute it again so this is how you
16:06:05
SQL 서버에서 뷰의 논리를 교체합니다.
replace your logic in view in sql server and with that we have learned all possible scenarios how to create a view how to drop a view and how to update the
16:06:15
이제 뷰의 논리입니다.
logic of a view now
16:06:20
데이터베이스 아키텍처로 돌아가서
back to our database architecture and let's understand how the database
16:06:24
뷰를 실행하는 방법을 이해해 봅시다.
executes views so now let's say that
16:06:27
데이터 엔지니어가 top n이라는 뷰를 생성하고 있습니다.
the data engineer is creating view called top n so
16:06:30
쿼리는 데이터베이스 엔진으로 전송될 수 있으며, 데이터베이스가
the query can be sent to the database engine and once the database
16:06:34
이것이 뷰라는 것을 이해하면, 이것은 테이블이 아닙니다.
engine understand this is a view this is not a table so
16:06:37
이제 데이터베이스 엔진이 디스크 저장소와 카탈로그로 이동합니다.
now the database engine gonna go to the disk storage and to the catalog
16:06:40
메타데이터만 저장하는 것이 아니라
and it will stores not only the metadata
16:06:44
뷰에 대한 SQL도 저장합니다.
about the view also the SQL that
16:06:47
뷰에 대한 SQL이므로, 생성된 뷰에서 정의한 SQL
is responsible for the view so it's gonna take the SQL
16:06:50
문을 카탈로그에도 저장합니다. 테이블과 비교하면,
statements that you have defined in the create view and
16:06:53
테이블에는 메타데이터만 있지만, 뷰에는
place it as well in the catalog so if you compare to the tables
16:06:56
메타데이터와 쿼리 모두가 있습니다.
we have in tables only metadata but in the views we
16:06:59
뷰의 메타데이터와 쿼리를 가지고 있으며, 데이터베이스 엔진이
have both the metadata and as well the query
16:07:03
사용자 데이터에 테이블을 생성하지 않을 것입니다.
of the view and as well you can see that the database engine
16:07:06
따라서 내부에 저장된 데이터가 없습니다.
will not create a table in the users data
16:07:09
디스크나 캐시에 실제 데이터, 물리적 데이터가
so there is no nowhere data stored inside the
16:07:12
어디에도 저장되지 않으며, 우리는 메타데이터만 저장합니다.
disk or the cache so the actual data the physical data
16:07:16
시스템 카탈로그 내의 쿼리도 저장합니다.
will not be stored anywhere we are storing only metadata
16:07:19
이제 데이터 분석가에게 새로운 뷰가 있다고 말합니다.
and the query inside the system catalog
16:07:22
데이터 분석가는 쿼리를 작성하여
so now we tell our data analyst okay we have a new view and
16:07:25
뷰에서 데이터를 검색할 수 있습니다. 그는 선택하여
the data analyst can go and write a query in order to retrieve
16:07:28
뷰에서 선택하고 실행하면 데이터베이스 엔진이 이를 이해합니다.
the data from the view so he gonna say and say select from
16:07:31
이제 뷰에 대해 이야기하고 있으므로, 데이터베이스는
the view and execute it the database engine gonna take it and understand okay now we are talking about view so the database first
16:07:38
데이터를 검색하는 것이 아니라, 카탈로그에서 쿼리를 검색해야 합니다.
has to retrieve not the data can retrieve the
16:07:42
무엇을 실행해야 하는지 이해하기 위해
query from the catalog in order to understand what
16:07:45
데이터베이스는 먼저 뷰의 쿼리를 실행하고, 이 데이터는
do we have now to execute then the database is going to execute
16:07:48
주문이라는 물리적 테이블에서 옵니다.
the query of the view first and the data for this
16:07:52
쿼리는 orders라는 물리적 테이블에서 발생합니다.
query comes from a physical table called orders so
16:07:55
이제 데이터베이스 엔진이 주문을 쿼리하여 데이터를 가져오고 있습니다.
now the database engine is querying the order to retrieve the
16:07:58
최종 사용자에게 데이터를 제공하기 위해 실행될 것이며, 결과는 데이터 분석가에게 전송됩니다.
data so that we have a data for the end user and then it's going to be executed and the result is going to be sent back to the data analyst so as you can see there There is like two queries.
16:08:07
SQL 엔진은 먼저 뷰에서 쿼리를 실행해야 합니다.
The SQL engine first has to execute the query from the view.
16:08:12
그 후에만 데이터베이스 엔진이 사용자로부터 오는 쿼리를 실행할 수 있습니다.
And only after that, the database engine can execute the query that comes from the user.
16:08:18
사실 데이터는 항상 물리적 테이블에서 오지만, 우리는 데이터 분석가에게 테이블 접근을 제공하지 않습니다.
So actually the data comes always from a physical table, but we are not providing the data analyst and access to the table.
16:08:24
우리는 뷰에 대한 접근만 제공합니다. 이는 최종 사용자가 뷰에서 데이터를 선택할 때마다 발생할 수 있습니다.
We are just providing an access to the view. So this can happen each time an end user selecting data from the view.
16:08:31
데이터베이스 엔진은 카탈로그에서 쿼리를 가져올 수 있습니다.
the database engine can grab the query from the catalog
16:08:35
먼저 실행되어 데이터를 가져온 후, 최종 사용자가 원하는 것을 실행합니다.
executed first in order to get the data and then execute
16:08:38
데이터를 가져온 후, 최종 사용자가 원하는 것을 실행합니다.
what the end user wants and now if the data engineer says no let's
16:08:42
뷰를 삭제하기 위해 쿼리를 작성합니다.
go and drop the view so she writes a query in order to
16:08:45
뷰를 삭제하고 데이터베이스 엔진은 시스템 카탈로그로 이동합니다.
drop the view and the database engine gonna go to the system catalog and
16:08:48
메타데이터와 쿼리를 모두 삭제합니다.
delete both the metadata and the query so as you can see
16:08:51
뷰를 삭제하면 실제 데이터를 잃지 않으므로 사용자 데이터가 손실되지 않습니다.
if you are dropping a view you are not losing the actual data so there will be no user data lost at all so don't worry about
16:08:59
잃는 것은 쿼리와 메타데이터뿐입니다.
it what you are losing is only the query and
16:09:02
물리적 테이블을 삭제하면 데이터를 잃게 됩니다.
the metadata about your view it's only if you drop a physical
16:09:06
뷰를 삭제하는 것은 데이터베이스 테이블을 삭제하는 것보다 나쁘지 않습니다.
table like the orders you will lose your data so dropping views is not that bad like dropping a database table so this is how the database works with the views behind the scenes
16:09:20
이제 두 번째 시나리오로 넘어가겠습니다.
now moving on to the second scenario to the next use case of using views in projects
16:09:24
복잡성을 숨기고 추상화를 개선하기 위해 뷰를 사용합니다.
is that we use views in order to hide complexity and to improve abstraction.
16:09:29
많은 시나리오에서 우리는 매우 크고 복잡한 데이터베이스로 작업하며, 뷰를 사용하여 복잡성을 줄이고 사용자가 더 쉽게 작업할 수 있도록 합니다.
In many scenarios, we work with a very large and complex databases, and we can use views in order to reduce the complexity and make things easier for the users.
16:09:39
이것이 의미하는 바를 이해해 봅시다.
So let's understand what this means. Now I'm going to explain for you a scenario that happens almost in each project.
16:09:45
데이터베이스에 접근하여 분석을 수행하고자 할 때의 시나리오입니다.
Like if you get an access to a database where you want to
16:09:48
복잡한 테이블이 많은 큰 데이터베이스를 찾게 될 것입니다.
do analysis, you will be in scenario, and this can happen a lot,
16:09:51
이름과 테이블 간의 연결 관계를 이해하기가 거의 불가능합니다.
where you're going to find a large database, where the tables are very complex to understand they have a lot of columns they have like technical and cryptical
16:09:59
이름과 테이블 간의 연결 관계는 거의 이해할 수 없습니다.
names and how tables are connected to each other's
16:10:03
서로의 관계를 이해하기 거의 불가능합니다.
and the relationship between them it's almost impossible to understand
16:10:06
데이터 모델에 깊이 관여해야 합니다.
then you have to be deeply involved with the data models
16:10:09
이 데이터베이스를 쿼리하는 방법을 이해할 때까지
with documentations and with experts until
16:10:12
개발자가 아니라면 최종 사용자 관점에서
you understand how to query this database so
16:10:16
여러 조인을 시도하는 악몽이 될 것입니다.
if you are not a developer and from end user perspective it's
16:10:19
간단한 분석을 하기 위해서입니다.
going to be nightmare where you are trying to do multiple joins in
16:10:22
이 데이터 모델은 충분히 좋습니다.
order to make simple analyzes and of course from the database
16:10:26
하나의 애플리케이션에 적합하지만
perspective this data model is good enough for
16:10:29
여러 데이터 분석 프로젝트를 위해 데이터베이스를 열면
one application but if you are opening your database for
16:10:32
각 사용자에게 설명해야 합니다.
multiple data analysis projects this can be a nightmare
16:10:35
데이터를 쿼리하는 방법을
because you have to go and explain for each user how
16:10:38
기술적이고 이해하기 어려운 데이터 모델에 직접 접근하는 대신
to query the data so what we usually do instead of
16:10:41
여러 개의 뷰를 생성합니다.
giving a direct access to such technical and hard to understand data model we go as developers creating multiple
16:10:49
우리는 데이터 모델의 전문가이기 때문입니다.
views since we are the expert of the data model and
16:10:52
내 데이터베이스의 복잡성을 추상화할 것입니다.
these new views gonna be an abstraction of the
16:10:56
이 뷰들이 객체를 제공하는지 확인해야 합니다.
complexity that i have in my database and we have to
16:10:59
친숙한 객체를 제공해야 합니다.
make sure that those views are providing objects
16:11:02
이해할 수 있는 전체 영어 이름과 열을
that are friendly so they have like a
16:11:05
친숙하게 만들고 많은 뷰를 제공하지 않으려고 합니다.
full english name that makes sense and as well the columns
16:11:08
사용자가 모든 조인을 하지 않도록
are friendly and we try to not offer a lot of views
16:11:12
친숙한 몇 개의 뷰를 제공합니다.
so the user don't have to do all the joins so we provide
16:11:15
사용자가 필요로 하는 많은 정보를 포함하고 있습니다.
like few views that are friendly
16:11:18
분석가들을 위해 사용자들이 접근할 수 있도록
and has a lot of informations that the users needs
16:11:21
더 친숙하고 소비하기 쉬운 것을 제공하고
for the analyzers so that the users can have an access to
16:11:24
간단한 쿼리를 작성할 수 있도록 합니다.
something more friendly and easy to consume and then they
16:11:27
간단한 쿼리를 작성하여 분석기를 사용할 수 있습니다.
can write simple queries in order to do analyzers on
16:11:30
이 친숙한 뷰의 상단에 이름을 붙일 수 있습니다. 우리는 데이터 제품을 제공하고 있습니다.
top of these friendly views and this is what we can give a name like we are providing a data product from my
16:11:38
복잡한 물리적 데이터베이스입니다. 여기서 다시
complex physical database so here again
16:11:41
뷰가 추상화를 제공하는 것이 얼마나 중요한지
how important are the views to provide an abstraction and
16:11:45
사용자에게 쉽게 소비할 수 있는 객체입니다.
easy to consume objects for the users and
16:11:48
그 덕분에 모든 복잡성을 숨길 수 있습니다.
with that i can hide all my complexity and the
16:11:51
전문가들로부터 개발될 뷰의 스크립트입니다.
script of the view going to be developed from the experts and
16:11:55
사용자가 이러한 복잡한 SQL 조인을 이해하거나 작성할 필요가 없습니다.
only once so that the users don't have to understand or to write these complex SQL joins and with that you can make your data projects way easier than before.
16:12:05
이것은 뷰의 또 다른 중요한 사용 사례입니다.
So this is another important use case for the views where we can use it in order to provide abstraction and as well easy and friendly objects for the end users.
16:12:14
주문, 제품, 고객 및 직원의 세부 정보를 결합한 뷰를 제공해야 합니다.
Okay, so now let's have the following task and it says provide view that combines details from orders, products, customers and employees.
16:12:23
이제 데이터베이스의 모든 테이블 대신 모든 것을 포함하는 결합된 뷰를 제공해야 합니다.
So now instead of having all those tables from our database, we have to provide one combined view that has everything.
16:12:30
거의 모든 것입니다. 이제 이러한 뷰를 만드는 방법을 살펴보겠습니다.
Well, almost everything. So now let's see how we can create such a view. So let's start first by the table orders.
16:12:37
먼저 판매 주문에서 첫 번째 별을 선택하겠습니다.
I'm going to go and select first star from sales orders.
16:12:43
모든 것을 연결하는 중앙 테이블입니다.
And let's go and execute it. This is the central table that connects everything.
16:12:47
주문 ID, 제품 ID, 판매, 고객 등이 있습니다.
You can see here we have the order ID, product ID, sales, customers, and so on. So it is a great start point.
16:12:53
이것은 필수적입니다. 고유 식별자가 있으면 좋습니다.
So now we're going to go and be picky about the columns. I would not show all the columns, but I would say let's go and show, for example, the order ID.
16:13:01
제품 ID는 표시하지 않겠습니다.
This is essential. It's nice to have a unique identifier.
16:13:05
고객 ID, 판매원 ID도 마찬가지입니다.
Now, the product ID, I will not show it, but I will just list it over here.
16:13:09
그래서 잊지 않도록 주석으로 남기겠습니다.
The same for the customer ID, salesperson ID. Those stuff I would like to replace later.
16:13:15
제품 ID와 고객 ID를 표시하는 것은 의미가 없습니다.
So I will just make it as comment so I don't forget about it.
16:13:19
각 객체에 대한 세부 정보를 표시하고 싶습니다.
Because it makes no sense to show the product ID and customer IDs and so on.
16:13:23
제품 ID 대신 제품 이름을 표시하고 싶습니다.
We would like to show the details about each object.
16:13:26
제품 테이블에서 다른 정보를 가져오고 있습니다.
Because instead of having the product ID, I would like to show, for example, the product name itself.
16:13:32
주문 날짜를 가져올 수 있습니다.
and some other informations from the table products. And with that, we are reducing the complexity. So now what else we can get from the table orders?
16:13:39
판매 및 수량과 같은 항목을 가져올 수 있습니다.
We can go and get the order date. I will put it here. And maybe we can go and get stuff like sales and quantity.
16:13:47
이렇게요. 물론 모든 열을 추가할 수 있지만, 지금은 이 정보로 진행하겠습니다.
So like this. Of course, we can go and put all the columns. But for now, I will go with those informations.
16:13:54
이제 중요합니다. 많은 테이블을 다룰 것이기 때문입니다. 별칭을 사용하는지 확인합시다.
Now it's important since we're going to have a lot of tables. Let's go and make sure we are using aliases.
16:13:59
이제 각 열에 대해 O.를 가질 것입니다. 이제 주문 테이블에서 네 가지 세부정보가 있습니다.
So now we're going to have the O. for each of those columns all right fine so now we have four details from the table orders
16:14:08
다음은 제품 ID입니다. 가봅시다.
now what is next we have the product id so let's go
16:14:11
제품에서 정보를 가져옵니다.
and get the informations from the products what
16:14:14
우리는 왼쪽 조인을 사용할 것입니다. 내부 조인을 사용하면 일부 주문이 누락될 수 있으므로 그렇게 하지 않겠습니다.
we're gonna do we're gonna use a left join just to make sure to not miss any order if you go with the inner join you might miss some orders so i will not do that so let's join it with the
16:14:25
이렇게 제품을 사용하고, 이제 테이블을 조인해야 합니다. 제품 ID 키를 사용할 수 있습니다.
products like this and so now we have to go and join the tables so we can use the keys product id
16:14:35
주문 제품 ID와 같아야 합니다.
equal the order products id all
16:14:38
그렇습니다. 이제 어떤 정보를 표시할지 질문입니다.
right so now the question is which information do we want to show for
16:14:42
사용자에게는 주문 테이블로 가서 제품과 카테고리, 가격을 확인합시다. 제품과 카테고리를 가져오는 것이 충분합니다.
the users let's go to the table orders so we have the product and category and the price i would say let's go and get the product and category that's enough so now instead of the id
16:14:53
이렇게 하면 제품과 카테고리가 될 것입니다. 이제 테스트해 보겠습니다. 실행하겠습니다.
I'm gonna have it like this so it's gonna be the products and that category now let's go and test it I'm gonna execute it.
16:15:01
이제 제품 ID가 없습니다. 제품 이름이 더 친숙합니다.
Now, as you can see, we don't have a product ID. We have the product name, which is more friendly.
16:15:06
이제 주문에서 두 개의 열과 제품에서 두 개의 열, 마지막으로 주문에서 두 개의 열이 있습니다.
So we have now those two columns from the orders and those two from the products and the last two as well from the orders.
16:15:12
정말 보기 좋고 친숙해 보입니다. 이제 고객에 대해서도 같은 작업을 해보겠습니다.
So it looks really nice and friendly. And with that, the user don't need extra table called products. We have everything in one.
16:15:19
이제 고객에 대해서도 같은 작업을 해보겠습니다.
Now let's go and do the same for their customers. So let's go and do the same thing.
16:15:24
판매 고객 C를 조인하고 고객 ID 키를 사용하여 조인합니다.
So let's join sales customers C and as well join them using the key customer ID equal to that customer ID.
16:15:35
이제 고객에서 몇 개의 열을 가져와야 합니다. 확인해 보겠습니다. 이름, 성, 국가와 점수를 가져옵니다.
Now we have to go and grab a few columns from the customers. Let's go and check. So we have a first name, last name and country and score.
16:15:41
이름과 국가를 가져가겠습니다.
I would say I would go with the names and the countries.
16:15:45
이름과 성을 따로 두지 않고 모두 하나로 합치겠습니다.
But instead of having first name and last name, I'm going to put everything in one. So we have to go and concatenate the informations.
16:15:52
먼저 이름을 가져오겠습니다.
so we're gonna get the first name then
16:15:56
이름 사이에 공백을 추가합니다.
plus then empty between the first name
16:15:59
그리고 성을 추가합니다.
and the last name and then the last name
16:16:02
이제 우리는 이렇게 하지 않을 것입니다.
like this now we will not
16:16:05
이름을 부르지 않을 것이고 고객 이름이라고 부를 것입니다.
call it a name we're gonna go and call it the customer name because
16:16:08
나중에 우리는 직원 이름도 가질 것이므로, 다음으로 우리는 국가를 가져오고 고객의 국가라고 말해야 합니다.
later we're gonna have as well an employee name all right so next we want to get the country and we have to say this is the country from the customers so we're gonna call it
16:16:19
고객 국가, 그게 전부입니다.
customer country and that's it
16:16:22
이제 실행해 보겠습니다. 다시 우리의 주문 제품을 볼 수 있습니다.
let's go and execute it now we can see we have again our orders products
16:16:26
이제 그 고객의 정보가 있습니다. 하지만
and now we have the informations from that customer but
16:16:29
여기에는 null이 있는 문제가 있습니다. 그 이유는
here we have issue that we have some nulls and that's because there is
16:16:32
성(last name)이 없기 때문입니다. 그래서 우리가 할 일은
no last name so what we're gonna do we're gonna go and handle
16:16:35
성(last name)과 이름(first name)의 null을 처리하는 것입니다.
the nulls for the last name and as well for the first name so
16:16:38
우리는 cowlis를 사용할 것입니다. 성이 null이면 빈 문자열로 만들고 이름도 마찬가지입니다.
we're gonna use the cowlis if the last name is null then make an empty string and the same thing for the first name
16:16:48
이제 이름(first name)을 처리해 보겠습니다. 자, 이제
so first name all right so now let's go and
16:16:52
실행해 보겠습니다. 이렇게 하면 첫 번째
execute it so with that we are getting as well the first
16:16:55
이름이 없거나 첫 번째 이름이 없으면 성을 가져올 수 있습니다. 그래서 괜찮아 보입니다.
name if the last name is missing or if the first
16:16:58
좋습니다. 고객의 세부 정보가 있습니다. 마지막으로
name is missing we can get the last name so it looks good so it looks
16:17:01
직원 정보를 가져와야 합니다. 여기 직원은
good with that we have the customer's details the last thing
16:17:04
판매원 ID라고 불리며, 이를 직원 테이블에 직접 연결할 수 있습니다.
we have to go and get the employees so the employee here is
16:17:07
이제 이름과 부서를 가져오겠습니다. 먼저 조인해 보겠습니다.
called salesperson id which we can connect it directly to the table employees so if you go to the employees over here which columns do we need we have the first name, last name, department and so on.
16:17:18
판매 직원과 조인해 보겠습니다.
I would say let's go get the names and the departments. So first, let's go and join it.
16:17:22
그래서 영업 직원들을 합시다.
So let's join sales employees.
16:17:27
직원 ID를 사용하여 조인할 것이고, 주문 테이블에서 오는 판매자 ID와 조인할 것입니다.
And we're going to join it using the employee ID and we're going to join it with the sales person ID that comes from the order table.
16:17:38
이제 사람 ID 대신에 동일한 것을 가질 것입니다. 그래서 저는 그냥 복사해서 붙여넣기 할 것입니다.
So now instead of the person ID, we're going to have as well the same thing. So I would just go and copy paste this.
16:17:44
별칭 C 대신에 E를 가질 것이고, 여기에서도 E를 가질 것이며, 이를 판매 이름이라고 부를 것입니다.
So instead of the alias C, we're going to have E and as well E for here, and we're going to call it sales name.
16:17:51
그리고 우리가 가질 것, 우리는 부서를 가질 것입니다. 그래서 부서, 그게 전부입니다.
And as well, what we're going to have, we're going to have that department. So department, that's it.
16:17:57
가서 실행해 봅시다. 이제 우리의 뷰에 많은 정보가 있습니다.
Let's go and excuse it. So now we have a lot of information in our view.
16:18:01
주문에서 첫 번째 열을 가지고, 그 다음은 제품에서 가져옵니다.
So we have the first columns from the orders, then from the products.
16:18:06
그리고 여기 고객으로부터, 그리고 직원으로부터 두 개, 마지막 두 개는 다시 주문에서 가져옵니다.
And here we have from customers and those two from the employees and the last two again from the orders.
16:18:13
이로써 우리는 데이터베이스의 여러 테이블에서 모든 관련 정보를 단 하나의 뷰로 결합했습니다.
So with that we have combined now all the relevant information from multiple tables in our database in only one view.
16:18:19
이 결과는 상대적으로 크지만 여전히 우리는 있습니다.
This result is relatively big but still we have
16:18:22
모든 정보를 하나로 모았고, 사용자가 데이터를 소비하기에 더 친숙합니다.
all the information in one and it is more friendly for the users in order to consume our data instead of going and joining like all those four tables together.
16:18:32
이제 다음 단계로 이 쿼리의 결과를 데이터베이스의 뷰에 넣을 수 있습니다.
So now the next step we can put the result of this query in a view in our database so that our end users can start consuming it.
16:18:40
이제 어떻게 할 것인지, 이것이 우리의 결합된 쿼리입니다.
so how we're gonna do it this is our combined query
16:18:43
이제 ddl을 작성할 것입니다.
and now we're gonna write the ddl for
16:18:46
뷰를 생성하고 이름을 order로 지정할 것입니다.
it so create view and now we're gonna give it the name order
16:18:50
전체 내용을 두 개의 괄호에 넣습니다.
details and then us and we're gonna put
16:18:53
시작과 끝에 괄호를 추가하고, 물론 잊지 말아야 할 것은
the whole thing in two parentheses so at
16:18:56
스키마입니다. 우리의 스키마는 sales입니다.
the start and at the end and of course don't forget the
16:18:59
그 다음 뷰 이름을 지정합니다.
schema so our schema is sales sales
16:19:03
올바른 스키마에 넣기 위해서입니다.
dots then we have the view name just in
16:19:06
모든 준비가 완료되었습니다. 이제 실행해 보겠습니다.
order to have it in in the correct schema and not in dbo so
16:19:09
데이터베이스를 확인해 보세요. 새로 고침하면
everything is ready let's go ahead and execute it so now let's
16:19:13
두 번째 뷰인 order details를 찾을 수 있습니다.
go and check our database if you go and refresh
16:19:16
이제 테스트해 보겠습니다. select star를 입력합니다.
you will find our second view order details so
16:19:19
sales v에서
now let's go and test it we're gonna say select star
16:19:23
판매에서 v
from sales v
16:19:26
주문 세부정보를 실행합시다. 이제 데이터베이스의 모든 중요한 정보를 보여주는 통합 보기를 얻고 있습니다.
order details let's go and execute it and with that we are getting now a combined view that are showing all important information from the database.
16:19:37
사용자가 볼 수 있는 것이 바로 이것입니다. 따라서 사용자는 테이블이 몇 개 있는지, 그리고 모든 테이블을 어떻게 조인하는지에 대해 신경 쓰지 않습니다.
So this is what the users can see. And with that, the users don't care about how many tables do we have in the tables and how to join all those tables.
16:19:45
우리는 하나의 보기만 가지고 있으며, 그 위에서 작업을 시작할 수 있습니다. 이것은 뷰에 대한 매우 일반적인 사용 사례입니다.
We have only one view and we can start working on it. This is a very common use case for the views.
16:19:55
좋습니다, 다음 시나리오로 넘어갑니다. 다음 사용 사례로, 우리는 모든 SQL 뷰를 사용합니다.
OK, moving on to the next scenario, to the next use case, we use SQL views in all
16:20:00
보안을 구현하고 데이터베이스의 데이터를 보호하기 위해서입니다.
to implement security and to protect our data in the database.
16:20:03
많은 시나리오에서 우리는 데이터에 민감한 정보가 있으며, 이를 모든 사람과 공유할 수 없습니다.
In many scenarios, we have sensitive information in our data and we cannot go and share it with everyone.
16:20:09
따라서 최선의 방법 중 하나는 사용자가 공유하기 전에 데이터를 보호하기 위해 뷰를 만드는 것입니다.
So one of the best practices is to create views in order to protect your data before sharing it with the users.
16:20:16
이것이 무엇을 의미하는지 이해해 봅시다. 이제 뷰 없이, 오직 테이블만 있는 시나리오를 먼저 이해해 봅시다.
So let's understand what this means. So now let's understand first the scenario without views, only tables.
16:20:22
이제 주문 테이블이 있고, 네 개의 열과 세 개의 행이 있다고 가정해 봅시다.
So now let's say that you have the table orders, four columns and three rows.
16:20:24
이제 테이블 주문이 있고, 네 개의 열과 세 개의 행이 있다고 가정해 보겠습니다.
And then you have like, for example, a manager that has an access directly to the database and start writing some queries in order to retrieve data.
16:20:32
예를 들어, 데이터베이스에 직접 접근할 수 있는 관리자가 있고, 데이터를 검색하기 위해 쿼리를 작성하기 시작합니다.
But in your project, you have multiple people that has an access to your database, like for example, a data analyst, and as well, she is writing a script in order to retrieve data from the orders.
16:20:42
프로젝트에는 데이터베이스에 접근할 수 있는 여러 사람이 있습니다. 예를 들어, 데이터 분석가가 있으며, 그녀는 주문에서 데이터를 검색하기 위해 스크립트를 작성하고 있습니다.
And as well, you have maybe a student that has an access to your database and querying the data, like any other role, like a manager and data analyst.
16:20:49
또한 데이터베이스에 접근할 수 있는 학생이 있을 수 있으며, 관리자나 데이터 분석가와 같은 다른 역할처럼 데이터를 쿼리하고 있습니다.
So as you can see, you have now different roles in your project and all of them having the same rights by accessing directly your table.
16:20:58
보시다시피, 프로젝트에는 이제 서로 다른 역할이 있으며, 모두가 테이블에 직접 접근하여 동일한 권한을 가지고 있습니다.
So a manager or data analyst or student, they are seeing the whole table or rows and all columns.
16:21:05
관리자, 데이터 분석가 또는 학생은 전체 테이블이나 행, 모든 열을 보고 있습니다.
And of course, in the real projects, this is a big problem. Sometimes the data are sensitive and you cannot give an access for everyone.
16:21:12
물론 실제 프로젝트에서는 이것이 큰 문제가 됩니다. 때때로 데이터는 민감하며, 모든 사람에게 접근 권한을 줄 수는 없습니다.
And of course, if you are using only tables, this is going to be a nightmare because you can go and create multiple tables, but it's going to be really hard to make all those tables in sync.
16:21:20
그리고 물론, 테이블만 사용하는 경우 이는 악몽이 될 것입니다. 여러 개의 테이블을 만들 수 있지만, 모든 테이블을 동기화하는 것은 정말 어렵습니다.
But instead of that, we have views. So what you can do, you can go and remove all accesses to the physical table.
16:21:27
그 대신 뷰가 있습니다. 따라서 할 수 있는 것은 물리적 테이블에 대한 모든 접근을 제거하는 것입니다.
But instead, you can go and create multiple views for each role.
16:21:32
대신 각 역할에 대해 여러 개의 뷰를 생성할 수 있습니다.
For example, you can go and create a view called orders managers.
16:21:35
예를 들어, '주문 관리자'라는 뷰를 생성할 수 있습니다.
And maybe you can give all the data and all the columns because the managers are allowed to see, let's say, sensitive data.
16:21:41
그리고 아마도 모든 데이터와 모든 열을 제공할 수 있습니다. 왜냐하면 관리자는 민감한 데이터를 볼 수 있기 때문입니다.
But still, it's nice to create a view. Maybe you change your mind later and you go and remove something.
16:21:46
하지만 여전히 뷰를 만드는 것이 좋습니다. 나중에 마음을 바꾸고 무언가를 제거할 수 있습니다.
Now, let's say that for the data analyst, you want to offer all the data, but there is only one column that is very sensitive.
16:21:53
이제 데이터 분석가에게 모든 데이터를 제공하고 싶지만, 매우 민감한 열이 하나만 있다고 가정해 보겠습니다.
So what you can do, you can go and create another view called orders analyst.
16:21:57
따라서 할 수 있는 것은 '주문 분석가'라는 또 다른 뷰를 생성하는 것입니다.
So in the view, only three columns are available A, B, C. And then you give access to all data analysts.
16:22:03
뷰에서는 A, B, C의 세 열만 사용할 수 있습니다. 그리고 모든 데이터 분석가에게 접근 권한을 부여합니다.
And with that, you have protected this sensitive information. So we call this column level security. And now we come to our poor students.
16:22:11
그렇게 하면 이 민감한 정보를 보호할 수 있습니다. 이를 열 수준 보안이라고 부릅니다. 이제 불쌍한 학생들에게 가보겠습니다.
And here we create another view where we are not only protecting the column D, but also we are protecting few rows.
16:22:18
여기에서 우리는 열 D를 보호할 뿐만 아니라 몇 개의 행도 보호하는 또 다른 뷰를 생성합니다.
Like for example, the row number three, because we want to offer only few information to the students.
16:22:22
예를 들어, 세 번째 행을 보호합니다. 왜냐하면 학생들에게 몇 가지 정보만 제공하고 싶기 때문입니다.
So we are protecting the columns and as well the rows.
16:22:26
따라서 우리는 열과 행을 모두 보호하고 있습니다.
And for that we can create another dedicated view called for example order students and we can offer it to the students and with that we are doing column level security and as well row level security.
16:22:38
이를 위해 '주문 학생'이라는 또 다른 전용 뷰를 생성할 수 있으며, 이를 학생들에게 제공할 수 있습니다. 이렇게 하면 열 수준 보안과 행 수준 보안을 모두 수행하게 됩니다.
So we are offering multiple views very easily without having to worry how to load the data from one table to another.
16:22:45
따라서 우리는 데이터를 한 테이블에서 다른 테이블로 로드하는 방법에 대해 걱정하지 않고 여러 개의 뷰를 매우 쉽게 제공합니다.
So creating those views are really easy and provide us a perfect tool in order to manage the security of our data.
16:22:53
따라서 이러한 뷰를 만드는 것은 정말 쉽고 데이터 보안을 관리하기 위한 완벽한 도구를 제공합니다.
So this is one very common use case of using views in data projects. All right, so now let's have the following task.
16:22:58
이것은 데이터 프로젝트에서 뷰를 사용하는 매우 일반적인 사용 사례입니다. 자, 이제 다음 작업을 진행해 보겠습니다.
And it says provide a view for EU sales team that combines details from all tables and excludes data related to the USA.
16:23:08
EU 영업 팀을 위해 모든 테이블의 세부 정보를 결합하고 미국과 관련된 데이터를 제외하는 뷰를 제공하라고 합니다.
So the first part of the task is similar to what we have already done, but we cannot offer all data for the user.
16:23:14
이번에는 팀, 즉 영업 팀을 위해 특별히 생성된 뷰를 제공합니다.
So this time we are providing a view that is specifically created for a team, the sales team.
16:23:20
우리가 이미 한 첫 번째 부분은 모든 세부 정보를 하나의 뷰로 결합하는 것입니다.
So the first part we have already done it where we are combining all details in one view.
16:23:24
하지만 우리가 만든 뷰의 문제는 모든 데이터를 보여준다는 것입니다. 하지만 이제 요구 사항이 변경되었습니다. 모든 데이터를 보여줄 수 없습니다.
But the problem with the view that we have created that it shows all data. But now the requirement change. We cannot show all data.
16:23:31
우리는 세부 정보에서 미국 데이터를 제외해야 합니다. 그러니 어떻게 할 수 있는지 봅시다. 매우 간단합니다. 같은 쿼리를 가져올 것입니다.
We have to go and exclude the USA data from our details. So let's see how we can do that. It's very simple. We're going to go and grab the same query.
16:23:38
우리는 그것을 반복하지 않을 것입니다. 그래서 여기에서 테이블을 조인하고 모든 것을 준비합니다.
We will not repeat that. So we have as well here joining tables and prepare everything.
16:23:44
하지만 모든 데이터를 보여주는 대신, 고객 국가를 기준으로 데이터를 필터링할 것입니다.
But instead of showing all data, what we're going to do, we're going to go and filter the data based on the customer country.
16:23:50
그래서 매우 간단합니다. 마지막에 C 국가가 미국이 아닌 경우의 where 절이 있을 것입니다.
So it's very simple. At the end, we will have a where clause where the C country is not equal to USA.
16:24:02
그래서 이제 필터가 있습니다. 실행해 봅시다.
So we have now a filter. Let's go and execute it.
16:24:05
그렇게 하면 출력에서 미국이 아닌 주문을 얻고 있습니다.
And with that, as you can see in the output, we are getting the orders that are not from USA.
16:24:10
그렇게 하면 미국의 데이터를 보호하고 EU 영업 팀은 자신의 데이터만 접근할 수 있습니다.
And with that, we are protecting the data of the USA and the EU sales teams can access only their data.
16:24:17
그래서 보기 좋고 보호됩니다. 이제 우리는 역할 수준 보안을 구현하고 있습니다.
so it looks nice and protected and with that we are doing now
16:24:20
역할 수준 보안은 이제 보지 못하게 할 모든 행을 숨기는 것입니다.
role level security that means we are hiding now all the
16:24:23
보지 못하게 할 모든 행이 이 사용자 그룹에서 소비됩니다. 이제 다음 단계는 매우 간단합니다.
orders all the rows that are not allowed to be seen
16:24:27
모든 것을 하나의 뷰에 넣을 것입니다. 그래서 쿼리가 준비되었고 새로운 뷰를 생성할 수 있습니다.
and consumed from this group of users so now what
16:24:30
그럼 스키마가 필요하고 이름은 거의 동일할 것입니다.
is the next step it is very simple we're gonna go and put everything in one view so with that we have the query ready and we can go and create the new view so we're gonna We're going to call it create view.
16:24:41
그래서 주문 세부 정보, 그리고 괄호를 이렇게 가져와야 합니다.
Then we need the schema and the name going to be almost the same.
16:24:45
모든 것이 준비되었습니다. 실행해 봅시다. 이제 새 뷰를 보기 위해 새로 고침할 수 있습니다.
So order details, but you and then we have to have as pants parentheses like this.
16:24:53
아직 보이지 않으면 여기에서 뷰로 가서
So everything is ready. Let's go and execute it. And now we can go and refresh in order to see our new view.
16:24:58
폴더를 새로 고침할 수 있습니다. 그래서 이제
If you still don't see it you can go to the views over here
16:25:01
새로운 뷰를 확인할 수 있습니다. 물론 다음 단계는
and refresh as well to the folder so with that i
16:25:04
가서 테스트하는 것입니다. 새로운 쿼리를 생성해 봅시다.
can see we have our new view now of course the next step we
16:25:08
판매에서 선택하여
go and test it so let's create a new query select
16:25:12
판매에서 스타와
star from sales and
16:25:15
v 주문 세부정보 eu 그래서 테스트해 보겠습니다. 그리고 그와 함께 보시다시피 우리는 EU 판매 팀과 관련된 데이터에 대해서만 결합된 보기를 얻고 있습니다.
v order details eu so let's test it and with that as you can see we are getting the combined view only for the data that is relevant for the EU sales team.
16:25:26
그래서 여기서 미국 기록은 보이지 않습니다.
So I'm not seeing here any USA records.
16:25:29
그래서 우리는 미국의 주문과 같은 몇 개의 행을 보호하는 뷰를 제공하고 있습니다.
So with that, we are providing view that protects few rows like the orders from USA.
16:25:34
보시다시피, 뷰는 데이터의 보안을 제공하는 데 정말 훌륭합니다. 열이나 규칙을 보호하든 간에요.
So as you can see, views are really great in order to provide security to our data, whether we are protecting the columns or the rules.
16:25:42
예를 들어, 우리의 뷰에서 미국 주문을 제거하고 싶다고 말할 수 있을 뿐만 아니라, 부서 정보가 민감한 정보라고 가정해 보겠습니다.
For example, in our view, we can say not only I want to remove the USA orders, but let's say the department information is sensitive information.
16:25:51
그 정보를 뷰에서 숨기고 싶습니다. 그래서 간단히 제거할 수 있습니다.
and I would like to hide it from the view so you can just simply remove
16:25:54
선택에서 그것을 제거하고, 그렇게 하면 열 수준의 보안을 수행하는 것입니다.
it from the select and with that you are doing column level security so
16:25:58
이제 사용자에게 제공할 수 있는 두 가지 옵션이 있습니다.
now I have two options that I can provide to the users the
16:26:01
첫 번째 옵션은 역할 수준의 보안이 없습니다.
first option doesn't have any like role level security it
16:26:04
첫 번째 뷰는 주문 세부 정보입니다. 필터가 없으므로 모든 주문을 표시합니다.
is the first view the order details we don't have
16:26:07
여기서는 모든 데이터를 볼 수 있는 사람들에게만 접근을 제공합니다.
there any filters so it's going to show all the orders so here we give
16:26:10
우리는 또 다른 옵션이 있습니다. EU와 관련된 세부 정보입니다.
access only to people that are allowed to see all data and
16:26:13
모든 데이터를 표시하지 않고 관련된 하위 집합만 표시합니다.
we have another option the details with the EU it
16:26:16
EU 팀을 위한 것이므로 이제 데이터 보안을 쉽게 제어할 수 있습니다.
doesn't show all data it shows only a subset that is relevant
16:26:19
뷰를 사용하여 내 데이터의 보안을 제어하는 것이며, 이것은
for the EU team so now it's really easy to control the
16:26:23
뷰에 대한 매우 중요한 사용 사례입니다.
security of my data using the views and this is
16:26:26
그래서 뷰에 대한 다음 사용 사례로 넘어가겠습니다.
very important use case for the views okay
16:26:32
더 동적이고 유연성을 가지기 위해서입니다.
so moving on to the next use case for the views we can use it
16:26:35
우리 프로젝트에서 이것이 의미하는 바를 이해해 봅시다.
in order to have more dynamic and flexibility in
16:26:38
테이블이 있고 여러 사용자가 이 테이블에 접근하고 있다고 가정해 보겠습니다.
our projects so let's understand what this means if you have
16:26:41
무슨 일이 일어날 수 있을까요? 디자인과 데이터 모델에 대해 마음을 바꿀 수 있습니다.
a table and you have multiple users accessing this table now
16:26:45
또는 다른 결정을 내릴 수 있습니다. 테이블 이름을 바꾸기로 결정하거나, 몇 개의 열 이름을 바꾸기로 결정할 수 있습니다.
what can happen you might change your mind about the design and the data model of your database where you can say you know what instead Instead of having one table, I'm going to go and split it into two tables.
16:26:55
또는 열을 추가하거나 열을 제거할 수 있습니다. 물리적 데이터 모델에 변경을 하고 있습니다.
Or maybe another decision. You say, you know what? I'm going to go and rename a table. Or in another day, you decide, you know what? Let's go and rename a few columns.
16:27:02
무슨 일이 일어날지 아시겠습니까? 테이블에 접근하는 모든 사용자들이 불평할 것입니다.
Or maybe add a column, remove columns. So you are doing changes to your physical data model. And you are changing stuff in the tables.
16:27:09
모든 사용자가 복잡한 SQL 쿼리를 가지고 있기 때문입니다.
You know what can happen? All those users that are accessing the tables are going to scream.
16:27:13
그리고 테이블의 작은 변경이 그들의 쿼리에서 모든 것을 망치고 있습니다.
Because all of them having a complex SQL queries.
16:27:17
이것은 에스컬레이션을 의미하며, 데이터베이스에서 어떤 변경도 하기 전에 100명과 이야기하지 않고는 더 이상 자유롭게 변경할 수 없습니다.
and your small changes at the tables are breaking everything in their queries.
16:27:22
그리고 이것이 의미하는 바는, 이는 에스컬레이션을 의미하며, 더 이상 데이터베이스에서 변경할 자유가 없다는 것입니다. 변경하기 전에 100명과 이야기해야 합니다.
And what this means, this means escalations and you don't have anymore the freedom to change anything in your database without talking before to 100 people before doing any change.
16:27:33
우리는 그렇게 하지 않습니다. 대신 뷰를 사용합니다. 그럼 어떤 일이 발생할 수 있을까요?
So we don't do that. Instead of that, we use views. So what can happen?
16:27:37
뷰를 생성하고 사용자에게 이 뷰를 사용하라고 말합니다. 그러면 저를 혼자 두세요.
You create a view and you tell the users, okay, take this view and consume it and leave me alone.
16:27:42
이제 원하는 모든 변경을 할 수 있는 자유가 다시 생깁니다.
And now you have again your freedom to do any changes you want.
16:27:46
그래서 테이블로 가서 분할하고 이름을 바꾸고
So you go to your tables and do splitting, renaming and
16:27:49
원하는 모든 것을 변경할 수 있지만, 사용자들이 변경 사항을 인식하지 않도록 테이블과 뷰 간의 쿼리를 업데이트해야 합니다.
changing everything you want as long as you are updating the query between the table and the view to make sure that the users are not noticing any change.
16:27:59
예를 들어, 테이블을 두 개의 테이블로 나누면, 뷰에 조인 또는 유니온을 추가하여 사용자가 익숙한 동일한 구조를 재구성해야 합니다.
So for example, if you go and split the table into two tables, then you have to put in the view, a join or a union in order to reconstruct the same structure that the users are used to.
16:28:10
데이터베이스에서 ID 대신 키라고 부르려면, 이름을 바꾸고 싶을 때는
And if you would like to rename something in your database, like instead of ID, you are now calling it a key.
16:28:15
뷰의 쿼리로 가서 키에서 ID로 다시 이름을 바꾸면 됩니다.
All you have to do now is to go to the query of the view and rename it back from a key to an ID.
16:28:21
그래서 아무도 물리적 테이블에 변경을 하고 있다는 것을 알 수 없습니다.
So no one can notice that you are doing changes to the physical tables.
16:28:26
그래서 뷰를 사용하고 사용자에게 제공하는 것은 당신에게 게임 체인저입니다.
So using views and offering it to users is a game changer for you.
16:28:30
사용자에게 뷰를 제공하면 더 많은 자유를 줄 수 있습니다.
because giving the users views can it gives you more freedom
16:28:33
동적이고 무엇이든 변경할 수 있는 유연성을 제공합니다.
dynamic and flexibility to change anything in
16:28:36
데이터 모델과 테이블을 머리 아프지 않게 변경할 수 있습니다.
your data model and the tables without getting any headache
16:28:40
그래서 이것은 뷰의 놀라운 사용 사례입니다.
so this is amazing use case for the views okay
16:28:46
계속해서 뷰에 대한 많은 사용 사례가 있습니다. 정말 놀랍습니다.
moving on we have a lot of use cases for the views they are just amazing so
16:28:50
다음은 데이터 모델의 두 번째 버전을 도입하기 위해 뷰를 사용할 수 있다는 것입니다.
the next one is we can use views in order to introduce a second version of my data model
16:28:56
다른 언어로 여러 언어를 제공할 수 있습니다.
in another language so we could offer multiple languages
16:28:59
사용자에게 제공할 수 있습니다. 이제 무엇을 의미하는지 이해해 봅시다.
to the users let's understand what this means so now we have the
16:29:02
다음 시나리오는 다시 테이블 주문이 있으며,
following scenario we have again our table orders where
16:29:05
데이터는 지속되고 모든 것이 영어로 되어 있습니다.
the data is persisted and everything in english and
16:29:08
물론 때때로 국제 팀이 데이터에 접근하는 경우가 있습니다.
of course what happens sometimes you have like international team that
16:29:12
미국에 팀이 있고, 독일에서 팀이 있을 수도 있습니다.
are accessing your data so you have team in usa and
16:29:15
이 데이터에 접근하고 싶어하는 최종 사용자입니다. 물론 사용자의 수에 따라 다릅니다.
maybe you have team from germany that as well are end users that want to access the data of course it depends on the number of users
16:29:22
데이터베이스를 사용하는 많은 사용자가 있다면, 독일과 인도에서 오는 경우가 있을 수 있습니다.
that are using your database but if you have a lot of users that
16:29:26
독일과 인도에서 온 사용자들이 많다면
come from Germany and as well from India it might make
16:29:29
데이터를 번역하는 것이 좋을 수 있습니다.
sense that you go and translate your data
16:29:32
예를 들어, 테이블 주문에 대한 접근을 제공하는 대신
and the table structure into another language so
16:29:35
bestellung이라는 다른 뷰를 만들 수 있습니다.
for example instead of giving access to the table orders we
16:29:39
독일어로 된 주문이지만, 새로운 이름을 부여하는 것뿐만 아니라
can create another view called bestellung that's
16:29:42
객체의 이름도 변경할 수 있습니다.
the order in German but not only you are giving a new name
16:29:45
뷰 안의 모든 열을 변경하면 독일 사용자가 독일어 뷰에 접근하게 되어
for the object you could go as well and rename
16:29:48
데이터 내용을 이해하기가 더 쉬워질 것입니다. 인도 팀과 인도 사용자도 마찬가지입니다.
all the columns inside the view then the German user is going to access the German view and it's going to be for them easier to understand the content of your data face.
16:29:58
힌디어로 뷰를 제공할 수 있습니다. 그 단어를 올바르게 발음하고 있는지 잘 모르겠지만,
The same thing for the Indian team and for the Indian users, you can go and provide a view in Hindi.
16:30:04
힌디어로 제가 처음 말한 단어입니다.
I'm not sure whether I'm pronouncing that word correct, but this is the first word that I said in Hindi.
16:30:10
힌디어를 배울 것이라고 약속하지는 않지만, 독일어를 배우는 것으로 충분합니다.
I don't promise that I'm going to learn the Hindi language because it's enough to learn Germany.
16:30:15
이 단어, Adish를 쓰려고 노력하고 있습니다. 맞기를 바랍니다.
So I'm trying as well to write this word, Adish. I hope it is correct.
16:30:20
솔직히 말해서, 이 단어를 힌디어로 쓰는 것이 정말 흥미롭습니다. 이제 주제로 돌아가겠습니다.
And to be honest, it is really interesting how you write this word in Hindi. So now back to the topic.
16:30:25
이제 우리는 데이터베이스에 대한 번역을 제공하기 위해 뷰를 사용하고 있습니다.
As you can see now we are using like the views in order to provide a translation for our database by just giving a new name for the views and as well for the columns.
16:30:36
뷰와 열에 새로운 이름을 부여함으로써 다국어를 제공하는 또 다른 좋은 사용 사례입니다.
So this is another nice use case that I usually use as well in my projects in order to provide multi-languages for the data model that I have and I can do that with the power of views.
16:30:50
이제 제가 가장 좋아하는 뷰의 사용 사례로 넘어가겠습니다.
Now we come to my favorite use case for the views and that I personally recommend in each project that we can use views as a virtual data mart in a data warehouse.
16:31:00
각 프로젝트에서 추천하는 가상 데이터 마트로서 뷰를 사용할 수 있습니다.
So now why this is my favorite because I'm a specialist in data warehouses and data lakes and this topic is very important decision in each project like this.
16:31:09
왜 이게 제 최애인지, 데이터 웨어하우스와 데이터 레이크의 전문가이기 때문입니다.
So let's understand what this means. So now a classical data
16:31:12
이 주제는 이러한 프로젝트에서 매우 중요한 결정입니다.
warehouse architecture based on the approach of nmon
16:31:15
이제 이것이 의미하는 바를 이해해 보겠습니다.
is going to look like this we have multiple source systems
16:31:18
고전적인 데이터 웨어하우스 아키텍처는 nmon 접근 방식을 기반으로 합니다.
where our data are spreaded and now we would like to go and
16:31:21
여러 소스 시스템이 있습니다.
extract all our data from these multiple sources
16:31:24
우리의 데이터가 퍼져 있는 곳입니다.
and put it in one big database called data
16:31:28
이 여러 소스에서 모든 데이터를 추출하고
warehouse and there will be a lot of operations on this central
16:31:31
하나의 큰 데이터베이스에 넣고 싶습니다.
database like the data can be first cleaned and then maybe integrated
16:31:35
함께 역사적 데이터를 구축하고 있으므로 복잡한 보고 및 분석을 위해 데이터를 준비하기 위해 여러 단계를 진행할 것입니다.
together and maybe we are building there some historical data so we're going to be doing multiple steps in order to prepare the data for complex reporting and analysis.
16:31:44
우리가 데이터 웨어하우스에서 일반적으로 하는 것은 모든 정보를 물리적 테이블로 저장하는 것입니다.
And what we usually do in the data warehouse, we can store all those informations as a physical table.
16:31:50
데이터 웨어하우스를 구축한 후 어떤 일이 발생할 수 있을까요? 다양한 보고를 위해 데이터 웨어하우스에 접근하고자 하는 여러 사용 사례가 있을 것입니다.
Now, once we have built the data warehouse, what can happen? We're going to have multiple use cases that would like to access the data warehouse in order maybe to do some different reporting.
16:32:00
보고 엔진인 Power BI와 같은 것을 즉시 연결하면 매우 복잡해질 것입니다.
Now, it's going to be very complex if we connect immediately like a reporting engine like Power BI
16:32:06
데이터 웨어하우스에 직접 연결하는 대신 여러 하위 집합으로 나누려고 합니다.
directly to the data warehouse but instead of this we try
16:32:09
주제나 도메인 또는 부서별로 나눌 수 있습니다.
to split the data warehouse into multiple subsets like
16:32:13
우리는 이를 데이터 마트라고 부릅니다.
we can split it after topic or domain or departments
16:32:16
데이터 마트는 항상 특정 사용 사례에 맞춰져 있습니다.
and we call those subsets as data marts
16:32:19
예를 들어, 우리는 하나의 주제에 집중하는 데이터 마트를 가질 수 있습니다.
so a data mart is always specific for a use case
16:32:22
판매를 위한 전용 마트와 다른 마트를 가질 수 있습니다.
that's focus on one topic like for example we
16:32:25
판매를 위한 전용 마트와 재무 주제 전용 데이터 마트를 가질 수 있습니다.
could have a dedicated mart for the sales and another
16:32:29
두 마트 모두 데이터 웨어하우스에서 나옵니다. 마지막 레이어는 예를 들어 보고 및 대시보드가 될 것입니다.
data mart which is dedicated only for finance topics but both of them comes from our data warehouse then the last layer gonna
16:32:36
예를 들어, 대시보드를 생성하는 Power BI와 같은 것이 될 것입니다.
be like for example the reporting and dashboarding maybe you have
16:32:39
판매와 같은 데이터 마트와 다른 마트에서 몇 가지를 가져올 수 있습니다.
something like power bi where you are creating a dashboard one
16:32:42
이제 데이터 마트에서 큰 질문은
data mart like the sales or and as well maybe a few stuff
16:32:45
데이터를 어떻게 저장해야 할까요? 데이터를 저장해야 할까요?
from other marts but now the big question here in the data mart
16:32:48
테이블을 사용해야 할까요, 아니면 뷰를 사용해야 할까요?
is how should i store the data should i store the data
16:32:51
데이터 마트를 구축하는 경우 최선의 방법은 뷰를 사용하는 것입니다.
using tables or should i use views and
16:32:54
우리는 이를 가상 데이터 마트라고 부르며, 사용하는 이유가 많습니다.
now the best practice says if you are building data marts
16:32:58
데이터 마트에서 뷰를 사용하는 것이 테이블을 사용하는 것보다 훨씬 낫습니다.
then use views and we call this virtual data marts and there are many reasons why using
16:33:04
예를 들어, 더 동적이고 빠르게 변경할 수 있습니다.
views at the data mart it's way better than using tables like
16:33:07
데이터 마트에서는 많은 비즈니스 로직을 구축하고 있기 때문입니다.
for example it is more dynamic and quicker to
16:33:10
유연성과 속도를 원합니다.
change them because usually at the data mart you are building a lot of business
16:33:13
유지 관리 노력이 매우 간소화되어 ETL이나 데이터 로드를 구축할 필요가 없습니다.
logics and you want to have some flexibility and speed and
16:33:17
데이터 웨어하우스에서.
the maintenance efforts is very simplified no need to build
16:33:20
데이터 웨어하우스에서의 모든 ETL 또는 데이터 로드
any etls or data loads from the data warehouse
16:33:23
데이터 부분으로, 이것은 데이터 웨어하우스를
to the data parts and this makes the data warehouse as
16:33:26
당신의 데이터에 대한 진정한 단일 진실의 지점으로 만들며, 한 레이어에서 다른 레이어로 데이터를 복사하기 시작하면 유지 관리가 정말 어렵고 혼란스러워지며, 매우 제한된 모니터링과 데이터 품질을 가져야 합니다.
a real single point of truth for your data and once you start copying data from one layer to another layer, it's going to be really hard to maintain and chaotic and you have to have really restrict monitoring and data quality.
16:33:39
그래서 뷰를 사용하면 데이터 웨어하우스의 상태를 항상 반영할 수 있습니다.
So that's why using views, you can always reflect the status of the data warehouse.
16:33:43
그리고 이것은 물론, 각 데이터 웨어하우스 프로젝트에서 중요한 포인트인 데이터 일관성을 도와줄 수 있습니다.
And this can help you, of course, with the data consistency, which is a critical point in each data warehouse project.
16:33:50
그래서 우리가 가상 데이터 마트를 구축하고 이 레이어에서 뷰를 사용하는 이유는 많습니다.
So there are many reasons why we build virtual data mart and we go with the views in this layer.
16:33:57
뷰가 데이터 웨어하우스를 구축하는 데 매우 중요한 역할을 하고 있는 것을 볼 수 있습니다. 이것은 데이터 프로젝트에서 뷰를 사용하는 또 다른 놀랍고 매우 중요한 사용 사례입니다.
see how the views are playing a very important role in building a data warehouse so this is another amazing and very important use case of using views in your data projects
16:34:12
좋아요, 친구들, 이제 뷰에 대한 간단한 요약을 해봅시다. 우리는 뷰가 실제로 데이터베이스에 데이터를 저장하지 않고 쿼리 결과를 기반으로 하는 가상 테이블이라는 것을 배웠습니다.
all right friends so now let's have a quick recap about views so we have learned that views are a virtual table that is based on the result of a query without actually storing any data in the database.
16:34:24
우리는 데이터베이스에 복잡한 SQL 로직과 쿼리를 지속하기 위해 뷰를 사용합니다.
So we use views in order to persist a complex SQL logic and query in the database.
16:34:29
그리고 우리는 어떤 시나리오에서 뷰가
And we have learned that in some scenarios views are
16:34:33
CTE보다 더 낫다는 것을 배웠습니다. 왜냐하면 재사용성을 향상시키기 때문입니다.
better than CTE because it improves the reusability
16:34:36
그리고 여러 쿼리에서 복잡성을 줄여 전체 프로젝트의 복잡성을 줄입니다. CTE는 단지 하나의 쿼리에서 재사용성만 향상시킵니다.
and reduces the complexity in multiple queries which reduce the complexity of the whole project where the CTE only improves the reusability in one query.
16:34:46
그리고 우리는 어떤 시나리오에서 뷰가 테이블보다 더 낫다는 것도 배웠습니다.
And we have learned that as well the views in some scenarios are better than tables.
16:34:50
우리는 뷰가 매우 유연하고 유지 관리가 더 쉽다는 것을 배웠습니다. 왜냐하면 데이터를 저장하지 않기 때문이며, 테이블에 비해 뷰에서 변경하는 것이 정말 빠르고 쉽습니다.
We have learned that they are very flexible and and easier to maintain since they don't store any data and it's really fast and easy to change stuff in the view compared to the tables.
16:35:01
하지만 또한 우리는 테이블이 뷰보다 더 빠르다는 것도 배웠습니다. 이제 뷰에 대한 끝없는 사용 사례가 있습니다.
But as well, we have learned that the tables are faster than views. Now, they are like endless use cases for the views.
16:35:07
하지만 프로젝트에서의 제 경험으로, 저는 여러분을 위해 뷰의 가장 좋은 사용 사례를 선택했습니다.
But from my experience in projects, I have chosen for you the best use cases for the views.
16:35:11
첫 번째 사용 사례는 SQL 쿼리에서 공통으로 반복되는 로직을 발견했을 때입니다.
The first use case is if we find like a common repeated logic in SQL queries,
16:35:17
우리는 이 로직을 데이터베이스의 뷰에 저장하여 사용자가 로직을 반복할 필요가 없도록 할 수 있습니다.
we can go and store this logic in a view in the database so that the users don't have to keep repeating the logic over and over.
16:35:24
그래서 우리는 중앙 비즈니스 로직을 갖기 위해 뷰를 사용합니다.
So we use views in order to have a central business logic.
16:35:28
또 다른 사용 사례는 물리적 데이터 모델의 복잡성을 숨기고 사용자에게 높은 추상화 레이어를 제공하는 것입니다.
Another use case is to hide the complexity of your physical data model and to offer for the users a high abstracted layer.
16:35:35
그래서 사용자가 매우 친숙한 것을 제공하고 데이터베이스에 있는 복잡한 기술 데이터 모델을 숨깁니다.
So you provide for the users something very friendly and you hide all the complex technical data model that you have in the database.
16:35:42
모든 사람이 당신의 데이터 모델에 전문가인 것은 아닙니다. 또 다른 사용 사례로, 우리는 데이터베이스에서 보안을 구현하고 민감한 데이터를 보호하기 위해 뷰를 사용할 수 있습니다.
Because not everyone is expert with your data model. One more use case, we can use views in order to implement security and to protect our sensitive data in the database.
16:35:51
그래서 우리는 테이블의 열이나 행을 보호하기 위해 여러 뷰를 제공할 수 있습니다.
So we can offer multiple views in order to protect columns or rows in a table.
16:35:56
또 다른 사용 사례로, 우리는 데이터베이스에 더 많은 동적성과 유연성을 갖기 위해 뷰를 사용할 수 있다는 것을 배웠습니다.
Another use case we have learned that we can use views in order to have more dynamic and flexibility for your database.
16:36:03
사용자에게 안정적인 뷰를 제공하고, 물리적 데이터 모델에서 모든 사용자에게 영향을 주지 않고 자유롭게 변경할 수 있는 것입니다.
Where we offer the users a stable view and then you have the freedom to change stuff at your physical data model without affecting all users.
16:36:11
우리가 사용자에게 안정적인 뷰를 제공하고 사용자가 물리적 데이터 모델을 변경할 자유를 가질 수 있습니다.
And another nice use case for the views we can offer multiple languages from our data model.
16:36:17
우리가 데이터 모델에서 여러 언어를 제공할 수 있는 뷰의 또 다른 좋은 사용 사례입니다.
And the last use case, we have learned how views play an important role in a data warehouse system. So views are amazing.
16:36:24
좋습니다, 친구들. 그래서 우리는 데이터베이스의 뷰에 대한 모든 것을 배웠습니다.
All right, my friends. So with that, we have learned everything about this new objects, the views in databases.
16:36:30
이것은 프로젝트의 유연성과 동적성을 위한 놀라운 것입니다. 이제 다음에는 쿼리를 기반으로 테이블을 만드는 방법을 배울 것입니다.
This is amazing for flexibility and dynamic in your projects. Now, in the next one, we're going to learn how to create tables based on query.
16:36:36
그리고 우리는 임시 테이블에 대해 배울 것입니다. 자, 시작합시다.
And we will learn about that temporary tables. So let's go.
16:36:44
좋습니다, 이제 먼저 데이터베이스 구조를 다시 살펴보겠습니다.
okay so now first let's have a look again to the database structure we
16:36:48
각 SQL 서버에는 여러 데이터베이스가 있다는 것을 배웠습니다.
have learned that in each sql server there are multiple databases
16:36:51
각 데이터베이스에는 여러 스키마가 있습니다.
and in each database there are multiple schemas and
16:36:54
이제 각 스키마 내에서 여러 객체를 정의할 수 있습니다.
now inside each schema we can define multiple objects
16:36:57
우리는 테이블과 뷰를 정의할 수 있으며, 이제 객체 테이블에 집중할 것입니다.
like we can define tables and views and now we will be focusing on the object table and we have learned as well we can use the language ddl data
16:37:06
우리는 데이터 정의 언어를 사용할 수 있다는 것도 배웠습니다.
definition language which is a set of sql commands in
16:37:09
데이터베이스 구조를 정의하기 위해 SQL 명령어를 사용할 수 있습니다.
order to define this database structure so we can use the
16:37:12
새 테이블을 정의하기 위해 CREATE SQL 명령어를 사용합니다.
sql command create in order to define a new table
16:37:16
구조를 업데이트하기 위해 ALTER를 사용합니다.
or alter in order to update the structure
16:37:19
전체 테이블을 삭제하기 위해 DROP을 사용합니다.
or drop in order to drop the whole table so a
16:37:22
테이블은 데이터베이스 구조의 객체입니다.
table is an object in the database structure and
16:37:25
우리는 데이터베이스 아키텍처의 세 가지 수준이 있다는 것을 배웠습니다.
we have learned as well there is three levels of the database architecture
16:37:28
우리는 논리적 수준에서 테이블과 관련하여 작업합니다.
and we have understood that at the logical level the middle one the conceptual level we deal as application developer or data engineer with the tables.
16:37:38
그래서 우리는 테이블과 그들 간의 관계를 정의합니다.
So we define tables and relationship between them.
16:37:41
최종 사용자나 비즈니스 분석가라면 테이블 작업이 조금 더 어려울 것입니다.
So if you are an end user or a business analyst, it's gonna be a little bit more hard to work with the tables.
16:37:47
개발자나 데이터 엔지니어가 되어야 하지만, 테이블 작업은 물리적 수준의 데이터베이스 복잡성보다 훨씬 쉽습니다.
You have to be a developer or a data engineer, but working with tables is way easier than working with the complexity of the database at the physical level.
16:37:56
테이블 작업을 위해 데이터베이스 전문가나 관리자가 될 필요는 없습니다.
So you don't have to be a database expert or administrator to work with tables.
16:38:01
여기서의 난이도는 중간 정도입니다. 추상화는 그리 낮지도 높지도 않습니다.
So the difficulty here is like in the middle. The abstraction is not that low, but as well not that high.
16:38:07
이제 질문에 답해봅시다. 테이블이란 무엇인가요? 데이터베이스 테이블은 구조화된 데이터 모음입니다.
So now let's answer the question, what are tables? A database table is a structured collection of data.
16:38:13
엑셀에서 찾을 수 있는 간단한 그리드나 스프레드시트와 같습니다.
It's like a simple grid or spreadsheet that you might find in Excel.
16:38:17
그래서 서로 다른 열이 있습니다. 각 열은 ID, 이름, 국가와 같은 필드를 나타냅니다.
So it has different columns, like each column represent a field like the ID, name, country,
16:38:22
그리고 테이블에는 여러 행이 있으며, 각 행은 데이터의 레코드 또는 항목을 나타냅니다.
and the table has as well multiple rows, and each row represent a record or an entry of the data.
16:38:28
예를 들어, 이 테이블이 직원에 관한 것이라면, 각 레코드, 각 행은 한 명의 직원입니다.
So for example, if this table is about the employees, then each record, each row is one employee.
16:38:35
이제 행과 열의 교차점을 우리는 셀이라고 부릅니다. 셀은 단일 데이터 조각입니다.
Now, the intersect between the rows and columns, we call it a cell. And a cell is a single piece of data.
16:38:42
이제 전체 테이블은 데이터베이스 파일로서 물리적으로 데이터베이스에 저장될 수 있습니다.
Now, the whole table can be stored physically in the database as database files.
16:38:47
그래서 그들은 테이블에 대한 정보를 보유하는 여러 파일처럼 데이터베이스에 있습니다.
So they are in the database like multiple files that are holding the information about the table.
16:38:53
그 파일들은 데이터베이스의 디스크 저장소에 물리적으로 저장됩니다.
And those files are stored physically in the disk storage of the database.
16:38:58
즉, 테이블 내부의 데이터는 엑셀과 같은 스프레드시트처럼 저장되지 않습니다.
So that means your data inside the tables are not stored like a spreadsheet like an Excel,
16:39:03
하지만 그들은 일반 개발자와 최종 사용자가 접근할 수 없는 특별한 데이터베이스 파일에 저장됩니다.
But they are stored in special database files that
16:39:06
그 파일에 접근할 수 없습니다. 테이블은 실제 데이터에 대한 추상화와 표현입니다.
usual developers and end users don't have access
16:39:09
실제로 데이터베이스 테이블을 쿼리할 때마다
to those files So tables again, it's like an abstraction and representation for the actual data that are in the files So actually each time you are querying the database table
16:39:19
데이터베이스는 그 파일에 가서 데이터를 가져와야 합니다.
The database has to go to those files and fetch the data for you.
16:39:23
좋습니다, 이것이 우리가 데이터베이스 테이블로 의미하는 것입니다. 이제 SQL에서 다양한 유형의 테이블이 있습니다.
Alright, so this is what we mean with database tables Okay, so now we have like different types of tables in SQL.
16:39:32
영원히 유지되는 테이블이 있습니다. 우리는 이를 영구 테이블이라고 부릅니다.
We have tables that stays forever, we call it permanent tables. So they stay as long as you don't drop them.
16:39:39
그래서 그들은 삭제하지 않는 한 계속 유지됩니다.
And you have another type of tables they called the temporary tables.
16:39:43
또 다른 유형의 테이블이 있습니다. 이를 임시 테이블이라고 부릅니다.
And those tables gonna be deleted and dropped once the session ends. So now we're gonna focus first on the first type, the permanent tables.
16:39:51
그 테이블은 세션이 끝나면 삭제되고 제거됩니다.
And there are two ways on how to create them. The first way is the classical way where you create table from scratch and then you go and insert
16:40:00
그래서 이제 우리는 첫 번째 유형인 영구 테이블에 먼저 집중할 것입니다.
data so we call it create insert and the
16:40:03
그들을 만드는 방법에는 두 가지가 있습니다.
other way called ctas create table as select it can create as well the table but based on sql query so let's understand the differences between them
16:40:16
첫 번째 방법은 고전적인 방법으로, 테이블을 처음부터 만들고 데이터를 삽입하는 것입니다.
the create insert method is the classical way on how we
16:40:20
그래서 우리는 이를 생성 삽입이라고 부릅니다.
define and create tables in sql where first we have to
16:40:23
다른 방법은 ctas라고 하는데, 선택으로 테이블을 생성하는 것입니다.
go and create the table and define the structure and
16:40:26
SQL 쿼리를 기반으로 테이블을 생성할 수 있습니다.
after that we insert our data into the database table
16:40:29
그래서 그들 간의 차이를 이해해 봅시다.
where the other method the ctas create table
16:40:32
생성 삽입 방법은 우리가 SQL에서 테이블을 정의하고 생성하는 고전적인 방법입니다.
as select this one gonna create a new table as
16:40:35
잘 하지만 이번에는 SQL 결과를 기반으로
well but this time based on the result of sql
16:40:39
쿼리이므로 이것이 의미하는 바를 이해해 봅시다.
query so let's understand what this means okay so now
16:40:42
첫 번째 방법은 삽입을 생성하는 것이며, 여기에는 두 단계가 있습니다.
to the first method create insert so here we have two steps
16:40:45
첫 번째 단계는 DDL 문이 있으며
the first step is we have a ddl statement where
16:40:48
명령어를 사용하여 생성합니다. 따라서 실행하면
we use the command create so once we execute the
16:40:51
첫 번째 단계에서 데이터베이스 엔진이 가서
first step what could happen the database engine gonna go and create
16:40:55
비어 있는 테이블을 생성합니다. 완전히 새로운 테이블입니다.
for us an empty table it is a brand new table
16:40:58
우리의 데이터를 저장할 수 있는 곳입니다. 그래서 우리는
where we can hold our data so with that we have defined the
16:41:01
테이블의 구조를 정의했지만 여전히 비어 있는 테이블입니다.
structure of our table but it's still an empty table
16:41:04
이제 다음 단계에서는 데이터를 삽입해야 합니다.
so now in the next step we have to go and insert our data
16:41:08
이 새로운 테이블 안에 데이터를 삽입해야 하며, 데이터는 여러
inside this new table so our data can come from multiple
16:41:11
출처에서 올 수 있습니다. CSV 파일이나 아마도 완전히
sources like a csv file or maybe completely from
16:41:14
다른 데이터베이스에서 마이그레이션 중이거나, 수동으로 데이터를 삽입하거나
another database where we are doing migration or maybe
16:41:17
애플리케이션에서 데이터를 삽입하거나 데이터 마이그레이션을 수행하고 있습니다.
you are inserting manually your data or maybe it come from
16:41:20
하나의 데이터베이스에서 다른 데이터베이스로. 그래서 마지막에 실행하면
an application or you are doing data migration from
16:41:23
삽입할 때 어떤 일이 발생할까요? 데이터가 삽입될 수 있습니다.
one database to another so at the end once you execute
16:41:26
이 새로운 테이블에. 따라서 이 방법에서는
insert what's gonna happen your data can be inserted
16:41:30
두 단계가 있습니다. 먼저 테이블의 구조를 정의합니다.
in this new table so in this method we have
16:41:33
두 번째 단계에서는 삽입을 처리합니다.
like two steps first we define the structure of the table
16:41:36
테이블 안에 데이터를 삽입하고 이제 이 새로운 테이블은
and the second step we take care of inserting
16:41:39
영구적으로 데이터를 저장할 수 있습니다. 이제 다른 방법을 확인해 봅시다. 이 도시는 한 단계입니다.
our data inside the table and now this new table
16:41:42
쿼리를 정의하고 이 쿼리를 실행하면
and your data can be persisted permanently now let's check the other method the city is here it's only one step
16:41:49
무슨 일이 발생할 수 있는지 데이터베이스가
where you define a query and once you execute this query
16:41:52
다른 테이블에서 데이터를 검색해야 합니다. 따라서 데이터를 검색할 수 있습니다.
what can happen the database has to retrieve the
16:41:55
방금 생성한 새로운 테이블에서 데이터를 검색할 수 있습니다.
data from another table so it might retrieve data
16:41:58
우리가 방금 생성한 새로운 테이블에서
from our new table that we just created using create insert
16:42:01
쿼리가 실행되면 결과를 얻을 수 있습니다
so once the query is executed we will get
16:42:04
새로운 브랜드 테이블을 생성할 수 있습니다
a result so now what the database can do can create a new brand table but this time the definition and the data of this new
16:42:13
우리가 지정한 정의에서 나오지 않습니다
table it doesn't come from any definition that we specify
16:42:16
쿼리의 결과에서 나옵니다
it comes from the result of the query so
16:42:19
결과에 있는 구조가 반영됩니다
whatever structure that we have in the results it's going to be reflected
16:42:23
우리의 새로운 테이블에 반영됩니다
in our new table so again the definition and
16:42:26
쿼리의 결과에서 하나씩 나옵니다
the data that we see in this new table comes one
16:42:30
정의할 필요가 없습니다
to one from the result of our query so
16:42:33
데이터를 삽입할 필요가 없습니다
in this type we don't have to define anything or to
16:42:36
쿼리의 출력이 테이블을 정의할 수 있습니다
insert any data we are just writing a query and
16:42:39
항상 데이터베이스 테이블이 필요합니다
the output of this query can define the table but in this method
16:42:42
쿼리를 실행하기 위해 데이터베이스 테이블이 필요합니다
as you can see it always needs a database table
16:42:45
우리는 처음부터 무언가를 만들고 있습니다
in order to execute the query but the create insert method
16:42:48
SQL에서 테이블을 만드는 두 가지 방법입니다
we are creating something from the scratch so these
16:42:52
그들 사이의 차이점입니다
are the two different ways on how you create tables in sql
16:42:55
CTA가 매우 유사하다는 질문을 할 수 있습니다
and the differences between them okay
16:43:01
쿼리와 그 출력이 있습니다
so now you might ask you know what the cta's are very similar
16:43:04
데이터베이스의 객체처럼 될 것입니다
to the views we have a query and the output of this query
16:43:08
그들 사이의 차이점입니다
gonna be like an object in the database so what are the differences
16:43:11
우리 데이터베이스에 세 개의 열이 있는 테이블이 있습니다
between them let's check this now let's say that in our database
16:43:14
기반으로 뷰를 생성할 수 있습니다
we have a table that has three columns abc and
16:43:18
DDL 문을 생성하여
now what we can do we can go and create a view based on a
16:43:21
데이터베이스에 뷰를 생성합니다
query so you create the ddl statement in order to create the
16:43:24
쿼리를 데이터베이스에 저장합니다
view in the database and of course the database is going to go and store the query
16:43:27
데이터베이스에 저장될 것이므로
in the database and it's going to be empty so there
16:43:30
데이터가 없을 것입니다. 뷰는 데이터를 저장하지 않으므로
will be no data because views does not store any data and
16:43:33
뷰의 쿼리는 아직 실행되지 않을 것입니다. 하지만
the query of the view will not be yet executed but
16:43:37
다른 한편으로, ctis를 사용하여 테이블을 생성하면
now in the other hand if you go and create the table using ctis
16:43:40
여기서 다시 객체에 연결된 쿼리가 있습니다.
so here again we have a query attached to the object to
16:43:43
테이블에서 데이터베이스가 해야 할 일이 있습니다.
the table so here what happens the database has to
16:43:46
구조를 이해하기 위해 쿼리를 실행해야 합니다.
execute the query in order to understand the structure
16:43:50
테이블에 삽입해야 할 데이터도 있습니다.
and as well the data that should be inserted
16:43:53
우리의 SQL 쿼리가 실행될 것입니다.
inside the table so our sql query gonna be executed
16:43:56
쿼리의 결과가 삽입될 것입니다.
and the result of the query gonna be inserted
16:43:59
이 새로운 테이블은 쿼리의 결과를 저장하고 있습니다.
inside the table so that means this new table is storing
16:44:03
이 새로운 테이블은 쿼리의 결과를 이미 저장하고 있습니다.
already the result of the query so now this
16:44:06
뷰를 생성할 때 쿼리는 실행되지 않으며 우리는
is the first differences between the table and view as you create
16:44:09
쿼리의 결과에 대한 정보가 없습니다.
view the query will not be executed and we don't
16:44:12
ctis에서는 이미 쿼리의 결과가 있습니다.
have anything about the result of the query where
16:44:15
테이블에 저장되어 있으며 모든 것이 준비되었습니다.
in the ctis we have already results of the query
16:44:18
이제 사용자가 선택할 때 어떤 일이 발생할지 봅시다.
stored inside the table and everything is prepared so
16:44:21
뷰에서 사용자가 선택할 때 어떤 일이 발생할지 봅시다.
now let's see what's gonna happen once the user selects something from
16:44:25
원본 테이블에서 데이터를 가져오고 결과를 사용자에게 제공합니다. 그러나
the view so now the database gonna go for the first time executing the query of the view in order to fetch
16:44:32
ctis에서 생성된 테이블을 쿼리하면 어떤 일이 발생할 수 있을까요?
the data from the original table and then present it as a result for the user but now in the other hand if the user go and query the table that is created from the ctis so now what can happen
16:44:43
SQL은 쿼리를 다시 실행하지 않을 것입니다.
sql will not execute again the query of
16:44:46
데이터베이스가 이미 작업을 완료했기 때문입니다.
the ctis because the database already done that and prepared
16:44:50
따라서 우리는 원본 테이블에서 쿼리하지 않으며
everything so that means we are not querying anything from the original table and the data can be directly fetched from the new table so the users can get immediately the results from our table that is created from the CTIS.
16:45:03
여기서 테이블과 뷰 간의 두 번째 차이가 나타납니다. 뷰는 CTIS보다 느립니다.
So here comes the second difference between the tables and views. The views are slower than CTIS.
16:45:09
데이터베이스는 여기서 추가 작업을 수행해야 합니다.
And that's because the database has here an extra task. It must execute the query of the view in order to get the data.
16:45:16
하지만 CTIS에서는 쿼리가 뷰보다 더 빠릅니다. 이미 모든 것을 실행하고 사용자를 위해 준비했기 때문입니다.
But in the CTIS, the query is going to be faster than the view because we have already executed everything and prepared it for the user.
16:45:24
그래서 CTAS의 테이블이 뷰보다 훨씬 빠른 이유입니다.
So that's why tables from CTAS are way faster than views.
16:45:27
이제 다음 날 원본 테이블에서 데이터 업데이트를 한다고 가정해 보겠습니다.
And now there is another difference and perspective about this, which is from my point view is more important than the performance.
16:45:34
C 열과 P 열에서 업데이트를 진행하고 있습니다. 이제 사용자가 뷰를 사용할 경우 이것이 무엇을 의미하는지 살펴보겠습니다.
So now let's say that in the next day, we are doing data updates on the original table.
16:45:40
다음 날 사용자는 다시 같은 쿼리를 실행하고 있습니다.
Like we are doing updates on the column C and as well in the column P. So now let's see what this means for the user if they are using views.
16:45:46
다시 여기서 데이터베이스는 원본 테이블에서 데이터를 가져오기 위해 뷰의 쿼리를 실행해야 합니다.
So the user on the next day is executing again the same query.
16:45:50
그렇다면 오늘 뷰에서는 어제와 다른 데이터를 얻고 있다는 의미입니다. 새로운 데이터와 업데이트가 있기 때문입니다.
And again here the database has to execute the query of the view in order to fetch the data from the original table.
16:45:56
결과적으로 사용자는 새로운 업데이트와 신선한 데이터를 볼 수 있습니다.
So that means today in the views we are getting different data than yesterday. Because we have new data and new updates.
16:46:03
따라서 사용자는 원본 테이블의 데이터 상태를 정확히 보고 있습니다.
And the user in the result can see as well the new updates and the fresh data.
16:46:08
하지만 이제 사용자가 CTAS의 테이블을 쿼리하면 어떤 일이 발생할 수 있는지 살펴보겠습니다.
So the user is seeing exactly the status of the data in the original tables.
16:46:14
CTAS의 테이블에서는 여전히 어제의 데이터를 가지고 있습니다.
But now let's see what can happen if the user go and query the table from the CTAS.
16:46:19
원본 데이터의 새로운 업데이트는 이 새로운 테이블에 반영되지 않습니다.
So in the table of the CTAS, we are still having the data from yesterday.
16:46:24
사용자가 이 테이블에서 무언가를 선택하면 데이터베이스는 원본 테이블에서 새로운 변경 사항을 쿼리하거나 가져오지 않습니다.
All those new updates from the original data will not be reflected in this new table.
16:46:28
우리는 이미 어제의 데이터를 준비했기 때문입니다. 즉, 사용자는 이제 CTAS 테이블에서 모든 데이터를 얻고 있습니다.
Because once the user selects something from this table, the database will not go and query or fetch the new changes from the original table.
16:46:36
새로운 신선한 데이터를 CTAS에서 얻는 유일한 방법은 CTAS 쿼리를 다시 실행하는 것입니다.
Because we have already prepared the data from yesterday. So that means our user now is getting all data from the CTAS table.
16:46:45
물론, 이것은 또 다른 단계이며 CTAS의 테이블을 유지하는 것이 더 어렵습니다.
And the only way to get new fresh data from the CTAS is to re-execute the CTAS query.
16:46:52
그리고 이것은 사용자에게 뷰와 CTAS 테이블 간의 큰 차이입니다. 이제 뷰에 대해 생각해 보세요.
And of course, this is another step and it is harder to maintain the table from the CTAS.
16:46:57
레스토랑에서 피자를 주문하고 있습니다. 따라서 뷰를 쿼리할 때마다 주문을 하는 것입니다.
And this is a big difference for the users between the views and the tables from the CTAS. Now, think about views.
16:47:03
셰프는 신선한 재료를 사용하여 처음부터 피자를 만들 것입니다.
You are ordering a pizza at restaurants. So every time you are querying the view, you are placing an order.
16:47:10
그렇다면 항상 신선하고 뜨거운 피자를 받고 있다는 의미입니다.
the chef gonna go and make a pizza from the scratch using the freshest ingredients.
16:47:15
셰프는 신선한 재료로 처음부터 피자를 만들 것입니다.
So that means you are always getting a fresh hot pizza.
16:47:18
그리고 CTS는 마치 식료품점에서 사온 냉동 피자와 같습니다.
And think about the CTS as like a frozen pizza from a grocery store.
16:47:23
피자는 미리 준비되어 냉동고에 보관되었습니다. 먹고 싶다면 오븐에서 데워야 합니다.
The pizza was prepared earlier and stored in the freezer. And if you want to eat it, you have to go and heat it up in the oven.
16:47:29
하지만 즉석에서 만든 신선한 피자와는 다릅니다.
But it's still not like a fresh pizza that is made on the spot and from the scratch.
16:47:34
이제 피자가 먹고 싶어졌습니다. 그래서 잠깐 쉬어야 할 것 같습니다.
Now I made myself hungry because I love pizza. So I think I'm gonna go for a quick break.
16:47:51
좋아요, 이제 이 두 방법의 문법을 빠르게 확인해봅시다. 첫 번째는 create insert입니다.
Okay, so now let's check quickly the syntax of those two methods. The first one is create insert.
16:47:55
첫 번째 단계로, DDL 문을 사용하여 테이블을 생성해야 합니다.
So first step, we have to go and create a table using a DDL statement.
16:47:59
그래서 우리는 create 명령을 사용하고, SQL에 테이블을 생성할 것인지 뷰를 생성할 것인지 알려야 합니다.
So we use the command create, and then we have to tell SQL, are we creating a table or view?
16:48:05
이 시나리오에서는 테이블을 생성하고, 테이블의 이름을 지정합니다.
In this scenario, we are creating a table, and then we specify the name of the table.
16:48:09
그 후에는 두 개의 괄호가 있고 그 안에
Then after that we have two parentheses and inside them we
16:48:12
이 테이블 안에 필요한 모든 열의 목록을 만듭니다. 그래서
make a list of all columns that we need inside this table So
16:48:15
우리는 두 개의 열, id와 name이 있습니다. 그리고 그 후에
we have two columns the id and the name And after that
16:48:18
우리는 그 열의 데이터 유형을 정의하고, 아마도 길이를 정의합니다.
we are defining the data type of those columns and maybe as
16:48:21
이 문법에 추가할 수 있는 옵션이 많이 있습니다. 하지만 지금은 테이블을 생성하는 가장 간단한 형태를 확인하고 있습니다.
well the length There are a lot of options that we can add to this syntax But now we are just checking the simplest form of creating a table
16:48:28
이제 다음 단계는 insert 문이 필요하다는 것입니다. 그래서 우리는 새로운 테이블에 다음 값을 삽입한다고 말하고 있습니다.
Now the next step is that we need an insert statement So we are saying insert into our new table the following values
16:48:36
우리는 ID 번호 1과 이름의 값으로 Frank를 삽입하고 있습니다.
We are inserting the ID number one and the value for the name going to be Frank.
16:48:40
이것은 새로운 테이블을 생성하고 데이터를 삽입하는 전통적인 방법입니다. 이제 두 번째 방법인 city AS로 넘어갑시다.
So this is a classical way on creating new table and inserting data to it. Now let's move to the second method, the city AS.
16:48:47
이번에는 select from where와 몇 가지 추가 논리가 있는 SQL 쿼리가 있습니다. 그래서 이것이 우리의 쿼리입니다.
Now this time we have an SQL query like select from where and some extra logic. So this is our query.
16:48:55
그리고 우리는 우리의 쿼리를 DDL 문 안에 넣을 것입니다. 뷰에서 했던 것처럼요.
And then we're going to go and put our query inside a DDL statement. It's like we have done it in the views.
16:49:01
우리가 뷰에서 했던 것과 정확히 같습니다. 하지만 이번에는 view 대신 table이라고 말할 것입니다.
It's exactly like we have done it in the views. But this time, instead of saying view, we're going to say table.
16:49:07
그래서 다시 create 명령이 있고 우리는 테이블을 생성하고, 테이블의 이름을 지정합니다.
So again, we have the create command and we are creating a table, then the name of the table.
16:49:13
그리고 우리는 as라고 말한 후 두 개의 괄호를 가지고, 그 안에 우리의 쿼리가 있습니다. 그리고 이것이 이름이 나오는 곳입니다.
And then we say as and then we have two parentheses. And inside them, we have our query. And this is where the name come from.
16:49:20
Create table as select CTAs. 그래서 매우 간단합니다.
Create table as select CTAs. So it is very simple.
16:49:25
한 문장으로 모든 것을 가집니다. 새로운 테이블을 생성하고 이 쿼리에서 오는 데이터를 삽입하고 있습니다.
In one statement, you have everything. You are creating a new table and as well you are inserting the data that comes from this query.
16:49:34
이 문법은 MySQL, Postgres 및 Oracle과 같은 데이터베이스에서 사용됩니다.
Now this syntax is used in databases like MySQL, Postgres and Oracle.
16:49:39
하지만 MySQL에서는 이를 수행하는 더 짧은 방법이 있습니다. 다시 우리는 쿼리 select from where를 가지고 있습니다.
But in MySQL we have like a shorter way on how to do it. Again we have our query select from where.
16:49:47
하지만 이제 SQL 서버에서는 select와 from 사이에 명령을 삽입할 수 있습니다.
But now in SQL server we can insert a command between the select and from like this.
16:49:53
그래서 우리는 다음 열을 새로운 테이블로 선택한다고 말하고 있습니다.
So we are saying select the following columns into a new table.
16:49:58
그래서 우리는 이 키워드를 사용하여 테이블을 지정합니다.
So we have this keyword into then the table
16:50:01
이름을 지정한 후 쿼리를 계속 진행합니다.
name and then you continue after that with your query from
16:50:04
여기서 집계와 관련된 내용이 ddl처럼 보입니다.
where aggregations and so on so here it's like the ddl
16:50:07
쿼리 자체에 포함되어 있지만 다른 데이터베이스에서는
is inside your query itself but in the other
16:50:10
쿼리가 ddl 문장에서 분리될 수 있습니다. 개인적으로 이 구문을 선호합니다.
databases you can have like the query is separated
16:50:13
쿼리에서 새 테이블을 생성하는 구문입니다. CTAS를 사용하여 다양한 데이터베이스에서.
from the ddl statements personally i prefer this syntax than having this into because if you have like big complex query this can be really hard to see and to miss the column selection
16:50:25
이제 CTAS를 사용할 때의 시나리오와 사용 사례를 확인해 보겠습니다.
So this is the syntax of creating a new table from a query, the CTAS, in different databases.
16:50:34
이제 CTAS를 사용할 때의 시나리오와 사용 사례를 확인해 보겠습니다.
Okay, so now we're gonna check the scenarios and use cases where it makes sense to use CTAS. So let's start with the first one.
16:50:41
복잡한 논리를 데이터베이스에 저장하는 것이 의미가 있습니다.
Now we have learned before it makes sense to have a complex logic stored inside the database so that our end users don't have to keep repeating the same logic
16:50:50
사용자들이 같은 논리를 반복하지 않도록 하기 위해서입니다.
over and over and it's as well maybe complicated for some
16:50:53
그래서 우리는 뷰를 사용했고 그 결과는
users so that's why we have used views and the result of
16:50:56
사용자들이 쉽게 사용할 수 있도록 합니다.
the view can be used from our users so everything can stay
16:51:00
사용자들이 쉽게 사용할 수 있도록 하지만
easy and friendly to consume for our users but
16:51:03
뷰의 논리가 매우 복잡할 수 있습니다.
now what might happen that the logic of the view
16:51:06
데이터베이스에서 실행되는 데 오랜 시간이 걸릴 수 있습니다.
could be very complicated and needs a lot of time
16:51:09
중간 결과를 얻기까지 시간이 걸리므로, 30분이 걸린다면
to be executed from the database so it takes really long time until we get the intermediate results from the database so that means if it takes 30 minutes
16:51:18
각 사용자는 30분을 기다려야 합니다.
then each user has to wait 30 minutes until
16:51:22
쿼리가 실행될 때까지 아무도 행복하지 않을 것입니다.
the query is executed and none of your users gonna be happy
16:51:25
이런 상황이 발생하면 쿼리를 최적화해야 합니다.
with the situation in this scenario if this happens you
16:51:28
최적화할 수 없다면 뷰를 전환해야 합니다.
have to try maybe to optimize the query but if you cannot
16:51:31
CTAS 테이블로 전환해야 합니다. 동일한 논리를 CTAS에 넣어야 합니다.
do anything about that you have to switch the view
16:51:34
중간 결과가 테이블에 저장되도록 합니다.
to a ctas table so now what you have to do you have to take the same logic and then put it in ctas so that the intermediate
16:51:43
테이블을 생성하는 데 30분이 걸릴 것입니다.
results are stored in a table and of course at the moment
16:51:46
같은 쿼리이기 때문에 시간이 오래 걸릴 것입니다.
of creating the table it will take 30 minutes it will
16:51:49
중간 결과를 생성하는 데 시간이 필요합니다.
take long time because it is the same query and the database
16:51:52
하지만 모든 것이 준비되면 큰 장점이 있습니다.
is going to need the time until creating the intermediate
16:51:56
사용자들이 온라인이 되어 데이터를 쿼리할 때 모든 것이 준비되어 있습니다.
results but the big advantage is that once everything is prepared
16:51:59
아마도 밤이나 아침에 사용자가 온라인이 되어 데이터를 쿼리하기 시작할 때 모든 것이 준비되어 있을 것입니다.
maybe at the night at the morning once your users are like online and start querying the data they have everything prepared so the user is going to go and start selecting and analyzing
16:52:11
이번에는 ctis와 응답을 사용하여 중간 결과를 얻습니다.
the intermediate result but this time using the
16:52:14
ctis와 응답을 사용하여 생성한 테이블입니다.
table that you have created from the ctis and the response
16:52:17
모든 사용자에게 다시 정상적이고 빠른 시간이 될 것입니다.
time gonna be for all users again normal and fast
16:52:20
뷰가 매우 느린 시나리오가 있다면,
so if you have a scenario where your views are very slow
16:52:24
ctis를 사용하지 않고 데이터를 준비해야 합니다.
you have to go and prepare the data either not using the ctis and
16:52:28
최종 사용자가 분석할 테이블을 준비해야 하며, 이는 ctis의 가장 일반적인 사용 사례입니다.
prepare the tables to be analyzed from the end users so this is the most common use case for the ctis and this scenario happens a lot in projects where you decide to go instead of views
16:52:39
ctis를 사용하여 처리된 데이터를 얻기 위해 가야 합니다.
to go with the ctis in order to have processed data and
16:52:42
성능을 향상시킬 수 있습니다. 자, 이제 sql로 돌아갑니다.
you gain performance okay so finally back to sql
16:52:45
이제 ctis를 사용하여 테이블을 생성해 보겠습니다.
let's go and create a table using ctis now we're
16:52:49
각 월의 총 주문 수를 보여주는 테이블을 생성할 것입니다.
gonna go and create a table that shows the total number of
16:52:52
주문 날짜에서 월 이름을 얻기 위해 date name을 사용하겠습니다.
orders for each month let's go and do it so first what do we need we need a query so let's write it select i'm gonna go with the date name in order to get the name of the month
16:53:03
주문 날짜에서 월 이름을 얻고 이를 order month라고 부를 것입니다.
from our order dates and we're going to call it order
16:53:07
주문 ID를 세어 데이터를 집계할 것입니다.
month and then we're going to go and aggregate the data by
16:53:11
우리 테이블의 총 주문 수를 세어볼 것입니다.
counting the order id for
16:53:15
우리의 월별로 그룹화하는 것을 잊지 마세요.
total orders from our table
16:53:18
결과는 매우 간단합니다. 주문 월과 총 주문 수가 있습니다.
sales orders and don't forget to group by our month so something like this let's go and execute it
16:53:27
쿼리가 준비되었습니다. 아직 아무것도 생성하지 않았습니다.
So the result is very simple. We have the order month and the total orders. So we have two columns and three rows.
16:53:34
쿼리에서 테이블을 생성하기 위해 from 앞에 write into를 작성할 것입니다.
So we have our query. And of course, we didn't create anything yet. Now in SQL Server, in order to create a table from the query, what we're going to do exactly before the from, we're going to write into.
16:53:46
스키마와 테이블 이름을 지정해야 합니다. 저는 sales 스키마를 사용할 것입니다.
And now we have to specify the schema and the table name. I'm going to stay with the schema sales.
16:53:51
이렇게 월별 주문이라고 부를 것입니다.
And I'm going to call it monthly orders like this.
16:53:56
즉, 쿼리와 DDL은 from과 select 사이에 있습니다.
So that means we have our query and the DDL is exactly between the from and select.
16:54:00
이것을 실행하면 어떤 일이 발생할까요? 쿼리 결과를 여기서 볼 수 없습니다.
So now if I go and execute this, what can happen? We will not see here the result of the query.
16:54:06
여기서 세 개의 행이 영향을 받았다고 표시될 것입니다.
We're going to get here like three rows affected because this is a DDL statement. It is not anymore a query.
16:54:12
데이터베이스가 이제 세 개의 행이 있는 테이블을 생성했다고 알려줍니다.
And the database is telling us I have created now a table with three rows. Now, if you check our tables, we don't see it yet.
16:54:18
가서 새로 고치고 테이블을 다시 확인해 봅시다. 이제 여기에서 우리의 테이블, 월별 판매 주문을 볼 수 있습니다.
Let's go and refresh and check again the tables. Now we can see our table here, sales monthly orders.
16:54:25
이제 물론 모든 것이 괜찮은지 확인해야 합니다.
now of course we have to go and check whether everything is fine so
16:54:28
우리의 새 테이블에서 행을 선택해 봅시다.
let's go and select the rows from our new table
16:54:32
월별 판매 주문
sales monthly orders
16:54:35
먼저 선택해 보겠습니다.
so let's go select
16:54:38
결과를 다시 볼 수 있습니다.
it first and execute and now we can see again
16:54:41
쿼리의 결과를 볼 수 있지만, 여기서 쿼리를 작성하는 것이 아니라 테이블에서 선택하고 있습니다.
the result of our query but we are not writing here the query we are just selecting it from the table so our data is stored in our table and we can go and check the structure of of this table.
16:54:51
열로 가면 주문 월과 총 주문 수가 있습니다. 이 정보는 우리의 쿼리에서 나옵니다.
So if you go to the columns, you can see we have here the order month and the total orders. And those informations comes from our query.
16:54:58
SQL은 여기서 주문 월이
So SQL is saying here the order month is a
16:55:01
varchar라고 말하고 있습니다. 이는 여기에서 이름이 있기 때문입니다.
varchar which is correct because here we have the names of the
16:55:05
월이므로 SQL은 데이터 유형을 정의할 수 있습니다.
month so sql is able to define the data type
16:55:08
쿼리에서 테이블의 두 번째 열은
of the table from our query and the second column the
16:55:11
총 주문 수는 정수입니다. 여기 숫자가 있기 때문입니다.
total orders it is an integer and that's because we have here numbers
16:55:14
보시다시피 SQL은
so as you can see sql is defining the structure of
16:55:17
쿼리 결과를 기반으로 테이블의 구조를 정의하고 있습니다.
the table based on the result of our query
16:55:21
여기에서 테이블의 데이터는 쿼리에서 나옵니다.
over here and of course the data inside the table comes as
16:55:24
쿼리에서 나온 데이터는 이렇게 유지될 수 있습니다.
well from the query and the result of this table can stay like this as
16:55:27
아무것도 변경하지 않는 한, 이걸 닫고
long as you don't change anything so if you go and close this and
16:55:31
1년 후에 열면 정확히 같은 결과가 나올 것입니다.
open it after one year it's gonna show exact same results
16:55:34
테이블을 삭제하지 않는 한 데이터베이스에 남아 있을 것입니다.
so it's gonna live in the database as long as you don't
16:55:37
하지만 테이블 주문에서 변경 사항이 있으면
drop this table but if things change in the table orders
16:55:40
이 테이블은 자동으로 업데이트되지 않습니다.
this table will not be updated automatically like
16:55:43
우리가 뷰에서 배운 것처럼, 이제 내가 이 테이블을 삭제하고 싶다고 말하면
we have learned in the views so now if you want to say you know what i would
16:55:46
테이블을 삭제하라고 말하면 됩니다.
like to go and drop this table well it is very simple just
16:55:50
테이블 이름을 여기에서 선택하고 실행하세요.
go and say drop table and the
16:55:53
여기 테이블 이름을 선택하고 실행하세요
table name over here so make sure you select it and execute
16:55:56
이제 여기로 가서 새로 고침을 해보세요
it and now if you go over here and refresh oh
16:55:59
테이블이 삭제된 것을 확인해보세요
let's check the tables you can see here the table is dropped
16:56:02
그리고
and
16:56:06
이제 당신이 알고 있다고 말하면, 가서 그 테이블을 새로 고치자.
now if you say you know what let's go and refresh that table
16:56:10
매일 ctas에서 오는 것들이니까.
that come from the ctas every day so
16:56:13
그래서 우리는 항상 이 테이블 안에 새로운 데이터를 얻는다.
that we always get a fresh data inside this table so
16:56:16
이제 다시 ctis를 실행해 보자.
now let's go and execute again our ctis and
16:56:19
그렇게 하면 새로 고침을 하면 다시 우리의 테이블을 찾을 수 있을 것이다.
with that if we go and refresh we're gonna find again our table
16:56:22
안에 지금 만약 당신이 한 번 더 실행하면,
inside it now if you go and execute it one more time in
16:56:25
테이블의 데이터를 새로 고치기 위해서 당신이 할 것은
order to refresh the data of the table what you're gonna
16:56:28
오류가 발생할 것이고, 데이터베이스가 이미
get you're gonna get an error the database gonna tell you we have already
16:56:31
이 테이블이 있다고 말할 것이다, 그래서 우리는 그것을 재생성할 수 없다.
this table so we cannot recreate it so now the question is how
16:56:35
그래서 이제 질문은 이 테이블의 내용을 어떻게 업데이트할 수 있는가이다.
we can update the content of this table well we
16:56:38
우리는 먼저 그것을 삭제하고 다시 생성해야 한다.
have to go and drop it first and then recreate it and
16:56:41
모든 것을 하나의 문장에 넣고 싶다면, 우리는 가서
if you want to put everything in one statement we have to go and
16:56:44
tsql을 사용해야 한다. 그것은 트랜잭트 SQL이다.
use the tsql it's transact sql it's
16:56:47
프로그래밍을 할 수 있는 확장과 같다.
like extension where you can do some programming inside
16:56:51
sql 안에서. 그래서 그렇게 하기 위해서, 우리는 여기서 시작할 것이고, f 로직을 만들 것이다.
sql so in order to do that what we're gonna do we're gonna go at the start over here and we're gonna make an f logic so we're gonna go and search for the objects so we're gonna say
16:57:01
그래서 우리는 객체를 검색할 것이다. 그래서 우리는 말할 것이다.
if the object id and now we have to go and specify the
16:57:04
객체 id가 있고, 이제 우리는 이 객체의
name of this object together with the schema make sure to select everything sales monthly order and put it inside here and then we have to define
16:57:13
이름을 스키마와 함께 지정해야 한다. 모든 판매 월별 주문을 선택하고 여기에 넣어야 한다.
the type of this object and here we're gonna go with
16:57:16
그리고 우리는 이 객체의 유형을 정의해야 한다. 여기서는
you it is a user defined table so we
16:57:19
사용자 정의 테이블이다.
are saying if the object sells monthly orders
16:57:22
그래서 우리는 판매 월별 주문이 null이 아니라고 말하고 있다.
is not null so that means
16:57:26
존재하므로 우리가 해야 할 것은
it exists so what you want to do we have to
16:57:29
가서 삭제하는 것입니다. 여기서 문장을 가져오고
go and drop it i'm gonna take the statement from here and
16:57:32
그런 다음 여기 f 뒤에 두겠습니다. 이 테이블이 존재하면 삭제하고 그렇지 않으면 아무것도 하지 않도록 하겠습니다.
then we're gonna put it after the f over here so we are saying if this table exists then drop the table otherwise don't don't do anything because we don't have any new table and the query can work.
16:57:43
TSQL의 끝에서 TSQL이 완료되었다고 말하기 위해 go가 있습니다.
And at the end of the TSQL, we have a go in order to say the TSQL is done and then our usual query after all that.
16:57:51
전체를 실행해 보겠습니다. 보시다시피 작동합니다. 그래서 무슨 일이 발생합니까?
So let's go and execute the whole thing. And as you can see, it is working. So what happens?
16:57:57
데이터베이스가 이 테이블을 찾아 삭제한 후 쿼리를 실행했습니다.
The database did find this table and drop it and then executed our query.
16:58:02
이것을 계속 실행하면 이 테이블의 내용을 새로 고치는 것입니다. 이것이 SQL에서 CTAS를 사용하는 방법입니다.
So if you keep executing this, you are just refreshing the content of this table. So this is how we work with the CTAS in SQL.
16:58:14
좋습니다. 이제 제가 프로젝트에서 자주 사용하는 CTAS의 또 다른 일반적인 사용 사례로 넘어갑니다.
All right, moving on to another common use case for the CTAS that I usually use as well in my projects.
16:58:19
우리는 특정 시간에 데이터의 지속적인 스냅샷을 생성하기 위해 CTAS를 사용합니다.
We use CTAS in order to create a persisted snapshot of the data at specific time in order to analyze data quality issue.
16:58:27
이것이 의미하는 바를 이해해 보겠습니다. 어떤 시나리오에서는 테이블이 있고 문제를 분석하고 있습니다.
So let's understand what this means. Now in some scenarios you have like a table and you are analyzing an issue.
16:58:32
데이터에 데이터 품질 문제가 있고 이 시나리오를 분석하여 왜 발생하는지 이해하고 있습니다.
So there is like a data quality issue at your data and you are analyzing this scenario in order to understand why it happens.
16:58:39
하지만 문제는 동시에 테이블에 업데이트가 있을 것이고 데이터가 변경되고 있다는 것입니다.
But the problem is that at the same time, there will be updates on the table and your data is changing.
16:58:44
어떤 필드에 업데이트가 있을 수 있고 새로운 레코드를 받으면서 모든 것이 뒤섞이고 있습니다.
So there will be updates maybe on some fields or you are getting new records and everything is getting mixed up.
16:58:50
데이터 품질 문제가 발생한 시나리오를 분석할 수 없게 됩니다.
And you will not be able to analyze the scenario where the data quality issue happened.
16:58:55
그래서 이제는 문제의 근본 원인을 찾는 것이 거의 불가능합니다.
So now it's almost impossible to find the root cause of your issue.
16:59:00
하지만 그 대신 데이터에 문제가 있을 경우
But instead of that, what we do if we have like an issue of
16:59:03
고정된 지속적인 스냅샷을 생성합니다.
the data, we go and create a fixed persisted snapshot
16:59:07
변경되지 않도록 하기 위해
of the data in a separate table using ctis
16:59:10
모든 것이 고정되고 이를 통해 분석을 계속할 수 있습니다.
so that we make sure nothing is changing and
16:59:13
같은 데이터에서 데이터가 변경될 걱정 없이
everything is fixed and with that i can keep doing my analysis
16:59:16
이것이 우리가 CTIS를 사용하는 또 다른 이유입니다.
on the same data without the worry that data
16:59:19
프로젝트에서 데이터의 스냅샷을 확보하여 분석이 발생한 동일한 시나리오에서 수행되도록 합니다.
are getting changed so this is another way why we use ctis
16:59:22
문제를 찾고 수정하는 데 사용될 수 있습니다. 알겠습니다,
in projects to make sure that we have snapshot of the data to ensure that our analyzes are done on the same scenario that caused the pack and can be used as a foundation
16:59:33
문제를 찾아서 해결하기 위해서입니다. 알겠죠,
for finding the problem and fixing it. Alright,
16:59:40
CTAS의 또 다른 사용 사례로 넘어가면, 우리는 이를 사용하여 데이터 마트를 생성할 수 있습니다. 가상 데이터 마트 대신 물리적 데이터 마트를 만들기 위해 뷰를 사용할 수 있습니다.
moving on to another use case of the CTAS, we can use it in order to create our data marts to make it physical data marts instead of virtual data marts using views.
16:59:50
이것이 의미하는 바를 이해해 봅시다. 이전에 배운 바와 같이, 데이터 웨어하우스 시스템이 있다면, 데이터 웨어하우스 레이어는 데이터를 테이블에 저장합니다.
So let's understand what this means. Now, as we learned before, if you have a data warehouse system, our data warehouse layer gonna store the data inside tables.
16:59:57
두 번째 레이어에 대해,
But for the second layer,
17:00:00
데이터 마트는 뷰를 사용하여 동적이고 유연하게 여러 데이터 마트를 생성할 수 있습니다.
The data marts, we can go and use views in order to have dynamic and flexibility in order to generate multiple data marts.
17:00:07
우리는 이를 가상 레이어라고 부릅니다. 그러나 어떤 시나리오에서는 상황이 복잡해지면 데이터 마트와 보고서가 느려질 수 있습니다. 왜냐하면 각 작업마다 쿼리를 생성하기 때문입니다.
And we called it the virtual layer. But now in some scenarios, if things get complicated, your data marts and reports can be slow because therefore each action you are generating a query.
17:00:18
Power BI 보고서와 대시보드는 데이터 마트에서 쿼리를 생성하며, 데이터 마트는 항상 데이터 웨어하우스로 가서 보고서에 필요한 데이터를 검색해야 합니다.
So the Power BI reports and dashboards are creating queries on your data marts and your data marts have always to go to the data warehouse in order to retrieve the data for the reports.
17:00:29
이 모든 과정은 몇 분 또는 때로는 몇 시간이 걸릴 수 있습니다.
And the whole thing could take minutes or maybe sometimes hours.
17:00:32
이런 시나리오에서는 뷰를 계속 사용할 수 없습니다. 왜냐하면 모든 것을 느리게 만들기 때문입니다.
So in these scenarios we cannot stay using views because they are slowing everything down.
17:00:37
대신 데이터 마트를 물리적 레이어로 변환해야 합니다.
But instead of that, we have to convert our datamart to a physical layer.
17:00:41
즉, 뷰를 사용하는 대신 테이블을 사용해야 합니다.
That means instead of using views, we have to go and use tables.
17:00:46
데이터 마트의 테이블을 매일 생성하는 일반적인 방법 중 하나는 데이터 웨어하우스 레이어와 데이터 마트 레이어 간에 CTAS 쿼리를 사용하는 것입니다.
And one very common way in order to generate the tables of the datamarts on a daily basis is to use CTAS queries between the data warehouse layer and the datamart layer.
17:00:55
여전히 30분 정도 걸릴 것입니다. 왜냐하면 밤에 데이터를 준비할 수 있지만,
It's still gonna take maybe 30 minutes. why you can go
17:00:58
보고서 레이어에서는 성능이 정말 중요합니다.
and prepare the data at the night but at the reporting layer where
17:01:01
테이블에서의 응답 시간이 훨씬 더 빠르기 때문에 성능이 향상될 것입니다.
things and the performance really matters the performance
17:01:04
뷰보다 빠르며 보고서는 항상 데이터를 가져오는 데 시간을 낭비할 필요가 없습니다.
is gonna be better because the response time from the tables is way
17:01:08
데이터 마트가 데이터를 가져오는 데 시간을 기다릴 필요가 없습니다.
faster than views and the reports don't have always to waste
17:01:11
그래서 이것은 CTAS를 사용하는 또 다른 사례입니다.
time waiting for the data marts to get data from the
17:01:14
데이터 마트가 느릴 때 뷰를 테이블로 교체해야 하는 또 다른 사용 사례입니다.
warehouse so this is another use case where you use ctas where
17:01:18
작업을 빠르게 하기 위해서입니다. 하지만 여전히 제 추천은
the views at the data marts are slow and you have to go and replace them with tables using ctas
17:01:23
먼저 뷰로 시작하여 가상 데이터 마트를 만드는 것입니다.
to speed up things but still my recommendation here is that start
17:01:27
뷰로 시작하여 가상 데이터 마트를 만들어야 합니다.
first with the views so create a virtual data mart using
17:01:30
구현이 매우 동적이고 빠르며, 항상 데이터 웨어하우스에서 신선한 데이터를 가져오기 때문입니다.
views because the implementation can be very dynamic and
17:01:33
하지만 나중에 데이터 마트와
fast and you are always getting fresh data from the warehouse
17:01:36
모델이 복잡하다고 느끼면, 몇몇 마트를 뷰에서 테이블로 교체하는 것이 좋습니다.
but maybe later if you notice okay some data marts and
17:01:39
좋습니다, 친구들. 이제 우리는 데이터베이스에서 영구 테이블이라는 첫 번째 유형의 테이블을 다루었습니다.
models are complex then maybe go and replace few marts from views to tables using ctis so this is another use case for the ctis and it is nice work around for your data warehouse system.
17:01:51
이제 데이터베이스의 또 다른 유형의 테이블, 즉 임시 테이블에 대해 이야기할 것입니다.
All right, friends. So with that, we have covered now the first type of the tables that we have in databases, the permanent tables where you create a table and it's going to live forever until you go and drop it.
17:02:02
이제 데이터베이스의 또 다른 유형의 테이블에 대해 이야기해 보겠습니다. 임시 테이블이 있습니다.
Now we're going to talk about another type of tables in databases. We have that temporary tables.
17:02:07
임시 테이블이 무엇인지 이해해 봅시다. 그래서
So let's understand what are temporary tables. So
17:02:14
임시 테이블, 또는 때때로 단축형으로 템프 테이블이라고 부릅니다.
temporary tables, or sometimes you call them as a shortcut temp tables,
17:02:18
그들은 세션 동안 임시 저장소에 중간 결과를 저장합니다.
they store intermediate results in a temporary storage
17:02:21
데이터베이스에서 세션 동안 데이터베이스가
in the database during a session and the database
17:02:24
세션이 끝난 후 이러한 테이블을 자동으로 삭제합니다.
automatically drop these tables after
17:02:27
이제 이것이 무엇을 의미하는지 이해해 봅시다.
the session ends so let's understand what this means now
17:02:31
우리는 CTIS에서 쿼리를 사용할 수 있다는 것을 배웠습니다.
we have learned in the ctis we could use a query in
17:02:34
하나의 테이블에서 데이터를 검색하기 위해 쿼리를 사용하고,
order to retrieve data from one table and then it puts the
17:02:37
그런 다음 중간 결과를 데이터베이스의 새로운 테이블에 넣습니다.
intermediate results in brand new table in the
17:02:40
그래서 우리는 쿼리를 기반으로 또 다른 테이블을 생성하고 있습니다.
database so with that we are creating another table based
17:02:43
임시 테이블에 대해서도 마찬가지입니다.
on a query the same thing for the temporary tables we
17:02:47
우리는 데이터를 검색하는 쿼리를 가지고 있습니다.
have as well a query that goes and retrieves the data from
17:02:50
테이블에서 데이터를 가져오고, 데이터베이스는
a table and as well the database gonna go and create a
17:02:53
쿼리 결과의 구조와 데이터를 가진 새로운 테이블을 생성합니다.
new brand table in the database that has the structure
17:02:56
그래서 CTIS에서 정확히 무엇이 다른지입니다.
and the data from the result of the query so
17:02:59
테이블의 수명에 관한 것입니다.
it is exactly at the ctis what is the difference here
17:03:02
우리가 CREATE INSERT 또는 CTIS를 사용하여 생성한 데이터베이스 테이블은
well it is about the lifetime of the table now
17:03:05
영구적으로 유지될 수 있습니다.
the database tables that we have created using create insert
17:03:08
그리고 당신이 그것들을 삭제하지 않는 한 데이터베이스에 존재할 것입니다.
or ctis those tables can stay permanent
17:03:11
시스템이 완전히 오프라인 상태여도, 데이터는
and they're gonna live in the database as long as
17:03:15
다시 온라인이 될 때까지 데이터베이스에 남아 있을 수 있습니다.
you don't drop them so even if the system is completely
17:03:18
하지만 임시 테이블은
offline the data can stay in the database once
17:03:21
자동으로 데이터베이스에서 삭제되고 제거될 수 있습니다.
it is online again but the temporary tables can
17:03:24
세션이 끝나면.
get deleted and dropped from the database automatically
17:03:27
세션이 끝나면 자동으로 삭제되고 데이터베이스에서 제거됩니다.
once the session ends so what
17:03:31
세션이 끝나면 무슨 의미인가요?
session means like once you open the client and you connect
17:03:34
클라이언트를 열고 연결하면 세션이 시작됩니다.
to the database and you are start doing queries we
17:03:37
데이터베이스에 연결하고 쿼리를 시작하는 사이의 시간을 우리는
call the time between connecting ourselves to the database and
17:03:40
데이터베이스에 연결하고 끊는 사이의 시간을 우리는
disconnecting from the database we call this a
17:03:43
세션이라고 부릅니다. 즉, 클라이언트를 닫고
session so that means once you close the client and you disconnect from
17:03:46
데이터베이스에서 연결을 끊고 PC를 종료하거나 다른 작업을 하면
the database and maybe shut down your pc and do something else what can
17:03:49
데이터베이스는 모든 임시 테이블을 파괴하고 삭제합니다.
happen the database is going to go and destroy and delete all
17:03:53
세션 동안 생성한 임시 테이블은 세션이 있는 동안만 존재하며
the temporary tables that you have created during the session so that means the table is going to live as long as you have a session and you can access during this time the table as you are accessing any other permanent table.
17:04:04
이 테이블에 접근할 수 있습니다. 이 테이블은 다른 영구 테이블과 마찬가지로 접근할 수 있습니다.
So this is what we mean with temporary tables or sometimes we call it as a shortcut temp tables.
17:04:15
이것이 우리가 임시 테이블이라고 부르는 이유입니다. 때때로 우리는 이를 단축형 임시 테이블이라고 부릅니다.
Okay so now let's check the easiest syntax ever. So for the temporary table the syntax gonna look like this.
17:04:20
이제 가장 쉬운 구문을 확인해 보겠습니다. 임시 테이블의 구문은 다음과 같습니다.
You're gonna have like a query select from where and as we learned in the ctis if you go and say into then the table name it's gonna go and create a physical new table.
17:04:30
쿼리에서 선택하고, 'into' 다음에 테이블 이름을 입력하면
but now if you want it as a temporary table what you're gonna
17:04:33
물리적인 새 테이블이 생성됩니다.
do you're gonna just put hash before the name
17:04:36
임시 테이블로 만들고 싶다면
of the table then isql can understand okay now we are talking
17:04:39
이름 앞에 해시를 붙이면 됩니다.
about temporary table and the database gonna store it
17:04:42
그럼 isql이 이해할 수 있습니다. 이제 임시 테이블에 대해 이야기하고 있습니다.
in that temporary storage so it is very simple this
17:04:45
데이터베이스는 이를 임시 저장소에 저장할 것입니다.
is the syntax of the temporary tables so so far we have learned
17:04:48
이것이 임시 테이블의 구문입니다. 지금까지 우리는
that we have a database called sales db and inside it we can find the tables that we have created the customers employees orders and so on those are our tables and they are always there.
17:04:59
sales db라는 데이터베이스가 있고 그 안에 고객, 직원, 주문 등의 테이블이 있습니다.
Like if you go and close everything and then start it or the next day, you're going to find always those tables with the same data.
17:05:05
이 테이블들은 항상 존재합니다.
So they're going to exist as long as we are not dropping them. Now the question is, where do we find the temporary tables?
17:05:12
모든 것을 닫고 다음 날 다시 시작하면 항상 같은 데이터가 있는 테이블을 찾을 수 있습니다.
Well as we learned, if you go over here at the system databases, you will find multiple databases from the SQL server and normally only the database administrator has an access to this.
17:05:24
우리가 이를 삭제하지 않는 한 계속 존재할 것입니다. 이제 질문은 임시 테이블은 어디에 있나요?
those databases called tempdb temporary database
17:05:27
여기 시스템 데이터베이스를 보면 SQL 서버의 여러 데이터베이스를 찾을 수 있습니다.
so let's go inside it now we can find multiple objects and
17:05:31
일반적으로 데이터베이스 관리자만 이 데이터베이스에 접근할 수 있습니다.
one of them we can find here the temporary tables and
17:05:34
물론 우리는 아무것도 만들지 않았기 때문에 내부에 아무것도 없습니다.
of course we don't have anything inside it because we didn't create anything
17:05:37
그러니 이제 하나를 만들어 봅시다. 이미 열린 세션이 있습니다.
so let's go and create one we have already an open
17:05:40
세션과 SQL 세이버와의 활성 세션에 연결되어 있습니다.
session and active session with the sql saver as you can see here
17:05:43
우리는 데이터베이스에 연결되어 있으며 임시 테이블을 만들기 시작할 수 있습니다.
we are connected to the database and we can start creating temporal
17:05:46
그렇다면 계획이 무엇인지 이제 몇 가지 수정 작업을 하고 싶습니다.
tables so now what is the plan i would like now to do
17:05:49
주문 테이블에서 직접 수정하지 않고 싶습니다.
few modifications on the table orders but i will
17:05:53
판매 데이터베이스에서 복사본을 가져오고 싶습니다.
not do it directly at the table orders i would like
17:05:56
그것으로 임시 테이블을 만들고 싶습니다. 그러니 이제 그 작업을 해봅시다.
to take a copy from the sales db and create from
17:05:59
먼저 필요한 것은 쿼리입니다. 그래서 저는
it a temporary table so let's go and do that what
17:06:02
모든 열과 모든 행을 선택하고 싶습니다.
do we need first we need a query so i
17:06:05
주문 테이블에서 모든 것을 선택하고 싶습니다.
would like to select everything all the columns all the rows
17:06:08
판매 주문 테이블에서 모든 것을 선택하고 싶습니다.
from the table orders so from sales
17:06:11
주문이므로 이것이 내 쿼리입니다.
orders so this is my query
17:06:15
지금까지 아무것도 생성되지 않았습니다. 우리는 오직 선택 문만 있습니다.
now so far nothing is created we have only select statements
17:06:18
하지만 이제 임시 테이블을 만들기 위해서 무엇을 할 것인지 우리는
but now in order to create a temporary table what you're gonna do we're
17:06:21
선택과 from 사이에 문을 넣을 것입니다.
gonna put a statement between the select and from
17:06:25
정확히 from 앞에 가서 여기에서
so exactly before the from go over here and
17:06:28
into라고 말한 다음 임시 테이블이 되도록 하기 위해
say into then in order to make sure it is a temporary
17:06:31
해시를 사용하고 테이블 이름을 지정합니다. 그래서 우리는
table we use hash and then the table name so we're gonna call
17:06:34
주문이라고 부를 것입니다. 그래서 그게 전부입니다. 우리는 우리의 쿼리를 가지고 있습니다.
it orders so that's it we have our query
17:06:37
그리고 그 사이에 우리가 into가 있고 임시 테이블이 되도록 해시를 사용하고 있는지 확인하세요. 그러니 실행해 봅시다. 이제 우리는 2개의 행이 영향을 받았고 오류가 없음을 볼 수 있습니다.
and in between we have that into and make sure you are using hash in order to be a temporary table so let's go and execute it and And now we can see that turn roads are affected and we don't have an error.
17:06:48
그리고 이제 물론 우리는 아직 볼 수 없습니다. 왜냐하면 객체 탐색기를 새로 고쳐야 하기 때문입니다. 그러니 가서 새로 고쳐봅시다.
And now of course we cannot see it yet because we have to go and refresh the object explorer. So let's go and do that.
17:06:54
이제 확장해 봅시다. 이제 우리의 임시 테이블을 볼 수 있습니다.
And now let's expand it. And now we can see our temporary tables.
17:06:58
보시다시피 스키마 DPO에 있습니다. 왜냐하면 우리는 어떤 스키마도 정의하지 않았기 때문입니다. 그리고 이것은 데이터베이스의 기본값입니다.
As you can see it is at the schema DPO because we haven't defined any schema. And this is the default one from the database.
17:07:05
아주 좋습니다. 이제 우리는 테이블을 가지고 있으니 몇 가지를 확인해 봅시다. 그러니 테이블 자체를 선택해 봅시다.
So nice. Now we have the table and let's go and check a few stuff. So let's go and select the table itself.
17:07:10
스타를 선택하고 해시 주문을 말하는 것을 확인하세요. 선택하러 갑시다.
So select star from and make sure to say hash orders. Let's go and select it.
17:07:17
이제 임시 테이블에서 데이터를 가져오고 있습니다. 원래 테이블인 데이터베이스의 주문이 아닙니다.
And now we are getting the data from the temporary table and not from the original table, the orders in the database sales DB.
17:07:25
모든 정보는 임시 테이블에서 나옵니다.
So all those informations comes from the temporary table.
17:07:27
이제 임시 테이블에 대해 원하는 대로 할 수 있습니다. 중요하지 않으니 어차피 삭제될 것입니다.
Now, of course, you can do whatever you want to this temporary table because it's not that important and it's anyway going to get deleted.
17:07:34
주문 상태가 배달 완료인 모든 주문을 삭제하고 싶다고 가정해 보겠습니다. 그렇게 해봅시다.
So let's say that I would like to delete all the orders where the order status equal to delivered. So let's go and do that.
17:07:41
해시 주문에서 삭제할 것입니다.
What we're going to do, delete from our hash orders.
17:07:47
임시 테이블을 선택하고, 주문 상태가 배달 완료라고 말할 것입니다.
So make sure we are selecting the temporary table. And then where are we going to say the order status equal to what I say delivered?
17:07:57
네, 배달 완료입니다. 이렇게 배달 완료로 설정합시다. 실행해봅시다.
Yeah, delivered. So delivered like this. Let's go and execute it.
17:08:02
그렇게 하니 다섯 개의 행이 영향을 받았다고 합니다. 다시 선택해봅시다.
okay with that it says five rows are affected let's go and select it again so select from
17:08:10
주문과 함께
orders and let's
17:08:13
확인해 보겠습니다. 보시다시피 지금 모든 주문이 있는 것은 아니고, 우리는 단지
check that so as you can see now we don't have all orders we have only
17:08:16
상태가 배송됨으로 설정된 주문만 가지고 있습니다. 그래서 모든 배달된
the orders where the status equal to shipped so all delivered
17:08:19
주문은 제거되었고 이제 우리는 원하는 대로 할 수 있습니다.
orders are removed and now we can do whatever we want
17:08:22
이 복사본에 대해 분석할 수 있고, 수정할 수 있으며, 우리는
to this copy we can analyze it we can modify it we can
17:08:26
새 데이터를 삽입할 수 있습니다. 그래서 우리는 이 복사본에서 원하는 모든 조작을 할 수 있습니다.
go and insert a new data so we can do whatever manipulation
17:08:29
이제 당신이 말한다면, '나는 이 결과가 마음에 든다'고, 나는 그것을 세션 중에만 가지고 싶지 않다.
we want on this copy and now if you say you know what i
17:08:32
내일이나 다른 용도로 필요할 수도 있으니,
like these results and i would like to have it not only during
17:08:35
이제 당신이 할 일은 정확히 반대의 작업을 할 것입니다. 우리는 이제
the session maybe i'm gonna need it for tomorrow or something so
17:08:38
임시 테이블의 결과를 다시 저장할 것입니다.
now what you're gonna do we're gonna do the exact opposite we're gonna now store
17:08:41
우리 데이터베이스에, 그래서 이 중간 결과를 잃지 않도록.
the result of the temporary table back to
17:08:44
그렇게 하기 위해 우리는 'INTO'라고 말할 것입니다.
our database so that we don't lose this intermediate
17:08:48
그리고 판매 점을 지정하는 것을 잊지 마세요.
result so in order to do that we're gonna say into
17:08:51
우리는 올바른 스키마를 선택하고 싶으니, 그리고 이제
and then make sure to specify the sales dots
17:08:54
주문이라고 말하고, 나는 그것을 테스트라고 부를 것입니다.
because we want to select the correct schema and then let's say
17:08:57
it is orders and i'm gonna call it test
17:09:01
이렇게 하여 실행해 보겠습니다.
like this so let's go and execute it so it
17:09:04
다섯 개의 행이 영향을 받았다고 합니다.
says five rows are affected now we have to
17:09:07
판매 데이터베이스에서 정보를 확인해야 합니다.
see those informations in the sales db we still don't have this
17:09:10
여기에 테이블이 있으니 데이터베이스를 오른쪽 클릭한 다음 새로 고침하세요.
table over here so right click on the db and then refresh
17:09:13
그럼 다시 테이블로 가서 이제 볼 수 있습니다.
it so let's go again to the tables and now you can see
17:09:16
우리는 새로운 테이블 주문 테스트를 만들었으니 정말 놀랍습니다. 우리가 한 것은 원래 테이블 주문에서 복사한 것입니다.
we have our new table orders test so it is amazing right what we have done is we have took a copy from the original table orders
17:09:25
임시 공간으로 옮겨서 몇 가지 수정 작업을 했습니다.
to a temporary space we have done some
17:09:28
데이터를 가지고 놀고 분석도 했습니다.
modifications and play with the data and we have done some analyzes
17:09:31
그리고 임시 테이블의 최종 결과입니다.
and then the end result of our temporary table
17:09:35
우리는 이를 다시 다른 새로운 테이블인
we have loaded back to another new table called
17:09:38
주문 테스트로 로드했습니다. 아마 다음 날에도 계속 작업할 수 있습니다.
orders test in order maybe in the next day to
17:09:41
그래서 정말 좋은 방법입니다.
keep working on it so it is really nice way to do
17:09:44
임시로 작업하면서 실수를 해도 괜찮다고 말할 수 있는 곳에서 변경 사항을 적용하는 것입니다. 마치 놀이터와 같습니다. 이제 우리는 데이터베이스와 활성 세션을 유지하고 있습니다.
changes in place where you say you know what it is temporary and whatever mistakes you make it's okay it is like playground so now we still have an active session with the database
17:09:54
그리고 우리의 임시 테이블은 항상 여기에 있을 것입니다. 이제 세션을 종료하면 어떤 일이 발생하는지 봅시다.
and our temporary table is going to be always here. Now, let's see what can happen if we end our session.
17:09:59
그래서 그렇게 하려면 모든 것을 닫아보겠습니다.
So in order to do that, let's go and just close everything.
17:10:02
그래서 저는 그냥 닫고 아무것도 저장하지 않을 것입니다. 그렇게 해서 우리는 이제 세션을 종료했습니다.
So I will just close and will not store anything. So with that, we have now ended the session.
17:10:10
다시 시작해보고 임시 테이블이 여전히 있는지 확인해보겠습니다. 이제 다시 SQL 서버에 연결해야 합니다.
Let's go and start it again and see whether we still have the temporary table. So we have now again to connect to the SQL server.
17:10:17
그리고 이제 또 다른 세션이 있습니다. 즉, 이전 세션은 이미 사라졌습니다.
And now we have another session. So that means the old session is already lost.
17:10:22
데이터베이스로 가서 시스템 데이터베이스로 가서 임시 DB로 갑니다. 그리고 임시 테이블로 갑니다.
Let's go to the databases, to the system databases, to the temp DB. And let's go to the temporary tables.
17:10:28
보시다시피 데이터베이스는 이미 모든 것을 정리했습니다.
As you can see, the database already cleaned up everything.
17:10:32
그리고 이 공간은 제가 만들 새로운 임시 테이블을 위해 다시 비어 있습니다.
And this space is again empty for any new temporary table that I'm going to create.
17:10:36
보시다시피 세션을 닫으면 모든 것이 사라집니다. 이제 테이블로 돌아가서 우리의 판매 DB로 가봅시다.
So as you can see, once you close the session, everything going to get lost. Now let's go back to our sales DB over here to the tables.
17:10:43
우리가 만든 주문 테스트 테이블이 여전히 여기 살아있고 우리가 만든 데이터가 여전히 있습니다.
We can see the table that we have created orders tests. It is still living here and still has the data that we have created.
17:10:50
이것이 SQL에서 임시 테이블이 작동하는 방식입니다.
So this is how things works with the temporary tables in SQL.
17:10:57
이제 데이터베이스 서버가 그 임시 SQL을 어떻게 실행했는지 봅시다. 이제 데이터 분석가로서 여러분이 있다고 가정해봅시다.
Now let's see how the database server executed that temporary SQL. So now let's say that you are as a data analyst.
17:11:04
쿼리를 생성한 후 임시 테이블에 저장합니다. 이제 데이터베이스 엔진이 쿼리를 식별할 수 있습니다.
You have created a query and then you say into a temporary table. Now the database engine can identify the query.
17:11:10
먼저 쿼리를 실행할 것입니다. 그리고 나서 그것을 실행할 것입니다.
And first it's going to go and execute the query. And then it's going to go and execute it.
17:11:15
이제 두 가지 일이 발생할 수 있습니다. 첫째, 데이터베이스 엔진이 메타데이터 정보를 시스템 카탈로그에 저장할 것입니다.
And maybe you're going to get the data from the table orders. And after the query is executed, the database engine now has the results.
17:11:22
이제 두 번째로, 데이터베이스 엔진이 테이블을 생성할 것입니다. 하지만 이번에는 사용자 대신 디스크의 임시 저장소에 생성됩니다.
Now, two things can happen. First, the database engine is going to go and store the metadata information in the system catalog.
17:11:29
테이블은 잠시 동안 그곳에 존재할 것입니다. 이제 여러 SQL 쿼리를 작성하여 이 테이블 위에서 여러 분석을 수행할 수 있습니다.
And now the second thing, the database engine is going to create a table, but this time not in the users, but in the temporary storage in the disk.
17:11:37
테이블은 잠시 동안 그곳에 존재할 것입니다. 이제 여러 SQL 쿼리를 작성하여 이 테이블 위에서 여러 분석을 수행할 수 있습니다.
So the table is going to live there for a short time. And now what you can do, you can write multiple SQL queries that are doing maybe multiple analysis on top of this table.
17:11:46
매번 무언가를 선택할 때마다 데이터베이스 엔진은
so each time you select something the database engine has to go
17:11:49
임시 저장소로 가서 데이터를 가져와야 합니다.
to the temporary storage and fetch the data from
17:11:52
그곳에서 이제 작업을 마치고 클라이언트를 종료한다고 가정해 봅시다.
there and now once you are finished and let's say you close your
17:11:55
클라이언트와 데이터베이스 간의 세션이
client the session between you and the database can
17:11:58
끝나고 이제 데이터베이스는 더 이상 연결이 없음을 이해할 수 있습니다.
end and now the database can understand okay there is no
17:12:02
이 사용자에 대한 연결이 더 이상 없음을 이해하고
more connection to this user and it's gonna go and
17:12:05
임시 저장소를 정리하여 이 세션에서 생성된 테이블을 제거합니다.
clean up now the temporary storage with any tables that are created from this session so that means the database is automatically cleaning
17:12:13
다른 세션을 위해 저장소를 정리합니다.
up the storage maybe for other sessions so
17:12:16
이것이 데이터베이스 엔진이 임시 테이블과 함께 작동하는 방식입니다.
this is how the database engine works with the temporary tables so
17:12:24
이제 질문은 왜 임시 테이블이 필요한가입니다.
now the question is why do we need temporary tables let's
17:12:27
다음 시나리오를 살펴보겠습니다. 이제 우리의 소스 데이터베이스에
see the following scenario now let's say that in our source database we
17:12:30
주문이라는 테이블이 있으며, 이제 이를 데이터 웨어하우스에 로드하고 싶습니다.
have a table called orders and now we would like to go and load the
17:12:33
데이터 웨어하우스에서 분석을 위해 데이터를 준비하기 위해 여러 변환을 수행해야 합니다.
table in our data warehouse we have to do several transformations
17:12:37
중복을 제거하는 쿼리와
in order to prepare the data for the analyzes in the data warehouse
17:12:40
널 값을 처리하는 쿼리가 있을 수 있으며, 필터링을 수행할 수도 있습니다.
so maybe you have one query to remove the duplicates and another
17:12:43
정리하고 마지막 단계로 데이터를 집계하고 싶습니다.
one to handle the nulls and maybe you are doing filtering
17:12:46
쿼리와 변환이 테이블 주문의 내용을 변경하고자 합니다.
and cleaning up and the last step you would like to aggregate the data and now of course those queries those transformations
17:12:52
그리고 이를 직접 수행할 수 있는 시나리오는 없습니다.
want to change the content of the table orders
17:12:55
소스 데이터베이스에서 직접 수행할 수 없으며, 이는 허용되지 않습니다.
and there is no scenario where you can do that directly
17:12:59
소스 데이터베이스에서 직접 그렇게 할 수 있는 시나리오는 없습니다.
on the source database and of course this is not allowed that's why in data warehousing we have to go and get our own copy of the data and then on top of this data we can do our transformations
17:13:10
임시 테이블을 사용하여 이를 수행하는 한 가지 방법입니다. 주문 테이블에서 데이터를 추출하고 임시 테이블에 중간 결과로 넣기 위해 스크립트를 하나 작성합니다.
Now one way to do this using the temporary tables. So you have one script in order to extract the data from the table orders and put it in temporary table as an intermediate result.
17:13:20
그런 다음 변환과 모든 쿼리를 작성하여 임시 테이블의 이 추가 복사본의 데이터를 조작하고 변경하기 시작합니다.
And then you come with the transformations and all those queries and they start manipulating and changing the data of this extra copy in the temporary table.
17:13:29
마지막 단계는 로드 단계로, 중간 결과의 최종 버전을 데이터베이스에 로드합니다.
And the last step you have the load where you go and load the final version of the intermediate results in the database.
17:13:36
데이터베이스에 데이터를 삽입하기 전에 전체 ETL을 수행하고 싶다면 이 방법입니다.
This is if you would like to do the whole ETL before inserting the data to the database.
17:13:41
이제 주문 테이블과 데이터 웨어하우스의 최종 테이블은 둘 다 테이블입니다.
So now the orders table and the final table in the data warehouse, both of them are tables.
17:13:46
그래서 이들은 영구 테이블이며 우리가 삭제하지 않는 한 그곳에 남아 있습니다. 그래서 이들은 매우 중요한 테이블입니다.
So they are permanent tables and they will stay there as long as we don't drop them. So they are very important tables.
17:13:52
하지만 이제 중간 결과에 대해서는 그렇게 중요하지 않습니다.
But now for the intermediate results, it is not that important.
17:13:56
이는 데이터를 조작하기 위해 추가 복사본을 갖기 위해 수행한 중간 단계일 뿐입니다.
It is just an intermediate step that we have done in order to have our extra copy of the data to manipulate it and someone in order to prepare
17:14:04
데이터 웨어하우스에 삽입되도록 준비하기 위해서입니다.
it to be inserted in the data warehouse so after we
17:14:07
데이터 웨어하우스에 로드한 이 데이터 복사본은 더 이상 중요하지 않습니다.
loaded it in the data warehouse this copy of the data
17:14:10
오래 남아 있어서는 안 됩니다.
is not any more important it shouldn't stay like for a long
17:14:13
이 시나리오에서는 임시 테이블을 사용할 수 있습니다.
time that's why in this scenario maybe we can go and use
17:14:17
중간 결과에 대해 정상 테이블 대신 임시 테이블을 사용하는 이유는 하나의 이점 때문입니다.
the temporary tables instead of normal tables
17:14:20
데이터베이스가 세션이 끝난 후 자동으로 정리 작업을 수행하기 때문입니다.
for the intermediate results and that's because only of one
17:14:23
즉, 다음 로드를 위해 이 테이블의 삭제 메커니즘을 처리할 필요가 없습니다.
advantage that the database is gonna go and do an
17:14:26
데이터 웨어하우스에 문제가 발생하면 변환이 수행된 복사본을 항상 확인하여 문제를 디버그하고 찾아야 합니다.
automatic cleanup after the whole session ends so it comes out of the box automatically from the database So that means I don't have to deal with the dropping mechanism of this table for the next load.
17:14:37
이러한 시나리오에서는 일반적으로 임시 테이블을 사용하지 않고 일반 테이블만 사용합니다.
If there is like something wrong in the data warehouse, you would like always to check the copy where the transformations are done in order to debug and find issues.
17:14:46
하지만 다른 작은 프로젝트에서는 이 방법이 의미가 있을 수 있습니다.
So I don't normally use temporary tables in these scenarios, I use just normal tables. But for other small projects, maybe this makes sense.
17:14:53
이것은 프로젝트에서 임시 테이블을 사용할 때의 한 가지 사용 사례입니다.
So this is one use case on when to use the temporary tables in your projects.
17:14:58
중간 결과를 임시로 저장하기 위해 사용합니다.
We use it in order to store intermediate results temporary
17:15:01
세션이 끝날 때까지입니다.
until we are done with the session and then once we are
17:15:04
세션이 끝나면 데이터베이스가 그 임시 테이블을 삭제할 수 있습니다.
done the database can go and drop that temporary table
17:15:07
모두
all
17:15:12
좋아요, 여러분 이제 임시 테이블에 대한 간단한 이야기입니다.
right guys now a quick talk about the temporary tables to
17:15:15
솔직히 말해서, 나는 프로젝트에서 이걸 사용하지 않아.
be honest i never use this in my projects if i need
17:15:18
중간 결과가 필요하면 CTE를 사용할 수 있어.
an intermediate results in one query i can go and
17:15:21
자, 여러분, 이제 테이블에 대한 간단한 요약을 해보겠습니다.
use the CTEs and if my intermediate result is very important then I put it in either view or CTEs but it is nice technique to learn maybe you can utilize it in one of your projects
17:15:37
데이터베이스의 테이블은 스프레드시트나 그리드와 같아서
all right guys so now let's have a quick summary about tables tables
17:15:40
열과 행이 있으며 실제 데이터가 저장됩니다.
in database are like spreadsheet or grid that contains
17:15:43
이 테이블에 데이터가 저장되고, 우리는 두 가지 유형의 테이블이 있다는 것을 배웠습니다.
columns and rows and your actual data are stored
17:15:46
영구 테이블과 임시 테이블이 있습니다. 영구 테이블은
in these tables and we have learned there are two types of tables
17:15:49
데이터베이스에 영원히 존재하며 삭제하지 않는 한 계속 남아 있습니다.
we have permanent tables and temporary tables permanent tables
17:15:53
반면에 임시 테이블은
lives in the database forever as long as you don't drop them
17:15:56
짧은 수명을 가지고 있으며 세션이 종료되면 데이터베이스에서 삭제됩니다.
but in the other hand that temporary tables they have
17:15:59
세션을 종료하면 삭제됩니다. 이제 우리는 테이블을 생성하는 두 가지 방법을 배웠습니다.
short lifetime they will be dropped from the database once
17:16:02
데이터베이스에서 테이블을 생성하는 방법에 대해 배웠습니다.
you end the session now we have learned as well there are two methods
17:16:06
첫 번째 방법은 테이블을 정의하고 생성한 후 데이터를 삽입하는 것입니다.
on how to create tables in databases the
17:16:09
그래서 여러분은 처음부터 무언가를 만들고 있습니다. 두 번째 방법은 CTAS라고 부르며,
first method is create inserts this method involves two steps the first one is defining and creating the table and the second step is by inserting the data inside this new table.
17:16:20
쿼리 결과를 기반으로 새로운 테이블을 생성합니다.
So you are creating something from the scratch. And the second method we call it CTAS, it creates as well a brand new table but based on the result of a query.
17:16:30
이 단계는 한 번의 단계로 수행되지만 항상 다른 기존 테이블이 필요합니다.
So this step is done with only one step but it always needs another existing table.
17:16:35
우리는 테이블과 뷰의 차이점도 배웠습니다.
And we have learned as well the difference between tables and views
17:16:38
CTI에서 생성된 테이블을 사용하는 주요 장점은
where the main advantage of using tables created from
17:16:42
사용자 또는 보고 시스템의 성능을 보장하는 것입니다.
ctis is that to ensure the performance is
17:16:45
보고 시스템에서 CTI를 사용합니다.
fast enough at the end of the users or your
17:16:48
뷰의 논리가 매우 복잡하고
reporting system so we use ctis instead of
17:16:51
데이터베이스에서 실행되는 데 시간이 많이 걸립니다.
views if the logic of the view is very complex
17:16:54
CTI의 또 다른 유용한 사용 사례는
and takes a lot of time to be executed in the database and
17:16:57
데이터의 스냅샷을 유지하여
one more nice use case for the ctis is that we can
17:17:01
버그와 데이터 품질 문제를 분석하고 보장하는 것입니다.
go and persist a snapshot of the data in order to
17:17:04
버그와 데이터 품질 문제를 분석하고
analyze a bug and data quality issue and to ensure that
17:17:07
우리가 해결책을 찾기 위해 정확한 데이터를 가지고 있는지 확인합니다.
we have the exact data in order to find a solution for
17:17:10
임시 테이블을 사용하여 중간 결과를 저장할 수 있다는 것을 배웠습니다.
the bug and the issue now we have learned as well that we can use temporary
17:17:13
임시 저장소에 중간 결과를 저장할 수 있습니다.
tables in order to store intermediate results
17:17:16
세션이 끝나면 데이터베이스가 모든 임시 테이블을 자동으로 삭제합니다.
in a temporary storage and the main advantage of the temporary
17:17:20
실제 데이터 프로젝트에서 데이터베이스가 있다면, 많은 분석 사용 사례가 데이터에 접근하여 분석을 수행하고 싶어합니다.
table is the database automatically drops all the temporary tables when the session ends and that's because for you the intermediate results are not that important to live long time
17:17:36
복잡한 쿼리를 작성할 수 있습니다.
Hey my friends, so we have learned that in real data projects, if you have a database, there will be a lot of analytical use cases that want to access your data and do analytics.
17:17:46
프로젝트에서 아무것도 하지 않으면 복잡성과 중복 문제에 직면하게 됩니다.
And what can happen, they can write complex queries because in many scenarios, they are doing complex analyzes.
17:17:52
여러 사용자로부터 복잡한 논리와 성능 문제에 직면할 수 있습니다.
And if you don't do anything about it in your projects, you're going to face a lot of challenges like complexity and a lot of redundancy of the same
17:18:01
보안 문제와 함께 다섯 가지 놀라운 기술을 배웠습니다.
complex logic but from multiple users and maybe performance
17:18:04
이 문제를 해결하기 위한 기술을 배웠습니다.
and security issues and we have learned we have five amazing
17:18:07
서브 쿼리와 CTE를 배웠습니다.
techniques in order to solve those problems we
17:18:11
뷰와 CTAS와 같은 객체를 만드는 방법을 배웠습니다.
have learned the sub queries and cities and as
17:18:14
이제 우리는 그것들을 나란히 비교할 것입니다.
well how to create objects like views ctas
17:18:17
각 방법의 장단점을 비교할 것입니다.
and temporary tables so now what we're gonna do we're gonna go and
17:18:20
저장 유형을 비교하고 싶습니다.
compare them side by side in order to have a big picture about
17:18:23
서브 쿼리와 CTE를 사용할 경우 데이터베이스가 결과를 메모리에 저장할 수 있습니다.
the advantages and the disadvantages of each method so let's go and compare them okay so now we have our five methods and the first criteria that I would like to compare them is the storage type.
17:18:34
주 쿼리가 이러한 중간 결과에 빠르게 접근할 수 있습니다.
We have learned that if you are using sub queries and CTE,
17:18:38
임시 테이블이나 CTE의 테이블을 사용하면 새로 생성된 테이블이 디스크 저장소에 저장될 수 있습니다.
what can happen the database can put the result of those two techniques in the memory in the cache so that later the main query has a fast access to those intermediate results.
17:18:48
뷰는 데이터 저장소가 없으므로 데이터베이스에서 저장소를 사용하지 않습니다.
But in the other hand, if you are using temporary tables or tables from CTE, the new created table can be stored inside the disk storage.
17:18:57
객체가 데이터베이스에서 얼마나 오래 지속될 수 있는지에 대해 이야기하고 있습니다.
And now for the views, as we understood, there will be no data storage. And that means we are not using any storage from the database.
17:19:05
서브 쿼리, CTE 및 임시 테이블은 모두 데이터베이스에서 짧은 시간 동안만 존재합니다.
Now, if you are talking about the lifetime, so that means how long the object can live or persist in the database.
17:19:11
모두 임시입니다. 그러나 이제 CTE와 뷰를 사용하여 객체를 생성하는 것에 대해 이야기하고 있습니다.
Now, our three techniques, subquery, CTE and temporary tables, all of them going to live a short time in the database.
17:19:17
두 개는 영구적이 될 것입니다.
So all of them are temporary. But now we are talking about creating objects using CTE and views.
17:19:24
데이터베이스에서 이러한 객체를 삭제할 때와 비교할 것입니다.
Those two going to be permanent. So that means they're going to live in the database as long as you don't drop them.
17:19:30
이제 우리는 데이터베이스가 이러한 객체를 삭제할 때와 비슷한 것을 비교할 것입니다.
Now we're going to compare them with something similar is when the database is going to go and drop or delete those objects.
17:19:37
서브쿼리와 CTE는 짧은 시간 동안만 존재한다는 것을 배웠습니다.
Now we have learned that the subqueries and the CTEs have a short time.
17:19:41
그들은 쿼리가 실행되는 동안만 존재합니다.
They're going to live only during the execution of the query.
17:19:45
쿼리가 끝나면 데이터베이스는 캐시로 가서 모든 것을 삭제합니다.
So once the query ends, the database is going to go to the cache and delete everything.
17:19:49
임시 테이블은 세션이 있는 동안 조금 더 오래 존재합니다.
But for the temporary tables, they live a little bit longer as long as you are in the session.
17:19:55
하지만 세션을 종료하면 데이터베이스는 테이블을 삭제합니다.
But once you end the session, the database as well gonna go and drop and delete your table.
17:20:00
CTE와 Fuse에서 오는 객체는 영구적이며, 데이터베이스는 DDL 명령어를 사용하여 삭제하라고 요청해야만 삭제할 수 있습니다.
Now for the objects that comes from the CTE and Fuse, as we learned they are persistent and permanent and the database can only delete them if you ask the database to do that by using the DDL command drop.
17:20:12
따라서 데이터베이스는 이 두 객체를 삭제하지 않습니다. 다음은 쿼리 범위입니다.
So the database will not delete anything for these two. So now the next one is the query scope, like how we can access those objects.
17:20:19
서브쿼리와 CTE의 범위는 매우 작습니다.
Now for the subquery and the CTE, the scope is here very small.
17:20:23
하나의 쿼리, 즉 CTE와 서브쿼리를 작성하는 쿼리에서만 접근할 수 있습니다.
It is accessed only from one single query, the query itself where you write the CTE and subquery.
17:20:30
외부 쿼리에서 접근할 수 없습니다.
so you cannot access it from external queries but we
17:20:33
임시 테이블과 뷰는 여러 쿼리에서 접근할 수 있습니다.
have learned that the temporary table ctis and views
17:20:36
즉, 여러 쿼리에서 이러한 객체에 접근할 수 있습니다.
you can access all those objects from multiple queries
17:20:40
여러 외부 쿼리에서 이러한 객체에 접근할 수 있습니다.
so that means you can access those objects from
17:20:43
재사용성을 고려할 때, 서브쿼리는 매우 제한적입니다.
multiple external queries now the next one if you are
17:20:46
서브쿼리는 하나의 쿼리와 한 장소에서만 사용할 수 있습니다.
thinking about the reusability if you look to the sub
17:20:49
따라서 여러 장소에서 필요하면 반복해야 합니다.
queries they are very limited the sub query can be used only in one query and only in one place so if you need it in multiple places you have to go and repeat
17:20:59
서브쿼리는 그들의 사용성 때문에 최악입니다.
the same logic so sub queries are the worst with their
17:21:02
하지만 CTE에 대해 이야기하면 조금 더 나아집니다.
usability but now if you are talking about the cte it is a little
17:21:05
여전히 하나의 쿼리에서만 접근할 수 있습니다.
bit better you still can access it only from one single query
17:21:08
하지만 동일한 쿼리에서 여러 번 접근할 수 있습니다.
but you can access it in the same query from multiple
17:21:12
여러 다른 조인에서 여러 번 접근할 수 있습니다.
places so you can access it multiple times from different joins
17:21:15
그리고 동일한 논리를 반복할 필요가 없습니다.
and you don't have to repeat the same logics over and
17:21:18
하지만 여전히 제한적입니다.
over but still it is limited because you have only
17:21:21
하나의 쿼리만 논리를 사용하고 있습니다.
one query that is using the logic now if you think about
17:21:24
임시 테이블의 재사용성은 중간 정도이며, 여러 쿼리로 데이터를 접근할 수 있지만 이 세션 동안만 가능합니다.
the temporary tables i I could say the reusability here is medium and that's because you can access the data by multiple queries but only during this session.
17:21:35
세션이 끝나면 더 이상 접근할 수 없으므로 다시 사용하려면 재생성해야 합니다.
So once the session is ended, you cannot access it anymore, which means you have to recreate it in order to reuse it again.
17:21:41
CTE와 서브쿼리보다 더 재사용성이 높지만 CTE S&Fuse처럼 좋지는 않습니다.
So it is more reusable than the CTE and the subqueries, but not that good like the CTE S&Fuse.
17:21:48
이 기술들은 여러분에게 가장 높은 재사용성을 제공할 수 있습니다.
Those techniques can offer the highest reusability for you.
17:21:52
여러 사용자와 여러 쿼리를 위해 항상 존재하므로 많은 중복을 제거할 수 있습니다.
So they are always there for multiple users from multiple queries. So it's going to eliminate a lot of redundancies.
17:21:59
작업을 한 번만 하면 됩니다. 이제 다음으로 넘어가겠습니다. 이 기술들의 중간 결과에 대해 생각하고 있다면.
And you have to do the job only once. Now moving into the next one. If you are thinking about the intermediate result of those techniques.
17:22:05
질문은 데이터가 얼마나 신선한가입니다. 이 객체의 데이터는 항상 최신인가요?
The question is how fresh is the data? Is the data from these objects always up to date?
17:22:11
서브쿼리와 CTE는 항상 최신입니다. SQL이 즉시 로직을 실행하기 때문입니다.
Now for the subqueries and the CTEs. They are always up to date. Because the SQL is executing the logic on the fly.
17:22:18
메모리에 데이터를 저장하고 그 직후에
And storing the data in the memory. and immediately after that
17:22:21
주 쿼리가 와서 데이터를 가져오므로 항상 중간 결과가
gonna come the main query and get the data so always the intermediate results
17:22:25
메모리에 최신 상태입니다. 하지만 이제 임시 테이블과 CTE에 대해 생각해보면
in the memory are up to date but now if you think about
17:22:28
쿼리는 한 번만 실행되며, 업데이트가 있을 경우
the temporary tables and the ctis the query is
17:22:31
원본 테이블의 변경 사항을 찾을 수 없습니다.
only executed once and if there is like an update and
17:22:34
이 객체에서 이러한 변경 사항을 찾을 수 없으며, 그 이유는
changes on the original table you will not find
17:22:37
그 객체의 변화는 그렇기 때문입니다.
those changes in those objects and that's because
17:22:40
명확하게 한 번만 실행되며 그게 전부입니다. 그래서 그 테이블을 쿼리하면 데이터가 최신 상태일 것이라는 보장이 없습니다. 그래서 만약
it's clearly executed once and that's all so if you query those tables there is no guarantee that the data are up to date so if
17:22:48
최신 데이터를 원한다면 항상 테이블을 삭제하고
want a fresh data you have always to drop the table and
17:22:51
쿼리에서 다시 생성해야 합니다. 이제 뷰에 대해 이야기하고 있다면
create it again from the query now if you are talking about the views
17:22:54
그들은 놀랍습니다. 항상 최신 상태입니다. 왜냐하면 뷰는
they are amazing they are always up to date because views
17:22:57
어떤 데이터도 저장하지 않기 때문입니다. 그래서 매번 요청할 때마다
does not store any data so each time you ask
17:23:01
데이터를 위한 퓨즈가 발생할 수 있습니다. 데이터베이스는
the fuse for data what can happen the database is going to go to
17:23:04
원본 테이블로 가서 데이터를 뷰로 가져옵니다. 그래서 당신의
the original table and fetch the data to the view so your
17:23:07
데이터는 항상 신선하고 최신 상태입니다. 그래서 이것은 큰
data are always fresh and up to date so this is a big
17:23:10
고급 기술의 동작에 대한 그림입니다. 그 기술은
picture about the behavior of those advanced techniques that
17:23:13
SQL 프로젝트에서 사용할 수 있으며, 제 의견을 묻는다면 제
you can use in SQL projects and if you ask my opinion my
17:23:16
내가 가장 좋아하는 것은 뷰입니다.
favorite is gonna be the views in the first place then
17:23:19
내 목록에서 두 번째는 CTE입니다.
in the second in my list is the CTE they are amazing
17:23:23
하지만 하나의 쿼리에서 다섯 개 이상의 CTE를 사용하지 마세요.
but don't use more than five CTEs in one query otherwise
17:23:26
세 번째는 서브 쿼리와 CTE입니다.
it's gonna be really annoying and hard to read and then I'm gonna say in the
17:23:29
CTE는 뷰가 느릴 때 사용합니다.
third place the sub queries and then the CTEs
17:23:32
이것이 제가 기술을 순위 매기는 방법입니다.
I use CTEs if the views are slow if that's a scenario I'm jump to the CTEs I create a permanent physical tables from my query and the last one that I regularly use is the temporary tables.
17:23:44
이제 제 프로젝트에서 어떻게 작동하는지 큰 그림을 보여드리겠습니다.
So this is how I rank those techniques in my skill projects.
17:23:52
큰 그림과 요약입니다. 이야기를 시작하겠습니다.
Now I would like to show you as well a big picture on how things works in my projects in order to see all those different techniques and possibilities that you can use.
17:24:00
큰 그림과 요약과 같아요. 그래서 이야기 시간입니다.
It's like a big picture and recap. So story time.
17:24:03
데이터베이스가 있고, 데이터베이스 관리자가 있거나 데이터 엔지니어가 처음부터 새 테이블을 만드는 것부터 시작합니다.
So you have a database and things starts where you have a database administrator or let's say a data engineer that is creating a new table from the scratch.
17:24:12
그는 데이터베이스에 물리적 테이블을 만들기 위해 DDL 문을 작성할 것입니다. 이제 우리의 데이터베이스 테이블은 비어 있습니다.
So he gonna write a DDL statement in order to create one physical table at our database. And now our database table is empty.
17:24:19
그래서 두 번째 단계에서는 새로운 테이블에 데이터를 채우기 위해 삽입 문을 작성할 것입니다.
That's why in the second step, he gonna go and write an insert statement in order to fill our new table with data.
17:24:26
이제 테이블이 생겼으니, 데이터 과학자나 데이터 분석가에게 접근 권한을 줄 것입니다. 그들이 SQL 쿼리를 작성하기 시작할 수 있도록요.
Now once we have a table, we gonna give the access maybe to a data scientist or data analyst in order to start writing SQL queries.
17:24:33
그래서 첫 번째로 일어날 수 있는 것은 논리가 복잡해서 그녀가 두 단계로 나누어야 한다는 것입니다.
So now the first thing that could happen is that the logic is complex and she has to do that in two steps.
17:24:39
첫 번째 단계는 두 번째 단계를 실행하기 위해 데이터를 준비하는 쿼리입니다.
So the first step is a query that prepares the data in order to execute the second step.
17:24:44
그래서 그녀는 서브 쿼리를 사용하고, 메인 쿼리는 중간 결과에서 데이터를 검색하여 분석가를 위한 최종 결과를 준비할 것입니다.
So that's why she gonna go and use the sub query and the main query gonna go and retrieve the data from the intermediate results in order to prepare the final results for the analyst.
17:24:54
이제 쿼리에서 SQL 논리가 발생할 수 있는데, 그 논리는 스크립트를 반복하게 됩니다.
Now what could happen is that there will be an SQL logic in the query where it keep repeating the scripts.
17:25:00
그래서 그에 대한 또 다른 서브쿼리를 작성하는 대신, 그녀는 이 논리를 CTE에 넣을 것입니다.
So now instead of writing another subquery for that, she gonna go and put this logic in CTE.
17:25:05
이제 그녀는 메인 쿼리로 가서 같은 쿼리의 여러 곳에서 CTE의 결과를 사용할 것입니다.
And now she gonna go to the main query and use the result of the CTE in multiple places in the same query.
17:25:12
모든 서브쿼리와 CTE 쿼리, 메인 쿼리 등 모든 것이 하나의 쿼리에서 발생합니다.
So all those stuff, the subqueries and the CTE queries, the main queries, all those stuff happens in one single query.
17:25:19
이제 그녀가 멋진 코드를 작성하고 있다면, 그 코드를 그녀의 쿼리에서만 사용하는 대신, 어떤 일이 일어날 수 있을까요?
And now what could happen that she is writing an amazing code. So instead of using it only in her query, what can happen?
17:25:26
그녀는 이 논리를 데이터베이스에 지속할 것입니다.
She's going to go and persist this logic in the database.
17:25:30
그래서 그녀는 데이터베이스에 뷰로 넣어서 다른 모든 사용자와 분석가들이 이 논리를 활용할 수 있도록 하고, 그들이 다시 작성할 필요가 없게 할 것입니다.
So she's going to put it as a view in the database so that all other users and analysts can benefit from this logic and they don't have to write it again.
17:25:38
대신, 그들은 뷰를 쿼리할 것이고, 이것이 그들의 삶을 더 쉽게 만들 수 있습니다.
So instead, they're going to go and query the view and this can make their life easier.
17:25:43
물론, 우리의 데이터 분석가도 메인 쿼리에서 이 뷰를 사용할 수 있습니다.
And of course, our data analyst can as well use this view in the main query.
17:25:47
그리고 이제 한 가지 더, 그녀는 정말 복잡한 또 다른 논리를 가지고 있으며, 모두가 그것으로부터 혜택을 받을 수 있습니다.
And now one more thing, she has as well another logic that is really complex and as well everyone can benefit from it.
17:25:54
하지만 문제는 이 쿼리가 매우 느리다는 것입니다. 그래서 이제 그녀는 뷰에 넣을지, 아니면 ctis를 사용하여 쿼리를 기반으로 새 테이블을 만들지를 결정해야 합니다.
But the issue, this query is very slow. So now she has to decide, do I put it in view or do I create a new table based on the query using ctis?
17:26:03
물론 성능 때문에 뷰를 실행하는 데 약 30분이 걸리므로, 그녀는 ctis를 사용하여 쿼리를 실행하기로 결정했습니다. 그곳에서 물리적 테이블을 생성합니다.
Now, of course, because of the performance and the view takes around 30 minutes to be executed, she decided to execute the query using the ctis where she generate a physical table.
17:26:13
모든 다른 분석가들도 이 새로운 테이블에 접근할 수 있도록 하기 위해서입니다.
so that all other analysts as well can access this new table
17:26:16
결과를 재사용하기 위해서입니다. 그리고 물론
in order to reuse the results and of course
17:26:19
그녀는 그것을 그녀의 주요 쿼리에서 사용할 수 있으며, 이제 우리는
she can use it in her main query and with that now we
17:26:22
실제 프로젝트에서 일이 어떻게 진행되는지 경험하게 됩니다.
have experience how things works in real projects it
17:26:25
단순한 테이블에서 선택 쿼리가 아닙니다. 그것은
is not simple select query from table it is
17:26:28
사람들이 서브 쿼리, ctes, 뷰를 생성하는 것과 같습니다.
like this people are creating sub queries ctes views
17:26:32
임시 테이블, ctas는 다양한 목적을 위해 사용됩니다. 자, 친구들, 그래서 ctas와 임시 테이블에 대한 모든 것입니다. 그리고 그로 인해 우리는 복잡한 프로젝트를 조직하는 방법에 대한 모든 기술을 배웠습니다.
temporary tables ctas for different purposes all right my friends so that's all about the ctas and temporary tables and with that we have learned all the techniques on how to organize our complex projects.
17:26:44
이제 다음으로 우리는 완전히 다른 것에 대해 이야기할 것입니다.
Now next we're going to start talking about something completely different.
17:26:47
우리는 데이터베이스에 코드를 넣는 방법에 대한 저장 프로시저에 대해 이야기할 것입니다.
We're going to talk about the stored procedures on how to put our code inside the database.
17:26:52
이것은 프로그래밍 가능성과 매개변수, 변수, 오류 처리와 같은 것을 추가하는 방법에 관한 모든 것입니다.
This is all about that programmability and how to add stuff like parameters, variables, error handling.
17:26:58
그래서 프로그래밍과 같습니다. 자, 가봅시다. 저장 프로시저의 세계를 밝혀봅시다.
So it's like programming. So let's go. So let's uncover this world of the stored procedures and let's go.
17:27:04
이제 저장 프로시저를 이렇게 생각해 보세요.
Now think about stored procedures like this.
17:27:11
커피숍에 갈 때마다 '나는 원합니다'라고 말합니다.
Every time you go to a coffee shop you say i would like
17:27:14
코코넛 밀크가 들어간 큰 카페, 설탕 없이
a large cafe with a coconut milk no sugar and
17:27:17
추가 휘핑 크림을 원하고, 매번 반복합니다.
extra whipped cream and you repeat this over and
17:27:20
이 커피숍에 갈 때마다, 이제 저장 프로시저로 작업하고 있다면 이렇게 될 것입니다.
over each time you go to this coffee shop and now if
17:27:23
커피숍에 가면 '내가 자주 시키는 걸 주세요'라고 말합니다.
you are working with stored procedures it's gonna be like this whenever you
17:27:26
커피숍에 가서 평소처럼 주문해 주세요라고 말하세요.
go to the coffee shop you just say give me my usual
17:27:30
바리스타는 그 말의 의미를 정확히 알고 있으며, 당신은 모든 것을 한 단어씩 반복하지 않고도 정확한 주문을 받을 수 있습니다. 이것이 저장 프로시저를 사용할 때 발생할 수 있는 일입니다.
and the barista know exactly what you mean behind that and you will get exactly your order without specifying and repeating everything word by word and this is exactly what can happen if you work with stored procedures.
17:27:41
그럼 커피 한 잔 하죠, 그렇죠? 좋아요, 이제 계속할 수 있습니다. 좋아요, 이제 처음부터 다시 시작합시다.
So let's have some coffee, right? All right, so now we can continue. All right, so now let's start again from the scratch.
17:27:48
우리는 항상 이 두 가지 측면이 있습니다. 데이터베이스의 클라이언트 측과 서버 측입니다.
We have always these two sides. We have the client side and the server side of the database.
17:27:52
당신이 배운 것처럼, 우리는 데이터베이스가 있고, 사용자로서 당신은 다양한 SQL 문을 작성할 수 있습니다.
And what you have learned, we have like a database and you as a user, you can go and create like different SQL statements.
17:27:59
예를 들어, SQL 선택문을 만들 수 있습니다.
Like for example, you can create like an SQL select
17:28:03
데이터베이스에서 데이터를 검색하기 위한 SQL 문을 만들 수 있습니다.
statements in order to retrieve data from the database or
17:28:06
데이터베이스에 데이터를 삽입하는 다른 SQL 문을 만들 수 있습니다.
another SQL statements where you are inserting data to
17:28:09
데이터베이스와 다른 업데이트를 하는 SQL 문을 만들 수 있습니다.
the database and another one let's say that you are updating
17:28:13
테이블의 내용을 업데이트하는 등 다양한 SQL 문을 사용할 수 있습니다.
the content of your tables and so on so you have like
17:28:16
이제 데이터베이스와 상호작용하기 위한 다양한 SQL 문이 있습니다.
different statements in order to interact with the database now
17:28:19
이 작업은 한 번만 하는 것이 아니라 반복적으로 수행됩니다.
let's say that's what you are doing is not only one time job you
17:28:22
따라서 매일 매일 삽입, 업데이트, 선택을 반복하게 됩니다.
are keep repeating those steps over and over so you are always like doing an insert then an update and then is select and you keep repeating that
17:28:31
이제 휴가를 가는 것과 같은 미친 상황을 상상해 보세요.
day after day so now imagine that you are doing something crazy where you go on vacation
17:28:36
하지만 작업은 완료되어야 하므로 모든 것을 넘겨줍니다.
but the job should be done so what you do you hand over all those
17:28:39
선택문을 동료에게 넘겨주고 그들이
select statements to your colleagues and they have
17:28:42
당신이 없는 동안 매일 수행해야 합니다.
to do it every day as well as you are gone so you go
17:28:45
모든 SQL 스크립트를 주고 그들에게
and give them all those sql scripts and you tell them
17:28:48
첫 번째 쿼리를 실행한 다음 두 번째 쿼리를 실행해야 한다고 말합니다.
okay you have to execute the first query then the second query
17:28:52
세 번째 쿼리를 실행하는 것은 좋은 방법이 아닙니다.
and then the third query this is of course not a good way
17:28:55
작업을 수행하는 방법에 대한 문제입니다.
on how to do things because of course there will be some
17:28:58
스크립트 실행에서 인간 오류가 발생할 수 있습니다.
human errors where like the execution of the script is
17:29:01
첫 번째로 업데이트한 다음 삽입하는 것이 올바르지 않습니다.
not correct like first updating then inserting and
17:29:04
문제가 발생할 수 있으며, 그래서 우리는
things can go wrong and that's exactly why we
17:29:07
SQL에 저장 프로시저를 사용합니다.
have stored procedures in sql so what we can
17:29:11
모든 SQL 문을 하나의 프레임, 하나의 프로그램에 넣을 수 있습니다.
do we can put all those sql statements together in one frame in one program and we call it stored procedure and now once you do that all your sql statements
17:29:22
저장 프로시저라고 부르며, 그렇게 하면 모든 SQL 문이
will not stay at the client side they will be stored now
17:29:25
클라이언트 측에 남지 않고 이제
in the server side of the database so that means in
17:29:28
데이터베이스의 서버 측에 저장됩니다.
stored procedures we are storing our sql statements
17:29:32
따라서 동료에게 SQL 문을 넘길 필요가 없습니다.
inside the database so you don't have to go and hand over
17:29:35
당신의 SQL 문을 동료에게 전달할 필요가 없습니다.
your sql statements to your colleagues and now all
17:29:38
SQL 문과 상호작용하기 위해 해야 할 일은
what you have to do in order to interact with your sql statements
17:29:41
저장 프로시저를 실행하는 것입니다. 예를 들어 execute sp라는 간단한 명령을 작성합니다.
is to go and execute the stored procedure so you write very simple command called execute sp for example so with that you are calling your stored procedure that is stored inside the server.
17:29:53
이것을 실행하면 어떤 일이 발생할까요?
And once you execute this, what can happen?
17:29:55
데이터베이스가 저장 프로시저로 이동하고
The database is going to go to the stored procedure and
17:29:58
당신이 가진 모든 SQL 문을 실행하기 시작합니다.
start executing all the sql statements that
17:30:02
당신이 정의한 순서대로, 즉 위에서 아래로
you have inside the start procedure and it's going to do it exactly
17:30:05
이제 데이터베이스가 모든 SQL을 처리한 후
in the order that you have defined so from top to
17:30:08
문을 사용자에게 반환할 것입니다.
button so now once the database went through all your sql
17:30:11
우리가 선택한 데이터가 반환됩니다.
statements it's going to return back to the user the
17:30:14
정말 간단하니 동료에게 이렇게 말할 수 있습니다.
data that we have from the selects and with that things
17:30:17
이 시작 프로시저를 실행하면 나머지는
are really easy and you can tell your colleagues okay just execute
17:30:20
데이터베이스에서 수행할 수 있습니다.
this start procedure and the rest can be done from
17:30:24
이로 인해 인적 오류를 최소화할 수 있습니다.
the database so with that you minimize the human errors
17:30:27
모든 것이 원하는 대로 실행될 수 있도록 합니다.
and you make sure that everything can be executed as you wish
17:30:30
휴가에서 돌아온 후 모든 것이 더 쉬워집니다.
and as well as you are back from your vacation things are
17:30:33
저장 프로시저는 여러 SQL 문을 특정 순서로 저장할 수 있습니다.
easier you have to just go and execute the stored procedure so
17:30:36
이제 일반 쿼리와 저장 프로시저를 비교해 보겠습니다.
this is what we mean with stored procedure you can store inside it multiple SQL statements in specific order and you can save it inside the database and each time you need your SQL statements you can go and simply execute them.
17:30:53
일반 SQL 쿼리는 select from where와 같은 것입니다.
So now let's have a quick comparison between a normal query, normal SQL statements compared to a stored procedure.
17:30:59
하나의 요청에 대해 데이터베이스에 요청하는 것입니다.
So a normal SQL query you have like select from where and so on. This is like one time transaction.
17:31:06
저장 프로시저에서는 여러 SQL 문이 있습니다.
You are asking the database for one thing and the database is answering. So it is like one time request.
17:31:12
저장 프로시저를 실행하면 여러 상호작용이 발생합니다.
But now in the other hand, in the stored procedures, you have multiple SQL statements.
17:31:17
즉, 저장 프로시저에서 여러 트랜잭션이 발생합니다.
And once you execute the stored procedure, there will be many interactions with the database in one go.
17:31:22
SQL 쿼리는 간단한 요청과 같습니다.
So that means you will have multiple transactions that is happening in your stored procedure.
17:31:27
반면 저장 프로시저는 프로그램과 같습니다.
So an SQL query, it is like a simple request. You need one thing and you are getting it.
17:31:32
하지만 반면에 저장 프로시저에서는 프로그램과 같습니다.
But on the other hand, in the stored procedure, it is like a program.
17:31:36
프로그래밍 언어로 코드를 작성할 때, 하나 이상의 요청이 필요합니다. 많은 내용이 포함되어 있습니다.
As you are writing a code in any programming languages, it is more than one request. It has a lot of stuff.
17:31:43
예를 들어, 반복 로직을 구축하거나 FL 문과 같은 제어 흐름을 만들 수 있습니다.
Like for example, you can go and build looping logic where we go and iterate through something or you can go and build a control flow where you have a logic like the FL statements.
17:31:53
코드에는 다양한 경로가 있습니다.
So there are like different paths in your codes.
17:31:56
프로그래밍에서는 코드를 동적이고 유연하게 만들기 위해 매개변수와 변수를 사용합니다.
And as well in programming, we have like parameters and variables in order to make our code dynamic and flexible.
17:32:03
또한, 문제가 발생할 경우 어떤 일이 일어날지를 사용자 정의하기 위해 오류 처리를 구축할 수 있습니다.
And as well, we can build error handling on our code in order to customize what can happen if there is like an issue.
17:32:10
저장 프로시저는 예를 들어, 파이썬에서 코드를 갖는 것과 같습니다.
So the stored procedure, it is like having a code, like for example, in Python.
17:32:15
즉, 단순 쿼리에서 하나의 요청만 있는 것과 비교하여 더 복잡한 작업을 수행할 수 있습니다.
So that means you can do more complicated stuff compared to a simple query where you have only like one request.
17:32:22
저장 프로시저에서는 프로그래밍과 코딩을 하며, 단순 쿼리보다 더 고급입니다.
So in the stored procedures, you are doing like programming and coding, and it is more advanced than only just having a query.
17:32:29
저장 프로시저로 작업할 경우, 상황이 더 복잡하고 고급이 될 수 있습니다.
So that means if you are working with stored procedures, things can get more complicated and advanced.
17:32:34
물론, 단순 쿼리와 비교하여 많은 유연성과 재사용성을 얻을 수 있습니다.
But of course, you will get a lot of flexibility and reusability compared to a simple query.
17:32:43
이제 저장 프로시저에 대한 다른 대안이 있습니다.
So now there is like another alternative to stored procedures.
17:32:46
모든 SQL 문을 파이썬 코드에 넣을 수 있으며, 잘 작동할 수 있습니다.
Well, you can go and put all your SQL statements in a Python code and things can work as well.
17:32:52
저장 프로시저 안에 SQL 문을 넣거나 파이썬 코드에 넣을 수 있습니다.
So either you put your SQL statements inside the stored procedure or in a Python code.
17:32:58
하지만 이제 큰 질문은 그들 사이의 차이점은 무엇인가입니다?
But now the big question is what are the differences between them?
17:33:00
서버가 다른 경우 파이썬을 사용하는 단점이 있습니다. 서버와 데이터베이스 서버 간의 연결을 구축해야 합니다.
Well, there is like a disadvantage if you're having Python in different server because you have to go and build a connection between your server and the database server.
17:33:10
연결은 항상 네트워킹을 의미하며, 성능이 약간 저하될 수 있습니다. 이것이 저장 프로시저의 장점 중 하나입니다.
connection means always networking and you might get slightly worse performance. So this is one advantage for the search procedure.
17:33:17
저장 프로시저의 또 다른 장점은 데이터베이스에 저장할 수 있는 모든 스크립트가 미리 컴파일될 수 있다는 것입니다.
Another advantage for search procedure that all the scripts that you can store inside the start procedure in the database can be pre-compiled.
17:33:26
미리 컴파일된다는 것은 SQL 데이터베이스 서버가 알고 있다는 의미입니다.
So pre-compiled means the SQL database servers knows
17:33:29
이미 당신의 SQL 문에 대해 알고 있으며 모든 구문이 올바른지 확인하는 과정이 있었고 데이터베이스도 준비할 수 있습니다.
already about your SQL statements and there was already a check whether all your syntaxes are correct and the database as well can be preparing
17:33:37
저장 프로시저를 실행하기 위해 모든 것을 준비하는 것과 같은 과정입니다.
everything to execute the stored procedure like maybe preparing
17:33:41
실행 계획과 많은 것들을 준비하는 것이므로, 당신의
the execution plans and a lot of stuff so if you store your
17:33:44
기술 문을 데이터베이스의 저장 프로시저 안에 저장하면
skill statements inside stored procedure in the database it
17:33:47
데이터베이스와 매우 가까워지고 데이터베이스는 모든 것을 알고 있습니다.
is very close to the database and the database knows everything
17:33:50
당신의 스크립트에 대해 준비가 되어 있지만
about your scripts and it is ready to execute it but
17:33:53
데이터베이스 외부에 모든 기술 문장을 넣으면
if you put all your skill statements outside of the database of
17:33:57
데이터베이스는 오는 내용을 이해할 수 없으므로
course the database has no chance to understand what is coming so it cannot go and compile anything until python sends the code
17:34:05
데이터베이스로 가는 것이므로 이는 또 다른 장점입니다
to database so this is another advantage for
17:34:08
시작 절차에 대한 것이지만 이제 SQL 문장을 작성하면
the start procedure but now if you build your sql statements
17:34:11
파이썬에서 많은 장점을 얻을 수 있습니다
in python you will get a lot of advantages like
17:34:14
예를 들어 매우 유연한 파이썬 코드를 만들 수 있습니다
for example you can go and build very flexible python codes
17:34:17
여기서 파이썬 기능을 SQL과 함께 사용할 수 있습니다
where you can use python features together with the sql
17:34:21
그렇게 하면 많은 가능성과 유연성의 문이 열립니다
and with that you open the door of many possibilities and flexibility
17:34:24
파이썬을 사용하면 훌륭한 버전 관리를 할 수 있습니다
another thing with python you can make great version control so everything is integrated in python tools and one more advantage of that if you
17:34:33
프로젝트에 복잡한 요구 사항이 있으면 정말 힘들 것입니다
have a complex requirement in your projects it's going to be really hard
17:34:36
저장 프로시저에서 구현하는 것은 많은 코드 라인을 초래할 것입니다
to implement it in stored procedures it's going to cause you a
17:34:39
저장 프로시저에서 구현하는 것은 불편할 것입니다
lot of lines of code and things going to be not comfortable
17:34:42
하지만 복잡한 논리를 파이썬에서 구현하면
but if you are implementing a complex logic in
17:34:45
파이썬으로 복잡한 논리를 쉽게 구현할 수 있습니다
python things can be way easier so with python
17:34:49
저장 프로시저와 비교할 때 매우 쉽게 구현할 수 있습니다
you can implement complex logics very easily compared
17:34:52
저장 프로시저와 파이썬 간의 큰 차이점입니다
to the stored procedure so those are the big differences between the stored procedure and python now i have to be honest with you about
17:34:59
저장 프로시저 또는 파이썬에서 잘하는 것에 대해
having a good in stored procedure or in python well
17:35:02
데이터 프로젝트에서 함께 작업한다면 절대 추천하지 않을 것입니다
if we are working together in a data project i will never recommend
17:35:05
저장 프로시저를 사용하도록
you to use stored procedure if you have the possibility to
17:35:08
파이썬에서 코드를 작성할 수 있는 가능성이 있다면
have your code in python and that's because i saw a lot of
17:35:11
저장 프로시저를 사용하는 프로젝트는 혼란에 빠지기 쉽습니다
projects using stored procedure and most of them ends
17:35:15
디버깅하기 어렵고 테스트하기도 어렵습니다
in chaos it is really hard to debug it is really hard to test it's like catastrophic so really don't use in your
17:35:22
특히 큰 프로젝트와 많은 데이터가 있는 경우
projects and stored procedures especially if you have like a big
17:35:25
모든 것을 완벽하게 관리할 수 있습니다
project and you have a lot of data and tables and so on you
17:35:29
특히 데이터브릭스나 스노우플레이크와 같은 플랫폼이 있다면
can manage everything perfectly using python especially if
17:35:32
데이터브릭스나 스노우플레이크와 같은 플랫폼이 있다면
you have platform like databricks or snowflakes
17:35:35
물론 데이터 프로젝트를 제어하는 가장 좋은 방법은
then of course the best way to control your data projects is
17:35:38
파이썬을 사용하는 것이지만, 만약 이 가능성이 없다면
using python but of course if you don't have this possibility and you have only a database server and you can only work with this then you don't have any other option you have to work with
17:35:47
저장 프로시저를 사용해야 합니다. 하지만 파이썬에
stored procedures but if you have this possibility to put your
17:35:50
프로젝트를 넣고 거기서 스크립트를 실행하는 것이
project inside python and to run your scripts from there then
17:35:54
저장 프로시저를 사용하는 것보다 훨씬 낫습니다. 제
it is way better than having stored procedure well this is my
17:35:57
의견은 대규모 프로젝트에서 작업하는 것입니다.
opinion i'm just talking about working in projects in
17:36:00
작은 프로젝트와 몇 개의 테이블이 있다면
big projects but if you have like small projects few tables
17:36:03
저장 프로시저를 사용하는 것도 괜찮지만 절대
and so on then it's fine to stay with the stored procedure but never
17:36:06
저장 프로시저를 사용하여 대규모 프로젝트를 구축하지 마세요.
build a big project using stored procedures because i tell you it will never work so try to always to think about to have
17:36:14
프로젝트를 실행하기 위해 올바른 플랫폼을 갖는 것이
the right platform in order to run your projects and
17:36:17
중요합니다. 이제 생각해보니 이 팁을
now i'm thinking about it maybe i should have put this tip at the
17:36:20
비디오 끝부분에 넣었어야 했습니다.
end of the video not in the middle so whatever if
17:36:23
여전히 저장 프로시저를 배우고 싶다면
you still want to learn stored procedures we're going to continue on that and i'm
17:36:26
저장 프로시저를 단계별로 구축하는 좋은 예제를
going to have like a really nice example about how to build stored
17:36:30
가져올 것입니다. 미니 프로젝트를 진행하면서
procedures step by step like having a mini projects so
17:36:33
둘 다 배우는 것이 좋습니다. 이제 저장 프로시저의
why not learning both of them so let's go okay so now let's have a quick look to the syntax of the stored procedure
17:36:42
구문을 간단히 살펴보겠습니다.
it is very simple so it has always two parts first we
17:36:45
매우 간단합니다. 항상 두 부분이 있습니다.
have to define the stored procedure so we can do it like this
17:36:48
저장 프로시저를 정의해야 합니다. 이렇게 할 수 있습니다.
create procedure then we have to define the procedure name
17:36:51
프로시저를 생성한 다음 프로시저 이름을 정의해야 합니다.
and then we say as and then we have begin and end it's
17:36:54
그리고 'as'라고 말한 다음 'begin'과 'end'가 있습니다.
very important for sql to understand when that definition starts and
17:36:58
정의가 시작되고 끝나는 시점을 이해하는 것이
when it ends and then between the begin and end we're gonna have a
17:37:01
SQL에 매우 중요합니다. 'begin'과 'end' 사이에
set of sql statements so here you can insert whatever
17:37:04
SQL 문 집합이 있을 것입니다.
you want insert update queries anything and
17:37:07
정렬 절차를 정의한 후 다음 단계는 실행하는 것입니다.
once you have defined the sort procedure the next step is that we're gonna go
17:37:10
구문은 매우 간단합니다. 실행하겠습니다.
and execute it so the syntax is very simple we're gonna say execute
17:37:13
프로시저 이름을 입력하면 됩니다. 그게 전부입니다.
and then the procedure name so that's it with that is going to
17:37:17
정렬 프로시저로 이동하여 모든 SQL 문을 실행하기 시작합니다.
go to the sort procedure and start executing all the sql
17:37:20
정의에 있는 SQL 문입니다. 이것이
statements that you have in the definition so this is
17:37:23
정렬 프로시저의 구문입니다. 매우 간단합니다.
the syntax of the sort procedure as i said it is very simple all
17:37:26
자, 이제 단계별로 진행해 보겠습니다. 첫 번째 단계는
right guys so now let's do it step by step the first step is
17:37:29
쿼리를 작성하는 것입니다. 간단한 작업이 있다고 가정해 보겠습니다.
that we're going to go and write a query so let's say that you have a very simple task
17:37:32
미국 고객의 총 고객 수와 평균 점수를 찾으라고 합니다.
and it says for us customers find the total number of customers and the average score so let's go and do it it's very simple so select count star
17:37:44
총 고객 수와 평균 점수를
total customers and then the average
17:37:47
우리 테이블에서 평균 점수로 가져옵니다.
of scores as average score from our table sales customers
17:37:53
미국 고객을 대상으로 하므로
and then since it says us customers we have to
17:37:56
국가 열을 기준으로 데이터를 필터링해야 합니다.
go and filter the data based on the column country country is equal to usa so that's it this is our query let's go and execute it so we have a very
17:38:05
고객 수와
quick nice report about the total number of customers and
17:38:08
평균 점수를 보고해야 합니다.
the average score so now let's say that i have a weekly meeting
17:38:11
이 쿼리를 여러 번 실행해야 합니다.
and i have to represent this reports over and
17:38:15
주간 페이지에서 데이터를 얻기 위해
over so that means i have to go and execute this query like
17:38:18
보고서를 위해 쿼리를 실행해야 합니다.
frequently in weekly pages in order to get the data
17:38:21
이 쿼리를 저장해야 합니다.
for the reports so now what this means i have to go and
17:38:24
매번 다시 작성하지 않기 위해
save this query in order to use it later now that each
17:38:27
이 텍스트를 어딘가에 저장해야 합니다.
time i have to rewrite it so that means i have to store this text somewhere
17:38:31
쿼리를 여러 번 다시 작성하지 않기 위해
that i don't go and rewrite the query over
17:38:34
전체 쿼리를 복사합니다.
and over so what i usually do let's go and we copy the
17:38:37
새 텍스트를 만들고
whole query and then we create a new text and
17:38:41
주간 쿼리로 설정하겠습니다.
let's say it's going to be my weekly query and
17:38:44
내 주간 쿼리가 될 것이고
it's going to be sql so i'm going to go and edit it
17:38:47
여기서 내 쿼리를 확인할 것입니다
and here i'm going to see if my query and
17:38:50
이 쿼리가 필요할 때마다 복사해야 합니다
each time i need this query i have to go and copy it go
17:38:53
내 SQL로 돌아가서 붙여넣을 것입니다
back to my sql and then i'm going to go and paste it
17:38:56
실행하기 위해서 매번 작성해야 합니다
in order to execute it so either we're gonna write it each time
17:38:59
복사하고 붙여넣을 필요가 없습니다
or copy and paste it well we don't have to do that
17:39:03
저장 프로시저가 있으므로
we have stored procedures so that means we're gonna go
17:39:06
2단계로 가서 이 쿼리를
to the step two where we're gonna turn this query into a
17:39:09
저장 프로시저로 바꿉니다
stored procedure so let's do that it's very simple so we're gonna say
17:39:12
프로시저를 생성해야 합니다
create procedure and now we have to
17:39:15
이름을 지정해야 합니다
go and give it a name so it's gonna be get customer summary
17:39:19
그 다음에 us라고 말해야 합니다
and then after that we're gonna say us and then we need the begin
17:39:22
시작과 끝을 필요로 합니다
and end and in between we're gonna put our
17:39:25
쿼리를 복사해서 넣습니다
query so let's go and copy our query and
17:39:28
그게 전부입니다
just put it in between so that's it let's go
17:39:31
실행하고 저장 프로시저를 생성했습니다
and execute it and with that we have created our
17:39:34
저장 프로시저를 확인하려면
stored procedure and now in order to see our stored procedure
17:39:38
객체 탐색기로 가야 합니다
we can go to the object explorer to our database sales db
17:39:41
여기에서 프로그래머블 폴더가 있습니다
and then here we have a folder called programmability so let's
17:39:44
안으로 들어가면 많은 것들이 있습니다
go inside it and here we have a lot of stuff like functions triggers and we have stored procedures so let's go inside it and we can see over here this is our new created stored procedure
17:39:55
거의 다 왔습니다. 다음 단계는
So we are almost there. The next step is that we're going to go and call our service
17:40:00
서비스를 호출하는 것입니다
and this is the easiest part so it's going to be execute
17:40:03
저장 프로시저의 이름을 적습니다
the stored procedure and the syntax is very simple so execute
17:40:06
고객 요약을 가져옵니다
and then the name of the stored procedure so get
17:40:09
실행하고 결과를 얻습니다
customer summary so let's go
17:40:13
그리고 그것을 실행하면 결과를 얻을 수 있습니다.
and execute it and with that as you can see we get the result
17:40:16
우리의 쿼리 결과를 보시면 매우 간단합니다.
of our query so as you can see it is very simple in
17:40:19
몇 가지 단계로 저장 프로시저를 만들었고, 앞으로는 전체를 필요로 하지 않습니다.
just few steps we created a stored procedure and then in the future you don't need the whole thing you just go and execute the stored procedure i don't have to store the query
17:40:30
이제 저장 프로시저 내부의 매개변수에 대해 이야기해 봅시다. 매개변수란 무엇인가요?
locally at my pc or to copy and paste anything if i want these reports now i just have to execute the stored procedure like this and i will get the results
17:40:44
정보를 전달할 수 있는 자리 표시자와 같습니다.
okay so now let's keep moving now we can talk about the parameters inside stored procedures so So what is a parameter?
17:40:50
저장 프로시저를 실행하는 동안 정보를 전달할 수 있습니다.
It is like a placeholder where you can pass an information
17:40:54
이것이 의미하는 바를 이해해 봅시다. 새로운 작업이 생겼다고 가정해 봅시다.
from you into the stored procedure while running it and using parameters in stored procedure, it's going to make it flexible, reusable and dynamic.
17:41:03
독일 고객을 위해 고객 수와 평균 점수를 찾으라고 합니다.
So let's understand what this means. Let's say that you got a new task.
17:41:07
즉, 미국과 독일을 위한 두 개의 보고서를 생성해야 합니다.
So it says for German customers, find the total number of customers and the average score.
17:41:13
두 보고서 모두 동일한 집계를 수행하고 있습니다.
So that means now we have like to generate two reports, one for USA and one for Germany.
17:41:18
쿼리를 작성하기 시작해야 합니다. 이전 예제와 매우 유사할 것입니다.
in both of them you are doing the same aggregation and again we have
17:41:21
우리가 이전 예제에서 했던 것과 동일한 작업을 하고 있습니다.
to go and start writing the query it's going to be very similar to the
17:41:24
동일한 집계를 수행하지만 여기서 유일한 변화는
one that we have in the previous example so we are doing the same
17:41:27
데이터를 필터링하기 위해 다른 값을 사용할 것입니다.
stuff same aggregations but the only change here is that we're
17:41:30
미국 대신 독일을 사용할 것입니다.
going to use another value to filter the data so instead
17:41:34
여기서 실행해 보겠습니다. 그러면
of usa we're going to go and say here germany so
17:41:37
총 고객 수를 확인할 수 있습니다. 이것이 우리가
let's go and execute this one over here and with that we can see
17:41:40
주간 기준으로 제공해야 하는 보고서입니다.
we have total number of customers too so this is the report that we
17:41:43
복사 및 붙여넣기를 피하기 위해
have to provide like in weekly basis and again in order not
17:41:46
그에 대한 저장 프로시저를 만들 것입니다.
to go and copy paste stuff we're gonna go and create a
17:41:49
이름이 같을 수는 없으니
stored procedure for that at the end we're gonna have an end but
17:41:53
여기서 독일이라고 말할 것입니다. 저장 프로시저를 실행해야 합니다.
now of course we cannot have like the same names we're gonna go and
17:41:56
이렇게 실행해 보겠습니다.
say here germany so let's go and execute it and the next step we have to go and execute the stored procedure so
17:42:04
이제 전체 논리가 데이터베이스에 저장되었습니다.
like this let's go and execute it and
17:42:07
탐색기에서 새로 고침하면 이제 볼 수 있습니다.
the whole logic now stored inside the database let's go
17:42:10
이제 데이터베이스에 저장된 전체 논리로 여기에서 탐색기를 새로 고치면
and refresh on the explorer over here and you can see now
17:42:13
두 개의 저장 프로시저가 있지만 이제 그곳에서 느껴야 합니다
we have two stored procedures but now you have to feel there
17:42:16
프로그래밍과 코딩에는 항상 뭔가 잘못된 것이 있습니다
is something wrong always in programming and coding if
17:42:20
같은 작업을 반복하고 있다면
you find yourself repeating the same task over and over
17:42:23
반복되는 작업을 최적화하는 더 스마트한 방법이 항상 있습니다
then there is always a smarter way on how to
17:42:26
반복되는 작업을 최적화하는 것은 항상 나쁜 일이므로 이제 명확하게 같은 쿼리를 반복하고 있습니다
optimize that repeating stuff encoding is always
17:42:29
두 개의 다른 저장 프로시저에서 쿼리를 반복하고 있으며, 비교하면
bad thing so now clearly we are repeating the same query in
17:42:33
값 때문입니다. 여기에서 필터 값으로 독일과 미국의 값이 있으며, 이 값들은 정적입니다
two different stored procedure and now if you compare them you see
17:42:36
값이므로 항상 저장 프로시저 내에 유지됩니다
it's because of the value so we have here the value for the filter ones germany and one usa and those values are static
17:42:43
미국이지만 대신에 우리는 그것들을 교체할 수 있습니다
value so it's always going to stay inside the stored procedure as
17:42:46
정적 값을 매개변수로 교체하고 나면
usa but instead of that we can replace those
17:42:49
저장 프로시저를 실행할 때 결정할 수 있습니다
static values with a parameter and then you decide
17:42:53
어떤 나라에 대해 저장 프로시저를 실행할지
as you are executing the stored procedure for
17:42:56
그럼 가서 그렇게 해봅시다. 여기에서 모든 것을 제거할 것입니다
which country you want to execute the stored procedure so
17:42:59
이제 첫 번째 저장 프로시저에만 집중하겠습니다
let's go and do that i'm just going to remove everything from here
17:43:02
저장 프로시저의 이름을 준 후에 할 일은
and focus only on the first stored procedure now
17:43:05
매개변수를 정의해야 합니다
what we're going to do after giving a name of our stored
17:43:08
그래서 ads로 시작하고 그것으로 명확하게 이해합니다
procedure we have to define our parameter
17:43:11
이제 매개변수에 대해 이야기하고 있으며, 이제 이름이 필요합니다
so it start with ads and with that is clear understand
17:43:15
매개변수의 이름은 나라일 수 없으며, 어떤 이름이든 될 수 있습니다
aha now we are talking about parameters and we need now the name
17:43:18
원하는 이름을 정하고 나서 SQL을 위해 정의해야 합니다
of the parameter so it cannot be country it could be any
17:43:21
데이터 유형은 테이블을 만들 때 각 열에 대해 정의하는 것과 같습니다
name that you want and after that we have to define for sql the
17:43:25
열을 정의할 때 각 열에 대한 데이터 유형을 할당합니다
data type it's like when you are creating a table and you define
17:43:28
여기에서도 각 매개변수에 대해 데이터 유형을 할당해야 하며, 우리는 var char 데이터 유형을 사용할 것입니다
columns you assign a data type for each column the same
17:43:31
국가의 경우 50자 길이의 링크가 충분합니다.
thing here you have to assign as well a data type for each parameter so we're going to use the data type in var char and for the countries it's enough to have the links of 50.
17:43:40
그래서 우리는 이 세 번째 프로시저에 대해 SQL에 말하고 있습니다.
so with that we are telling sql for this third procedure we
17:43:44
세 번째 프로시저에 정보를 전달할 수 있습니다.
can pass an information to the third procedure and this
17:43:47
정보와 값은 이 매개변수 안에서 사용될 수 있습니다.
information and value can be used inside this parameter
17:43:50
이 매개변수를 정의한 후 우리는
so now after we defined this parameter over here we
17:43:53
쿼리 내에서 어디서든 사용할 수 있습니다.
can go and use it anywhere inside our query
17:43:56
물론 우리는 이 정적 값 대신에 사용하고 싶습니다.
and of course we want to go and use it instead of this static value so now we're going to remove this static value and instead we can have the parameter so now we are
17:44:05
사용자로부터 오는 값에 따라 테이블을 필터링할 것이라고 말하고 있습니다.
saying you're gonna filter the table based on
17:44:08
더 이상 정적이지 않은 값으로 미국과 함께.
the value that comes from the user and not any more static
17:44:11
선택 문에서도 이 매개변수를 사용할 수 있습니다.
with the usa and as i said you can use this parameter everywhere
17:44:15
쿼리 내에서 어디서든 사용할 수 있는 값입니다.
like even here in the select statements so it is a value
17:44:18
우리의 새로운 매개변수를 정의했습니다.
that could be used everywhere in your query so that's it we have defined
17:44:22
새로운 정보로 저장 프로시저를 수정하겠다고 말하고 있습니다.
our new parameter and we have used this parameter in our query so now we have to go and update the stored procedure we cannot leave it as creates instead of that we're going to say alter
17:44:32
이제 실행하러 가야 합니다.
So we are saying alter stored procedure and with the new informations, let's go and execute it.
17:44:37
이제 저장 프로시저가 입력에서 값을 기대하고 있습니다.
And now we have to go and execute it. So now what we're going to do, we're going to say execute get customer summary.
17:44:43
여기서 이름에서 했던 것처럼 할 수 있습니다.
But now our stored procedure is expecting a value from you from the input.
17:44:47
매개변수 country는 독일과 같다고 말할 수 있습니다.
So we can do it exactly like we've done in the name over here.
17:44:50
이 매개변수의 값은 나에게서, 입력에서 온다는 뜻입니다.
So we can say the parameter country is equal to Germany.
17:44:56
이 정보는 내 쿼리와 저장 프로시저로 전달될 수 있습니다.
So that means the value of this parameter come from me, come from the input.
17:45:00
고객의 독일 보고서를 받고 있습니다.
And this information can be passed to my query, to the stored procedure. So let's go and execute it.
17:45:06
이제 미국에 대한 보고서를 생성하자고 말하면 됩니다.
And with that, as you can see, we are getting the report of customers for Germany.
17:45:10
값에서 독일 대신 미국이라고 말할 것입니다.
And now if you say, okay, let's go and generate the report for USA. All what you have to do is replace the parameter.
17:45:17
이제 실행하러 가면 좋습니다.
So in the value instead of Germany, we're going to say USA.
17:45:21
미국 고객에 대한 보고서도 받고 있습니다.
So let's go and execute it great now we are
17:45:24
그 두 보고서에 대해 친구들이 필요합니다.
getting as well the report for us customers so
17:45:27
하나의 저장 프로시저와 매개변수의 도움으로.
that seems my friends for those two reports i just need
17:45:30
하나의 저장 프로시저와 매개변수의 도움으로
one stored procedure and with the help of the parameter i
17:45:33
저장 프로시저를 이제 더 유연하게 만들었습니다
made my stored procedure now more flexible and
17:45:36
전문가가 되었습니다. 이것이 바로 매개변수의 힘입니다.
professional so this is exactly the power of the parameters it
17:45:40
모든 것을 재사용 가능하고 동적으로 만듭니다.
makes everything reusable and dynamic and
17:45:44
물론 독일에 대한 저장 프로시저는 필요하지 않습니다.
now of course we don't need the stored procedure for Germany
17:45:47
우리가 할 수 있는 것은 그것을 삭제하는 것입니다.
so what we can do we can go and drop it so we can say
17:45:50
저장 프로시저를 삭제하고 이렇게 말했습니다.
drop procedure and it was like
17:45:53
이 독일은 필요하지 않습니다.
this Germany so we don't need this
17:45:56
저장 프로시저를 유지하고 하나의 동적 저장 프로시저만 사용할 것입니다.
stored procedure and we're going to stay with only one dynamic stored
17:46:00
이것이 매개변수를 사용하는 방법입니다.
procedure so this is how to use parameters installed procedure
17:46:03
왜 중요한지 알겠습니다. 이제 다음 단계로 넘어갑니다.
and why it's important okay so now to the next step of that we
17:46:06
매개변수에 대한 기본값을 추가할 수 있습니다.
can go and add default values for the parameters
17:46:10
매우 자주 이 보고서를 실행한다고 가정해 보겠습니다.
so let's say that I execute very frequently this report
17:46:13
국가를 미국으로 설정하고 싶지 않습니다.
where I say the country equal to USA and I don't want each
17:46:16
매번 매개변수 값을 미국으로 정의하고 싶지 않습니다.
time to define the parameter value equal to usa so
17:46:20
매우 자주 사용하는 값을 추가할 수 있습니다.
if you are using a value very frequently you can add it
17:46:23
저장 프로시저 정의 내에서 기본값으로 설정할 수 있습니다.
as a default inside the definition of the stored procedure and
17:46:26
매우 간단합니다. 매개변수 뒤에 다시 정의로 가면
it is very simple so if you go to the definition again over here after the parameter and you say equal to usa
17:46:33
국가는 항상 미국이 아닙니다. 사용자가 값을 제공하지 않으면 기본값으로 미국을 사용합니다.
so now it's very important to understand that that
17:46:36
저장 프로시저 정의를 변경합시다.
country will not be always equal to usa it is just you are saying if i don't get from the user any value then as a default i'm gonna go and use the USA.
17:46:46
이제 저장 프로시저로 가서 전체를 건너뛰고 실행할 수 있습니다.
So let's go and again change the definition of our stored procedure using alter.
17:46:51
이제 기본값으로 미국의 보고서를 받고 있습니다.
So execute and now we can go to our stored procedure and again skip the whole thing over here and execute it.
17:46:58
정보를 전달하지 않고도 기본값으로 미국입니다.
So now as a default I'm getting the report of USA without passing an information to the stored procedure because I know it is as a default USA.
17:47:06
독일이 필요하면 정의해야 합니다.
But if you need it as a Germany of course you have to go and define it.
17:47:10
국가가 독일인 저장 프로시저를 실행하라고 말합니다.
So you say execute the stored procedure where the country equal to
17:47:14
독일을 기준으로 저장 프로시저를 실행한다고 하니
germany so if you execute it like this sql still can
17:47:17
입력값을 사용하니, 입력으로 들어오는 값이
use your value so the value that comes as an input
17:47:20
사용자에게 더 우선순위가 있습니다. 기본값으로
from the user has more priority of course as the default
17:47:23
그렇게 해서 우리는 독일 보고서를 받고 있습니다. 보시다시피
and with that we are getting the germany reports so as you can see
17:47:26
매개변수를 사용하는 것이 정말 좋습니다. 모든 소스 프로시저에서
it's really nice right using parameters in source procedure all
17:47:33
다음 단계로 넘어가서 이제 하나의 저장 프로시저 안에서 여러 쿼리를 작업할 수 있습니다. 처음 배운 대로 하나의 저장 프로시저에 여러 SQL 문을 가질 수 있습니다.
right moving on to the next step now we can work with multiple queries inside one stored procedure and this is what we have learned at the start we can have multiple SQL statements in one stored procedure.
17:47:44
이제 새로운 보고서와 쿼리를 생성해야 합니다. 총 주문 수와 총 매출을 찾으라고 합니다.
And now we have a new report and query to generate. It says find the total number of orders and the total sales.
17:47:51
그러니 빨리 해봅시다. 이렇게 작성할 수 있습니다. 계정 주문 ID를 선택합니다.
So let's do it quickly. We can write it like this. Select accounts order ID.
17:47:57
이것이 총 주문 수이며, 그 다음은 매출의 합계, 즉 판매 주문 테이블에서의 총 매출입니다.
This is the total orders and then the sum of sales, total sales from our table sales orders.
17:48:07
물론 우리는 항상 특정 국가를 기준으로 보고서를 생성하므로 고객 테이블과 조인해야 합니다.
And of course, we are always creating a report based on specific country so that means we have to go and join it with that customers table
17:48:15
데이터를 필터링하기 위해 고객
in order to filter the data so on customer
17:48:18
ID가 고객 ID와 같고
id equal to the customer id and
17:48:21
이제 우리는 데이터를 필터링할 것입니다. 국가가
now we're going to go and filter the data so country equal
17:48:25
미국이 되도록 이렇게 해봅시다.
to usa so something like this let's
17:48:29
미국 고객을 위해 이렇게 실행해보면
go and excuse it and with that for the us customers
17:48:32
주문 수는 6개이고 총 매출은 180입니다.
we have six orders and the total sales 180 and
17:48:35
물론 독일에 대해서도 같은 작업을 할 것입니다. 이제
of course the same thing we're gonna do for germany so now of course we
17:48:38
이것을 위해 추가 저장 프로시저를 만들지 않을 것입니다.
will not go and create an extra stored procedure for this we're
17:48:41
모든 것을 하나의 저장 프로시저에 넣을 것입니다. 그러니
gonna go and put everything in one stored procedure so let's
17:48:44
전체를 복사해서 여기에 넣어봅시다.
go and copy the whole thing and put it here inside
17:48:47
첫 번째 보고서 후에 우리는
so after the first report we're gonna
17:48:50
두 번째 보고서를 가질 것이며, 이제 여기서 최선의 방법은
have the second report and now the best practice here if you have
17:48:54
저장 프로시저에서 여러 쿼리가 있을 경우 각 쿼리 끝에 세미콜론을 추가하는 것입니다.
multiple queries in stored procedure go and add at the end of each query a semicolon it is just easier to understand how now this is the end of this query
17:49:03
특히 큰 복잡한 쿼리가 있을 경우
especially if you have like a big complex queries where you have cde
17:49:06
이해하기가 정말 어려울 것입니다.
union and so on it's gonna be really hard to
17:49:09
우리가 지금 완전히 새로운 쿼리에 대해 이야기하고 있다는 것을 이해하세요
understand that we are talking now about completely new query
17:49:13
데이터베이스에서 요구하는 것이 아니라 단순히 읽기 쉬운 것입니다
but it is not like something the database requires it but
17:49:16
각 쿼리 끝에 세미콜론을 추가하세요
it's just easier to read so just add semicolons at
17:49:19
이제 전체를 실행하여 쿼리의 정의를 변경합시다
the end of each query so now let's go and execute the
17:49:22
정적 값이 필요하지 않다는 것을 잊지 마세요
whole thing in order to change the definition of our query and
17:49:26
여기서 멋진 매개변수를 추가할 것입니다
one more thing of course don't forget we don't need static values over
17:49:29
국가를 추가하세요, 그래서 그걸로
here we're gonna go and add our nice parameters so
17:49:33
모든 것이 실행 준비가 되었습니다
add country so i think with that we
17:49:37
저장 프로시저의 정의를 변경합시다
have everything is ready to be executed so let's go
17:49:40
국가가 같을 때 기본값으로 시작합시다
and change the definition of our stored procedure and now let's go
17:49:43
미국으로 설정하고 실행합시다
and start with the defaults where the country equal
17:49:46
결과가 두 개가 나옵니다
to usa so let's go and execute it and now in the output
17:49:49
독일에 대해 저장 프로시저를 실행하면 두 개의 결과가 나옵니다
as you can see we have two results and that's because we have two queries so the first report is for the first query and the second one for the new one that we we just created and the same thing.
17:49:58
여기서 우리는 독일에 대해 네 개의 주문과 200의 총 판매를 볼 수 있습니다
If you go and execute the stored procedure for Germany, we will get as well two results.
17:50:03
이제 여러 SQL 문을 추가할 수 있습니다
And here we can see we have four orders and 200 of total sales for Germany. So as you can see, it's very simple.
17:50:09
삽입, 삭제 등 어떤 종류의 SQL 문도 추가할 수 있습니다
You can go now and add multiple SQL statements, not only queries. You can go and update.
17:50:15
SQL은 위에서 아래로 실행할 수 있습니다
You can do an insert, delete, any kind of SQL statements. You can just go and add it inside your program.
17:50:22
첫 번째 SQL 문이 먼저 실행됩니다
and as usual SQL can execute it from the top to the bottom so
17:50:25
자, 이제 변수에 대해 이야기합시다
since this is the first SQL statement it's going to execute it first and then after that it's going to go to the next one so this is how you can add multiple SQL statements to your stored procedure
17:50:40
변수란 나중에 사용할 값을 저장하는 자리 표시자입니다
all right everyone so now we're going to talk about the variables so what is
17:50:43
저장 프로시저 내에서 사용할 값을 저장합니다
a variable it is like a placeholder where you store inside it a value in order to use it later inside your stored
17:50:49
메모리 내에서 값을 보유하고 재사용할 수 있습니다
procedure so that means variable holds like a value inside
17:50:53
저장 프로시저 내에서 재사용할 수 있지만
the memory and you can reuse it everywhere you want inside
17:50:56
매개변수는 저장 프로시저 외부의 것입니다
your stored procedure but it's not like the parameters parameters
17:50:59
저장 프로시저를 실행하는 사람의 입력입니다
are something like outside the stored procedure it's
17:51:02
저장 프로시저를 실행하는 사람의 입력입니다.
an input from the one that is executing the stored procedure and
17:51:06
제공된 프로시저는 매개변수에 맞춰야 합니다.
the served procedure has to adapt with the parameter but
17:51:09
변수는 저장 프로시저 내부에 존재하며, 개발자가 코드를 동적으로 만들기 위해 사용합니다.
a variable it's something that lives inside the stored procedure and we use it as developers in order to make our code dynamic
17:51:16
값을 한 곳에서 다른 곳으로 이동하기 위해서입니다.
and to move a value from one place to another so let's
17:51:19
매우 간단한 예를 들어보겠습니다. 고객 수에 대한
have a very simple example now let's say that we don't want our
17:51:22
쿼리에서 고객 수에 대한 보고서를 원하지 않습니다.
report here about the total customers as a query so
17:51:25
결과로 원하지 않으니, 제가 생성하고 있는
i don't want it as a result in the output let's say i'm generating
17:51:28
보고서는 항상 이렇게 총 고객 수를 말합니다.
a report always like this we are saying the total customers from
17:51:31
독일에서 고객 수는 2명이고 평균 점수는
germany equal to two and the average score from germany is
17:51:34
425와 같으니, 텍스트로 필요합니다.
equal to 425 so i need it as a text not
17:51:38
여기와 같은 테이블이 아니라, 그렇게 하려면 tskl print를 사용하여 메시지를 전달할 수 있습니다.
as a table like here so in order to do that we can use the tskl print in order to give a message
17:51:44
세 번째 프로시저를 실행한 후, print의 문법은
after executing the third procedure so the syntax of
17:51:47
매우 간단하니, 여기서 print라고 말할 수 있습니다.
print is very simple so we can go over here and say print
17:51:50
따라서 평균 점수에 대해 여기에도 세미콜론을 넣습니다.
and then we have single quotes and let's go and get the whole message from here without the comments and then the semicolon and we can repeat that for the second message
17:52:02
이 메시지는 항상 고정될 수 있으니, 항상
so for the average score and we put it over here as well a semicolon now if you do it like this
17:52:10
총 고객 수와 점수에 대해 2와 같은 값을 가질 것입니다.
this message can be always static so we will have always
17:52:13
데이터가 변경되더라도 항상 이렇게 될 것입니다.
like two for the total customers and our score
17:52:16
따라서 이렇게 고정할 수는 없고, 만들어야 합니다.
gonna always be like this even though that the data is changing
17:52:19
동적이어야 하며, 특히 미국에 대해 이 함수를 호출할 경우.
so we cannot have it static like this we have to make it
17:52:22
여기서 독일로 고정할 수 없으니, 어떻게 할 수 있는지 봅시다.
dynamic and especially if we are calling this function for usa
17:52:26
이것을 동적으로 만들고, 독일 대신 쉽게 시작하겠습니다.
so we cannot have it here as a germany so let's see how we can
17:52:29
매개변수를 올바르게 설정할 수 있습니다.
make this dynamic now let's start with the easy stuff instead of the germany over here we can go and put our parameter right so instead of this
17:52:37
이제 ads country라고 말할 것입니다. 그러나
so we're gonna say ads country but now the
17:52:40
문제는 전체 문자열의 일부라는 것입니다.
problem is it is part of the whole string we cannot do that
17:52:43
따라서 텍스트를 중단하고 색상이 변하는 것을 볼 수 있습니다.
so we're gonna stop the text and you can see the coloring
17:52:46
변경되고 있으며 연결을 위해 더하기가 필요합니다
is changing and then have a plus in order to have concatenations
17:52:50
이 텍스트가 먼저 나오고 그 다음 값이 나옵니다
so this text comes first then the value
17:52:53
국가에서 가져오고 또한 이중 점을 가질 수 있습니다
from the country and then we can have as well the double point
17:52:56
정적 텍스트로서 다시 연결을 하고
as a static text and again a concatenation and
17:53:00
그럼 우리는 나중에 이야기할 두 가지가 있습니다
then we have the two we can talk about later so let's do the same stuff
17:53:03
여기서 우리는 국가를 더한다고 말할 것입니다
over here so we're gonna say plus at country carrying
17:53:07
이 인용문 때문에 변경되지 않으므로 제거하겠습니다
is not changing because of this quote so let me just remove it and
17:53:10
그 후에 다시 정적으로 만들고
then afterwards plus make it static again plus
17:53:14
마지막 인용문을 제거하겠습니다
and remove the final quotes so with that in
17:53:17
우리는 이제 동적 메시지를 가지고 있습니다
the message we have now dynamic where we get the value of the country
17:53:20
매개변수에서 가져오고 이제 흥미로운 부분으로 갑니다
from the parameter and now we come to the interesting part we have here an issue those two values they come from this query and of course we cannot use
17:53:29
그것을 위해 이제 변수를 사용해야 합니다
parameter for that we have to use now the variables now
17:53:32
변수를 만들기 위해 세 단계가 필요합니다
in order to make a variables we have three steps the first
17:53:35
첫 번째 단계는 SQL에 새 변수를 알려주는 것입니다
step is that we have to tell sql about our new variable
17:53:38
SQL이 준비하고 자리 표시자를 만들 수 있도록
so sql can prepare and make like placeholder for
17:53:42
메모리에 그것을 두기 위해
it in the memory so we have to tell skill and prepare it with our
17:53:45
변수 선언을 보통 정렬 절차 시작 시 합니다
new variables now usually we do all the declarations
17:53:48
시작 후에 선언한다고 말할 것입니다
of our variables at the start of the sort procedure immediately
17:53:52
그 후에는 매개변수와 같습니다
after begin so that means we're going to go over here and say declare
17:53:56
매우 간단합니다, 총 고객 수에서
and now after that it's like the parameters it's
17:53:59
이것이 변수의 이름이며 그 후 데이터 정의가 필요합니다
very simple so at total customers so
17:54:02
물론 쿼리에서 데이터 유형을 이해해야 합니다
this is the name of the variable and after that we have to define the data
17:54:05
우리가 count star를 말하고 있으므로 출력은
type of course you have to understand the data type from the query
17:54:08
정수일 수 있습니다, 그래서 이렇게 작성할 것입니다
since we are saying count star then the output
17:54:11
정수이며 평균을 위한 또 다른 것이 필요합니다
can be an integer that's why we're gonna write it like this so
17:54:14
정수이고 이제 평균을 위한 또 다른 변수가 필요합니다.
integer and now we need another one for the average
17:54:18
우리가 할 일은 이제 쉼표를 만들 수 있습니다. 우리는 선언하고 있습니다.
so what we're gonna do we can make a comma now we are declaring
17:54:21
또 다른 변수를 평균 점수로 설정합니다.
another variable so at average score
17:54:24
이 변수의 데이터 유형은 부동 소수점이 될 것입니다. 왜냐하면 우리는
and the data type of this one gonna be float because we
17:54:27
평균을 가지고 있으므로 첫 번째 단계는 이렇게 말하는 것입니다.
have an average so that's it for the first step we are telling
17:54:30
SQL에서 우리는 두 개의 변수를 가지고 있으며, 이는 생성할 것입니다.
sql we have two variables and is going to go and create an
17:54:33
빈 플레이스홀더를 생성합니다. 이제 두 번째 단계에서
empty placeholder so now in the second step we
17:54:37
우리의 변수에 값을 부여해야 합니다. 그래서 우리는
have to give our valuables a value so where we're
17:54:40
값을 가져올 것입니다. 우리는 쿼리에서 가져올 것이므로 이제 시작하겠습니다. 첫 번째 열부터 시작하겠습니다. 여기에서 count star가 있습니다. 오른쪽에 작성하는 모든 것은 열의 별칭이 됩니다.
going to get the values we're going to get it from the query so let's do that now let's start with the first column as you can see we have here the count star and as we learned anything that we write on the right side it's going to be like an alias for the column.
17:54:51
하지만 SQL에서는 그 전에 무언가를 작성하면 변수가 됩니다.
But in SQL, if you go and write something before it, it's going to be the variable.
17:54:56
그래서 우리는 이렇게 할 수 있습니다. 총 고객 수에서
So we can do it like this at total customers
17:55:00
그리고 이제 우리는 어떤 값이든지 이 쿼리가 반환하는 것을 저장해야 합니다.
and then equal so now we are saying whatever
17:55:03
내 새로운 변수에 저장해야 하므로 값을 할당하고 있습니다.
value this query returns it should be stored inside
17:55:06
내 변수에 저장해야 하지만 여기에는 우리가 가질 수 없는 한 가지가 있습니다.
my new variable so that I'm assigning values to
17:55:10
내 변수지만 여기에는 우리가 가질 수 없는 한 가지가 있습니다.
my variable but here there is one thing that we cannot have
17:55:13
더 이상 별칭을 사용할 수 없습니다. 왜냐하면 우리의 쿼리는 결과를 반환하지 않기 때문입니다. 우리의 쿼리는 이제 값을 할당할 단 하나의 작업만 가지고 있습니다.
any more aliases because our query will not return any results our query have now only one task to assign values to
17:55:21
변수이기 때문에 이렇게 할 수 없는 이유입니다. 우리는 제거해야 합니다.
variables so that's why we cannot have it like this we have to remove
17:55:24
별칭을 그리고 평균에 대해서도 같은 작업을 할 것입니다.
the alias and the same thing we're going to do it for the average
17:55:27
그래서 평균 점수는 같고
so at average score equal
17:55:30
평균 점수에 할당해야 하며 별칭을 제거해야 합니다.
to the average score and we have to remove the alias so
17:55:33
이제 우리의 쿼리는 다른 목적을 가지고 있습니다.
that's it now our query having different purpose it
17:55:36
결과를 반환하기 위한 것이 아니라 할당하기 위한 것입니다.
is not for returning result it is to assign
17:55:39
값을 우리의 변수에 할당했으므로 이제 우리는 값을 사용해야 하며, 우리의 변수를 시작 절차 내 어디에서나 사용할 수 있습니다.
values to our variables so now we have values in the next step we have to go and use it and we can use our valuables everywhere inside our start procedure
17:55:48
그래서 출력에 있을 수도 있고 다음 쿼리에 있을 수도 있습니다.
so it could be in the print it could be in the next query so in
17:55:51
어떤 선택 문에서도, 어떤 장소에서든 때때로 우리는 변수를 사용합니다.
any select statements in any place sometimes we use variables
17:55:54
하나의 쿼리에서 정보를 전달하기 위해
in order to pass an information from one query to
17:55:58
다른 쿼리로 하지만 이 예제에서는 변수들을 출력 안에 사용하고 싶습니다. 그래서 매우 간단합니다.
another one but in this example we want to use our variables inside the prints so it is very simple now we're going to go and replace the static number and it's like the parameter we're going to say at
17:56:09
총 고객 수와 평균에 대해서도 같은 방식입니다. 평균 점수는 아주 간단합니다.
total customers and the same thing for the average that's average score so that's it it's very simple
17:56:17
다시 말해, 첫 번째 단계는 그것들을 선언하고 정의하는 것입니다.
so again the step one we have to declare them to define it for
17:56:20
SQL과 함께 우리는 빈 변수를 얻을 것입니다. 두 번째
sql and with that we're going to get an empty variable the second
17:56:23
단계는 그 변수들에 값을 추가해야 합니다.
step we have to add values to those variables and
17:56:27
마지막 단계는 그 변수들을 사용해야 합니다. 그래서
the last step we have to go and use those variables so it makes
17:56:30
지금 확인해보면 모든 것이 동적이며 정적 값이 없다는 것을 알 수 있습니다.
sense right now if you check our message over here you can see
17:56:33
하지만 한 가지 더 있습니다. 출력에서는 모든 것이 문자열이어야 하므로 날짜, 숫자, 부동 소수점이 있을 수 없습니다.
that everything is dynamic and we don't have any static values
17:56:36
그래서 매개변수를 추가하고 있는지 확인해야 합니다.
but there is one more thing that's in the print everything should be as a string so we cannot have dates numbers floats
17:56:43
모든 변수는 문자열이어야 하므로
and so on so that's why you have to make check if you are adding any parameter
17:56:47
국가는 괜찮습니다. 왜냐하면 우리는 varchar 데이터 유형을 가지고 있기 때문입니다.
and variables all of them should be string so the
17:56:50
하지만 총 수와 평균 점수는
country it is okay because we have the data type of varchar
17:56:53
사실 좋지 않습니다. 왜냐하면 서로 다른 데이터 유형을 가지고 있기 때문입니다.
but the total number and the average score this
17:56:56
따라서 이제 그 데이터 유형을 다른 것으로 변환해야 합니다.
is not really good because they have different data type and we have
17:57:00
그래서 우리는 변환하겠다고 말할 것입니다. 여기서 varchar로 변환하겠습니다.
to go and now cast those data types to another
17:57:03
이렇게 말이죠. 자, 이제 준비가 된 것 같습니다. 시작합시다.
one so we're gonna say cast i'm gonna say here as in varchar so that we don't get any errors from sql so cast as well here as in varchar
17:57:15
이렇게 말이죠. 자, 이제 준비가 된 것 같습니다. 시작합시다.
like this all right so i think we are ready let's go
17:57:18
저장 프로시저의 정의를 변경해야 합니다.
and change the definition of our stored procedure in
17:57:21
테스트하기 위해서입니다. 자, 실행해봅시다.
order to test so let's go and execute perfect and now let's
17:57:25
테스트해보겠습니다. 기본값으로 시작하겠습니다.
go and test so let's start with the defaults where we have
17:57:28
매개변수를 usa로 설정했습니다. 이제 보시다시피 하나의 결과를 얻고 있습니다.
the parameter as usa so now as you can see we are getting one
17:57:31
결과는 두 번째 쿼리에서 나온 것입니다. 첫 번째 쿼리는 더 이상 출력에 아무것도 반환하지 않습니다.
result and this is from the second query so the first query
17:57:34
하지만 여기 메시지로 가면 새로운 메시지가 있습니다. 총
is not returning anything anymore in the output but if you go to the messages over here you can see we have a new message it says total
17:57:42
미국의 고객 수는 3명이며
customers from usa is equal to three and
17:57:45
미국의 평균 점수는 825입니다.
the average score from usa is equal to 825
17:57:49
이것이 우리가 보고서에서 원했던 것입니다.
and this is exactly what we wanted for our reports
17:57:52
이제 매개변수를 실행하러 갑시다.
now let's go and execute the parameter equal
17:57:55
독일에 대해 다시 한 번, 우리는 결과가 하나뿐입니다.
to germany again we have only one result and in the
17:57:58
독일의 고객 수는 2명이고 평균 점수는 425입니다.
messages we're gonna get total customers from germany is equal
17:58:01
이것이 우리가 변수를 사용하는 방식입니다.
to two and the average score from germany is equal to 425
17:58:05
정보를 한 곳에 보관하기 위해서입니다.
so this is exactly how we work with the variables we use it
17:58:08
나중에 다른 곳에서 재사용하기 위해서입니다.
in order to hold one information in one place in order
17:58:11
변수에 대한 모든 것입니다.
to reuse it later in different place so that's
17:58:14
모든 변수에 대해
it for variables all
17:58:19
좋습니다, 이제 모두 흐름 제어에 대해 이야기할 것입니다.
right everyone now we're going to talk about how to control the flow in
17:58:22
저장 프로시저에서 이를 수행하는 방법을 배우고, if
your stored procedure and we're going to learn how to do that using the if
17:58:26
else 문을 사용할 것입니다. 이제 다음 시나리오를 살펴보겠습니다.
else statements so now let's have the following scenario now
17:58:29
여기 우리의 쿼리를 확인하면 점수의 평균을 계산하고 있으며, 데이터를 확인하면 점수에
if you check our query over here we are doing the average of score and if you check the data you can see that in the scores we have
17:58:36
null 값이 포함되어 있고 null 값은 집계에 정말 나쁩니다.
nulls and nulls are really bad for aggregations so
17:58:39
그래서 우리는 보통 집계를 하기 전에 데이터를 정리해야 합니다.
we usually have to clean up our data before doing
17:58:42
이 시나리오에서는 null을 0으로 이해할 수 있습니다.
any aggregations and in this scenario we can understand null
17:58:45
데이터를 정리하고 처리하는 방법은
as a zero and how we're going to clean up and handle the data
17:58:48
테이블에서 업데이트를 진행할 것입니다.
we're going to go and make an update on our table where
17:58:52
null이 있으면 0으로 만들라고 말합니다.
we say if there is like a null then make it as a zero and
17:58:55
이 작업을 저장 프로시저 내의 사전 단계로 수행할 것입니다.
we will do this as a pre-step inside our stored procedure so
17:58:59
즉, 먼저 데이터를 정리한 다음
that means first we have to clean up the data and then afterward
17:59:03
보고서를 생성할 것입니다. 이것이 우리가 보통 하는 일입니다.
we're going to generate the reports and this is what we usually do
17:59:06
기술 프로젝트 내에서 논리는 매우
inside skill projects so the logic can be very
17:59:09
간단할 수 있습니다. 먼저 null 값이 있는지 확인해야 합니다.
simple we have to check first do we have nulls inside the
17:59:12
점수가 null인지 먼저 확인해야 합니다. 답이 예라면 업데이트해야 합니다.
score if the answer is yes then we have to go and update
17:59:15
null 값을 0으로 업데이트해야 하지만, 답이 아니면
the null values to zero but if the answer is no
17:59:18
값이 없으니 모든 것을 건너뛰어야 합니다. 이제
we don't have any values then we can skip everything so now
17:59:21
이 논리를 저장 프로시저 안에 구축하여 데이터를 정리하고 준비할 것입니다. 자, 이제 이 부분을 보고서 생성이라고 부를 것입니다.
we're going to go and build this logic inside our stored procedure in order to clean up and prepare the data so let's go okay so now this part we're going to call it generating reports
17:59:34
이제 FL 문장의 구조를 먼저 준비합시다. 구문은 이렇게 보일 것입니다.
And we're going to have another part called prepare and clean up data.
17:59:40
그래서 if와 then, begin과 end가 있습니다.
So now let's prepare first the structure of the FL statements. So the syntax is going to look like this.
17:59:45
그래서 시작하고 끝납니다.
So if and then begin and end.
17:59:48
그래서 이것은 F의 블록이고 else에 대해서도 같은 작업을 할 것입니다. 그래서 우리는 else가 있고 시작과 끝이 있습니다.
So this is the block of the F and we're going to do the same thing for the else. So we have else and we have begin and end.
17:59:55
그들을 분리해 보겠습니다. 이제 이것이 어떻게 작동하는지, 우리는 조건을 만들어야 합니다.
Let me just separate them. So now how this works, we have to create a condition.
18:00:00
조건이 충족되면 F 문이 실행될 수 있습니다.
If the condition is met, then the F statement can be executed.
18:00:03
하지만 조건이 충족되지 않고 false가 되면 else 문이 실행될 수 있습니다. 그럼 조건은 무엇인가요?
But if the condition is not fulfilled and we have false, then the else statement can be executed. So what is the condition?
18:00:10
우리는 점수 안에 null이 있는지 확인해야 합니다. 그래서 아주 간단한 쿼리를 작성해 보겠습니다.
We have to check whether there is null inside the scores. So let's write a very simple query.
18:00:15
이 쿼리는 sales customers에서 score가 null인 것을 선택하라고 할 것입니다.
It's going to say select one from sales customers where score is null.
18:00:25
그리고 항상 country가 USA와 같아야 한다고 확인해야 합니다. 그래서 여기에서 이 쿼리를 실행해 보겠습니다.
And always we have to check that country equal to let's say USA. So let's go and execute this one over here.
18:00:32
그래서 이제 출력에서 결과를 얻고 있습니다. 결과가 있다면 어딘가에 null이 있다는 의미입니다.
So now we are getting in the output a result. If we are getting a result, that means somewhere there are nulls.
18:00:38
하지만 예를 들어 독일을 입력하고 같은 쿼리를 실행하면 출력에서 결과가 없음을 알 수 있습니다.
But if you go, for example, and say here Germany and execute the same query in the output, you see that we don't have any results.
18:00:45
그것은 독일 고객의 점수에 null이 없다는 것을 의미합니다.
That means for the German customers, we don't have any nulls in their scores.
18:00:50
그래서 이 쿼리가 무언가를 반환하면 null이 있습니다. 아무것도 반환하지 않으면 null이 없습니다.
So if this query returns something, we have nulls. If it didn't return anything, then there is no nulls.
18:00:56
그리고 우리는 정확히 이 쿼리를 조건으로 사용할 것입니다.
And we're going to use exactly this query as a condition.
18:01:00
그래서 우리는 우리의 체크를 가져와서 exists가 있으면 두 개의 괄호를 넣고 우리의 쿼리를 넣습니다.
So we can take our check and say if exists and then two parentheses and then we put our query.
18:01:06
당신이 말하는 것은, exists가 있으면 이 쿼리가 무언가를 반환하면 다음 블록을 실행하라는 것입니다.
So what you are saying, if exists, if this query return anything, then go and execute the next block.
18:01:12
그리고 존재하지 않으면 아무것도 반환하지 않는다는 의미이므로 두 번째 블록을 실행하라는 것입니다.
And if it is not exist, that means it is not returning anything, then go and execute the second block.
18:01:18
그래서 이건 논리입니다, 맞죠? 매우 간단합니다. 이제 물론 여기에서 정적 값을 사용하는 대신 매개변수를 사용할 수 있습니다.
So it's a logic, right? It's very simple. Now, of course, instead of having a static value for here, we can use our parameter.
18:01:24
그래서 country에서, 이제 SQL에게 존재하는 경우 무엇을 해야 하는지 알려줘야 합니다.
So at country, and now we have to tell SQL what to do if it exists.
18:01:30
그래서 그 사이에 업데이트 문이 있을 수 있습니다. 그래서 sales customers를 업데이트합니다.
So in between, we can have like an update statement. So updates sales customers.
18:01:36
그리고 우리는 점수를 0으로 설정할 것입니다. 매우 중요합니다. 우리는 조건을 사용해야 합니다.
And we're going to set the score equal to zero. That's very important. We have to go and use where condition.
18:01:42
그렇지 않으면 모든 것을 업데이트하게 됩니다. 점수가 null입니다.
Otherwise, it's going to go and update everything. The score is null.
18:01:48
그리고 국가를 우리의 매개변수 국가로 설정합니다.
And the country equal to our parameter country.
18:01:52
그래서 우리는 특정 국가의 null을 정확히 업데이트하고 있습니다. 마지막에 세미콜론을 추가합시다.
So with that, we are updating exactly the nulls for specific country. And let's have a semicolon at the end.
18:01:58
그리고 시작할 때 좋은 메시지를 출력하겠다고 말할 것입니다.
and at the start maybe i'm gonna say just to have a nice message
18:02:01
출력에서 메시지를 업데이트할 것입니다.
in the output print and we're gonna have a message updating
18:02:05
null 점수를 0으로 설정합니다.
null scores to zero
18:02:08
그리고 마지막에 세미콜론을 추가합니다. 만약
and as well a semicolon at the end so if there is
18:02:11
null이 있다면 전체를 실행하고 메시지를 출력합니다.
any nulls then execute the whole thing print the
18:02:14
메시지를 출력하고 테이블을 업데이트합니다. 이제 다음 단계는 우리가 가야 할 것입니다.
message and update the table so now the next step is that we're gonna go and
18:02:18
SQL이 조건이 충족되지 않았을 때 발생할 수 있는 일을 알려줍니다. 즉, null이 없습니다.
tell sql what can happen if the condition is not fulfilled that means we don't have any nulls well we don't have to update the table at all because we don't have
18:02:26
그래서 테이블을 업데이트할 필요가 없습니다.
clean up anything but i'm gonna go and make prints over
18:02:29
아무것도 정리하지 않겠지만, 출력을 만들 것입니다.
here so prints and we're gonna give the message
18:02:32
여기서 출력을 하고 메시지를 전달할 것입니다.
no null scores found
18:02:35
null 점수를 찾지 못했습니다.
and at the last end i'm gonna go and put
18:02:39
마지막에 세미콜론을 추가할 것입니다. 이게 우리의 논리입니다.
a semicolon so that's it this is our logic we
18:02:42
우리는 조건을 확인하고, 조건이 충족되면 실행합니다.
are checking our condition and then we execute if
18:02:45
조건이 충족되면 테이블을 0으로 업데이트합니다.
the condition is met where we update the table with zero
18:02:48
null 대신에. 조건이 충족되지 않으면 아무것도 하지 않고 메시지를 출력합니다.
instead of null and if the condition is not met then don't do anything just print a message now you might say you know what why you are doing this we just can use this
18:02:56
왜 이렇게 하는지 물어볼 수 있습니다. 우리는 그냥
update statements and we don't need the whole if else statements so
18:02:59
업데이트 문을 사용할 수 있습니다. 전체 if else 문이 필요하지 않습니다.
why we are checking in the first place i can like each time i run this stored
18:03:02
왜 처음에 확인하는지 매번 이 저장 프로시저를 실행할 때
procedure i go and update all the nulls if they exist
18:03:05
존재하는 모든 null을 0으로 업데이트합니다.
to a zero well this is not really professional because
18:03:09
이것은 정말 전문적이지 않습니다.
you are wasting resources so each time you run an
18:03:12
자원을 낭비하고 있습니다.
update statement like this so imagine that you have a big
18:03:15
테이블이 있고, 저장 프로시저 SQL을 실행할 때마다 널 값이 있는지 확인해야 합니다. 이는 물론
table and each time you run your stored procedure sql have to go and check whether there is any nulls and so on and this is of course
18:03:22
리소스를 소모하므로, 정말 필요한지 먼저 확인하는 것이 훨씬 좋습니다.
consume resources it's way better if you go and check
18:03:25
그래서 현재 이 로직을 구현하고 있습니다. 보시다시피, 저장 프로시저가 점점 커지고 있습니다.
first whether it's really needed so that's why we are doing this logic now as you can see our stored procedure is getting bigger and bigger
18:03:32
그래서 두 부분이 있습니다. 첫 번째 부분은
so we have like two parts the first part is
18:03:35
데이터를 준비하고 정리하는 것이고, 두 번째 부분은
preparing and cleaning up the data and the second part
18:03:39
보고서를 생성하는 것입니다. 이제 전체를 업데이트하고 실행해 보겠습니다.
we are generating reports let's go and update the
18:03:42
단계별로 진행해야 하므로, 여기서 쿼리를 확인해 보겠습니다. 여기 널 값이 있습니다.
whole thing and execute it and now we have to do it step by step so let's check our query over here and you can see we have here null
18:03:49
미국 고객을 위해 먼저 실행해 보겠습니다.
for usa customers so let's go first executed
18:03:52
미국을 기본으로 하고, 이제 메시지를 확인해 보겠습니다.
for the usa as a default and now let's go and check the
18:03:55
메시지에서 널 점수를 업데이트하고 있다고 합니다.
messages it's saying updating null scores
18:03:58
0으로, 이는 첫 번째 블록이 실행되었음을 의미합니다.
to zero that means the first block is executed because
18:04:02
SQL이 널 값이 있는 고객을 찾았기 때문에
sql did find a customer with a null and
18:04:05
그로 인해 평균 점수가 이전과 다를 수 있습니다.
with that the average of scores can be different than
18:04:09
현재 더 정확한 평균을 가지고 있습니다.
previously so we have now more accurate average
18:04:12
보고서에서 쿼리를 다시 확인하면
in our reports so if you go and check our query again
18:04:15
이제 널 대신 0이 있음을 알 수 있습니다.
you can see now we have a zero instead of null let's
18:04:18
이제 독일에 대해 이렇게 실행해 보겠습니다.
go and execute it for germany like this and let's
18:04:21
메시지를 확인해 보니 널 점수가 발견되지 않았다고 합니다.
go and check the messages it says no null scores found
18:04:25
그리고 이는 맞습니다. 독일에는 널 값이 없기 때문입니다.
and that is correct because for germany we don't have
18:04:28
그래서 이를 통해 제어 흐름을 생성했습니다.
any nulls so with that we have created a control
18:04:31
FL 문을 사용하여, 이제 더 이상 단순 쿼리를 수행하지 않고
flow using the fl statements and as you can see we are
18:04:34
미니 프로그램을 만들고 있습니다. 이제 ETL처럼 데이터 준비 후
not doing any more like simple queries we are creating like a mini program and now it's like an etl where first we prepare the data and
18:04:42
보고서를 생성하는 것입니다. 실제 프로젝트에서 이러한 정렬 프로시저가 얼마나 커질지 상상할 수 있습니다.
second we generate reports and you can imagine a real project how big those sort procedures gonna get where you have a lot of tables and a lot of things to do.
18:04:55
이제 저장 프로시저에서 오류 처리에 대해 이야기해 보겠습니다.
Okay, so now we're gonna talk about that error handling in start procedure.
18:04:59
오류 처리는 프로그래밍 중 필수적인 작업으로, 오류가 발생했을 때 어떤 일이 일어날 수 있는지를 제어할 수 있습니다.
Your handling it is like essential things to do while programming because it gives you the control on what can happen once you have an error.
18:05:07
프로그래밍 중 오류가 발생했을 때 어떤 일이 일어날지 제어할 수 있게 해줍니다.
And there is a lot of things that you can do, like maybe deleting data, printing a very structured message, or maybe doing some logging and so on.
18:05:15
오류가 발생했을 때 무엇을 해야 할지 완전히 제어할 수 있습니다. 물론, 우리는 시작 절차에서 이를 수행할 수 있습니다.
So you have a full control on what to do if there is an error. And of course, we can do that in the start procedure.
18:05:20
이제 구문을 빠르게 확인해 보겠습니다. 일반적으로 두 부분으로 나뉩니다. 첫 번째 부분은 시도 부분입니다.
So now let's check quickly the syntax. It usually has two parts. The first part is the try part.
18:05:26
구문은 다음과 같습니다. 시작, 시도, 종료, 시도입니다. 그래서 시도의 경계를 정의하고 있습니다.
So the syntax is like this, begin, try, end, try. So you are defining the boundaries of the try.
18:05:33
그 사이에 모든 SQL 문과 코드를 넣을 수 있습니다. 두 번째 부분은 캐치 부분이 될 것입니다.
And in between, you can have all your SQL statements and your code. And the second part is going to be the catch part.
18:05:39
시작 캐치와 종료 캐치를 말합니다. 그래서 경계를 정의하고 있습니다.
So you say begin catch and end catch. So you are defining the boundaries.
18:05:44
그 사이에 SQL이 오류가 발생했을 때 무엇을 해야 할지 말할 수 있습니다. 시도와 캐치란 무엇인가요?
And then in between, you can tell SQL what to do if there is like an error. So what is try and catch?
18:05:49
단어가 말하는 것처럼, 시도는 실패할 수 있는 무언가를 시도하는 것입니다.
Like the word it says, try it's like you attempt to do something that might fail.
18:05:54
SQL에게 이 코드를 실행해 보라고 말하고 있습니다. SQL은 당신의 코드를 실행하려고 시도할 것입니다.
So you are telling SQL, try to execute this code. So the SQL gonna go and try to execute your codes.
18:06:00
코드를 실행하는 동안 오류가 발생하면 SQL은 두 번째 블록으로 점프하여 캐치에서 정의한 대로 작업을 시작합니다.
And if any error happens while executing your codes, the SQL gonna jump to the second block and start doing whatever you have defined in the catch.
18:06:09
오류가 전혀 없다면 이 부분은 실행되지 않습니다. 그래서 캐치는 백업 계획과 같습니다.
But if there is no errors at all, this part will not be executed. So the catch is like your backup plan.
18:06:16
여기서 뭔가 잘못되면 계획 B로 가서 무언가를 해야 합니다. 이제 시도와 캐치의 워크플로를 살펴보겠습니다.
If something goes wrong here, then go to the plan B and do something. So let's see the workflow of the try catch.
18:06:22
먼저 SQL이 시도를 실행할 것입니다.
so first the sql gonna go and execute the try and
18:06:25
그런 다음 오류가 있는지 확인할 것입니다. 오류가 없다면
then it's gonna check is there any error if we don't have any
18:06:28
모든 것이 끝나고 그게 전부입니다. 그러나 실행 중에 SQL이 오류에 직면하면 캐치를 실행할 것입니다.
error then everything ends and that's it but while
18:06:31
SQL이 오류에 직면했을 때 발생할 수 있는 일입니다. 캐치를 실행할 것입니다. 워크플로는 매우 간단합니다.
execution if the sql face an error what can happen it gonna go and execute the catch so as you can see the workflow is very simple and this is what we mean with try and catch so let's go back to sql to have some example
18:06:44
좋습니다. 이제 시작 절차로 돌아가서 코드 안에 오류를 도입해 보겠습니다.
all right so now back to our start procedure let's go and introduce an error inside our code
18:06:49
여기에서 쿼리를 살펴보겠습니다.
so let's go over here and maybe in our query
18:06:52
우리는 0으로 나누려고 할 것입니다. 이는 물론
we're gonna go and divide by zero which is of course
18:06:55
문제가 됩니다. 그래서 여기에서 오류가 발생하고
a problem so we have this error over here and let's
18:06:58
저장 프로시저의 논리를 업데이트하겠습니다.
go and update the logic of our stored
18:07:02
이제 실행하면 오류가 발생할 것입니다. '0으로 나눌 수 없습니다'라는 오류가 발생합니다.
procedure and now if you go and execute it so
18:07:05
하지만 이제 제가 하고 싶은 것은 오류가 발생할 때 사용자 정의 메시지를 갖는 것입니다.
let's go and do that we will get an error saying yeah you cannot divide
18:07:09
어떤 정보가 표시되어야 하는지 제어하고 싶습니다.
by zero but now what i would like to do i would like to have something else where we have customized message when error happens so i would like to have the control on which information
18:07:17
문제가 발생할 경우 표시되어야 하며, 이를 위해 시도와 캐치를 사용해야 합니다.
should be displayed if there is an issue and in order to do that we
18:07:20
문제가 있을 경우 표시되어야 하며 이를 위해
have to use that try and catch so it's going to be very simple
18:07:23
전체 코드를 보여주기 위해
now this is my whole code so the whole thing
18:07:27
보고서를 생성하는 준비부터 전체 코드가
from preparing to generate the report the whole thing is my
18:07:30
코드를 try 안에 넣어야 합니다.
code and we have to put the whole thing in a try so
18:07:33
첫 번째 시작 이후에 정확히 어떻게 할지
how to do that exactly after the first begin we're
18:07:37
다시 시작할 것이지만 try를 위해서
going to have another begin but for the try and
18:07:40
여기서 마지막 끝으로 가서
now what we're going to do we're going to go to the last end over here and
18:07:43
끝을 try로 두고
have an end try so with that we put now
18:07:47
전체 코드를 try 안에 넣고 그 후에
the whole code inside the try and after that we can introduce
18:07:50
catch를 도입할 수 있습니다.
the catch so begin cash
18:07:53
catch를 시작하고
and end catch and now in between we
18:07:56
우리가 만날 수 있는 경우에 대해 sql에 알려야 합니다.
have to tell sql what can happen if we encounter
18:07:59
오류가 발생할 수 있는 경우에 대해
an error and here we can do many stuff but i would like now to focus
18:08:02
오류 메시지를 사용자 정의하는 데 집중하고 싶습니다.
on customizing the error message let's start with the
18:08:05
첫 번째로 인쇄하겠습니다.
first one so i'm gonna say print let's say
18:08:09
오류 코드입니다. 첫 번째 항목입니다.
an error a code this is the first thing then on the next line i'm gonna print more informations and now we're gonna say the error message so error
18:08:20
메시지와 함께
message double point space and now we can
18:08:23
재정의된 sql 함수들을 사용할 수 있습니다.
go and use some redefined functions from sql like for example
18:08:27
오류 메시지가
the error message this
18:08:30
여기서 나누기 0 오류가 발생했습니다.
function gonna return the description of the error like the
18:08:33
계속 추가할 수 있습니다.
one we have here divide by zero error encountered and we
18:08:36
오류 번호와 같은 것들이 필요합니다.
can go and keep adding stuff the way that
18:08:39
이렇게 가질 수 있으며 이를 위해
we need like maybe the error number so
18:08:44
오류 번호 함수가 있습니다.
we can have it like this and for that we have as well a function called
18:08:47
이것을 캐스팅해야 한다고 생각합니다.
error number and I think we have to cast this one
18:08:50
이것은 숫자이기 때문에 메시지에는 오직
because it is a number and in the messages we have to have only
18:08:54
문자열만 있어야 하므로 문자열로 처리할 것입니다.
a varchar so it is gonna be as in varchar
18:08:58
이렇게 하면 메시지에 계속 추가할 수 있습니다.
like this and we can keep adding stuff to
18:09:01
예를 들어 오류 라인을 가져오겠습니다.
our message like for example let's take the error line
18:09:04
그에 대해 함수도 있으므로
and for that we have as well function so it's going to be the
18:09:07
오류 줄처럼
error line like
18:09:10
이것과 우리는 그것을 캐스팅해야 합니다.
this and we have to cast it because
18:09:13
그것은 숫자이기도 하고 정말 중요한 것은 저장 프로시저의 이름이므로 오류 프로시저입니다.
it is as well a number and as well what is really important is the name of the stored procedure so error procedure
18:09:24
그리고 우리는 그 오류 프로시저를 위한 함수가 있습니다. 이것은 문자열이 될 것이므로 캐스팅할 필요가 없습니다.
and we have a function for that error procedure like this it's going to be a string so that's why I don't have to cast it.
18:09:32
그래서 이제 우리는 SQL에서 코드에 오류가 발생할 경우 무엇을 할지 정의했습니다.
So now with that we have defined for SQL what to do if there is like an error in our code.
18:09:37
이제 전체를 실행해 보겠습니다. 이제 저장 프로시저를 실행해 보겠습니다.
So let's go and execute the whole thing and now let's go and execute our stored procedure.
18:09:43
그럼 해보겠습니다. 이제 출력에서 결과를 얻지 못하고 오류도 발생하지 않지만 메시지로 가면 매우 좋은 메시지를 볼 수 있습니다.
So let's go and do that. So now as you can see in the output we are not getting any results and it is not giving an error but if you go to the messages you will see a very nice message.
18:09:52
그래서 오류가 발생했다고 말하며 오류 메시지는
So it says an error is occurred the error message is divided
18:09:56
0으로 나누어졌고 오류 번호가 어느 줄에 있는지
by zero and we have the error number in in which line
18:09:59
그리고 저장 프로시저 이름도 있습니다. 보시다시피 놀랍습니다. 이것이 오류가 발생할 경우 더 많은 옵션을 갖거나 제어하기 위해 try와 catch를 사용하는 방법입니다.
and as well the stored procedure name so as you can see it's amazing this is how we use the try and catch in order to have more options or to control what can happen if there is an error
18:10:14
이제 다음으로 할 일은 저장 프로시저를 정리해야 합니다. 보시다시피 모든 것이 커지고 있습니다. 그래서 우리가 일반적으로 하는 것은 탭을 사용하여 공간을 만듭니다.
now the next thing what i'm gonna do we have to go and organize our stored procedure as you can see everything is getting bigger so now what we usually do we use tab in order to make spaces
18:10:22
각 섹션 사이에. 그래서 이제 첫 번째 섹션은 첫 번째 begin과 마지막 end 사이에 있습니다.
between each section so now the first section is between the
18:10:26
그래서 우리는 모든 것을 선택하고 한 번 탭을 눌러야 합니다.
first begin and the last end so
18:10:29
그래서 이제 읽기가 더 쉬워졌습니다. 이제 전체
we have to go and mark everything and hit once a
18:10:32
것은 우리의 코드입니다. 이제 다음 단계는 블록입니다.
tab so now it is easier to read now the whole
18:10:35
try의 블록입니다. 여기 전체가
thing is our codes so now the next level is the block
18:10:38
try입니다. 그래서 해보겠습니다. 저는 그냥
of the try so the whole thing over here is
18:10:41
여기까지 모든 것을 선택하고
the try so let's go and do that i'm just
18:10:44
탭을 누르겠습니다. 이제 더 잘 보이죠?
gonna mark everything until here and then
18:10:48
hit tab so now we can see it better right and
18:10:51
캐치에 대해서도 같은 작업을 했으니 이미
the same thing for the catch i think i have already done that so it's already
18:10:54
푸시된 상태입니다. 이제 다음 단계로 넘어갑니다.
pushed now we go to the next level so between this begin and
18:10:57
끝까지 모든 것이 푸시되었으니 이 모습은 좋습니다.
end everything is pushed so this looks nice the same
18:11:00
여기서도 푸시된 상태이며, 시작과 끝이 없으니
thing over here it's pushed as well and then we don't have
18:11:03
여기서도 시작과 끝이 없으니 괜찮아 보입니다.
here any begin and end so it looks okay and
18:11:06
여기서도 같은 작업을 했으니 모든 시작과 끝이
the same thing over here so all our begin and end
18:11:10
이제 올바르게 정렬되었습니다. 다음 단계는
is now sorted correctly now the next step is that we can
18:11:13
주석을 조금 개선하여 코드를 나눌 수 있도록 하는 것입니다.
go and improve the comments a little bit so we can split our code
18:11:16
여러 섹션으로 나누겠습니다. 그래서 우리는 여기로 갈 것입니다.
into multiple sections so what we're gonna do we're gonna go over here
18:11:19
그리고 이것이 첫 번째 단계라고 말할 것입니다.
and say this is step one and what i
18:11:22
분리를 추가하기 위해 등호를 사용하고 싶습니다.
like to do is to go and add separation using the equals
18:11:25
또는 원하는 특수 문자를 사용하고, 여기서
or any special character that you like and as
18:11:28
우리는 첫 번째 단계를 준비하고 있습니다.
well here so with that we have the first step
18:11:32
전체를 복사하러 가겠습니다.
we are preparing the data and then let's go and copy the whole thing
18:11:35
여기서 두 번째 단계라고 말할 것입니다. 우리는 요약 보고서를 생성하고 있습니다.
go over here and say this is the step two and we're we're going to say this is generating summary reports and something like this.
18:11:46
물론 그 아래에서 이 보고서가 무엇인지 볼 수 있습니다.
And of course, below that, we can see what is this report about?
18:11:49
따라서 특정 국가의 총 고객 수와 평균 점수를 계산합니다.
So calculate total customers and average score for specific country.
18:11:59
그리고 여기서도 총 주문 수와 총 판매량을 계산하는 주석을 추가할 수 있습니다.
And as well, we can go over here and add as well, a comment, calculate total number of
18:12:07
특정 국가에 대한 주문 수와 총 판매량입니다.
orders and total sales for
18:12:11
주문 수와 총 판매량에 대해
specific country and of
18:12:14
이 오류를 제거해야 합니다. 그렇지 않으면
course we have to go and remove this error over here otherwise we'll
18:12:17
오류가 발생하고 캐치에 대해 뭔가를 추가할 수 있습니다.
get an error and we can go and add something about the catch
18:12:20
이렇게 다시 몇 가지 주석을 추가할 수 있습니다.
where we can say like this again a few comments we're
18:12:25
오류 처리를 하겠습니다.
gonna say error handling so
18:12:29
다시 실행하여 최신 버전을 확인하고, 우리는 잘 정리된 프로시저를 만들었습니다.
let's go and execute it again in order to make sure we have the newest version and with that we are done we have a really nice
18:12:36
여러 단계가 있는 저장 프로시저를 만들었고, 전문적으로 오류 처리가 포함되어 있으며, 모든 것이 잘 정리되어 읽기 쉽습니다. 이것이 우리가 저장 프로시저를 만드는 방법입니다.
stored procedure with multiple steps and we have it professional where we have error handling inside it and everything looks well organized and easy to read so this is how we build stored procedures
18:12:47
좋아요, 친구들. 저장 프로시저에 대한 모든 것이었습니다. SQL에서 프로그래머블리티를 추가하는 놀라운 기능이었습니다. 이제 다음 단계에서는 트리거 주제를 빠르게 다룰 것입니다.
all right my friends so that's all about the stored procedures that was an amazing feature in sql to add programmability in sql now in the next step we're gonna cover quickly the topic of the triggers
18:12:58
좋아요, 시작합시다. 알겠습니다.
So let's go. All right.
18:13:03
이전에는 모든 SQL 문을 하나의 시작 프로시저에 넣을 수 있다는 것을 이해했습니다. 그리고 수동으로 시작 프로시저를 실행해야 합니다.
So previously we have understood that we can put all our SQL statements in one start procedure and you have to go and manually execute the start procedure.
18:13:13
즉, 시작 프로시저를 트리거하려면 수동으로 실행해야 합니다. 그리고 이것은 물론 문제입니다.
So that means in order to trigger the start procedure, you have manually to execute it. And this is, of course, a problem.
18:13:20
그것을 자동으로 수행하는 것은 어떨까요? 그래서 트리거가 있습니다.
How about to do that automatically? So triggers
18:13:23
SQL에서 트리거는 특정 이벤트가 테이블에서 발생할 때 자동으로 실행되는 특별한 저장 프로시저입니다.
in SQL they are special stored procedure that automatically runs or let's say fired in response to a specific event that happens on a table.
18:13:33
이게 정확히 무슨 뜻일까요? 이제 데이터베이스에 테이블이 있다고 가정해 봅시다. 이 테이블에서 데이터 삽입, 삭제, 업데이트와 같은 일이 발생할 수 있습니다.
So what this exactly means. So now let's say that we have a table in our database and now something could happen to this table like inserting data, deleting, updating data.
18:13:43
이런 일들이 발생하는 것을 우리는 이벤트라고 부릅니다. 이제 우리는 이 테이블 위에 트리거를 붙일 수 있습니다.
All those stuff that is happening we call them events. And now what we can do we can go and attach like a trigger on top of this table.
18:13:51
이벤트가 발생할 때마다 삽입, 업데이트, 삭제와 같은 다른 작업이 트리거될 수 있습니다.
and each time an event happens like insert update deletes, something else can be triggered.
18:13:56
예를 들어, 다른 테이블에 데이터를 삽입하는 것입니다.
Like maybe going and inserting data somewhere else in another table.
18:14:00
또는 우리가 처음에 데이터를 삭제할 수 있는지 확인하는 것입니다. 또는 경고 메시지를 보내는 것일 수도 있습니다.
Or doing a check whether we are allowed to delete the data in the first place. Or maybe sending a warning message or something.
18:14:07
테이블의 변경 사항에 따라 다른 이벤트를 트리거할 수 있습니다. 그리고 우리는 SQL 트리거를 사용하여 이를 수행할 수 있습니다.
So based on any changes to the table, we can trigger another event. And we can do that using the SQL triggers.
18:14:14
SQL 트리거에는 여러 유형이 있습니다. DML 트리거와 같은 것입니다.
And for the SQL triggers, we have like multiple types. Like the DML triggers.
18:14:19
이 유형의 트리거는 삽입이 있을 때 응답합니다.
and this type of trigger gonna respond once we have like insert
18:14:23
업데이트 삭제 문이 있는 또 다른 유형의 트리거가 있습니다.
update delete statements another type of triggers we
18:14:26
DDL 트리거가 있습니다. 트리거를 만들어서
have the ddl triggers like you can make a trigger to
18:14:29
테이블이나 뷰를 생성, 수정 또는 삭제하는 등의 스키마 변경에 응답할 수 있습니다.
respond to any schema changes like creating
18:14:32
테이블뿐만 아니라 세 번째 유형의 트리거는 로그인 트리거입니다.
altering or dropping a table or even view by
18:14:35
테이블과 세 번째 유형의 트리거 외에도 로그인하는 방법이 있습니다.
the way not only tables and the third type of triggers we have the login
18:14:39
트리거는 로그인 이벤트에 응답할 수 있습니다. 이제 이 튜토리얼에서는 DML 트리거인 삽입, 업데이트, 삭제에 집중할 것입니다. DML 트리거에는 두 가지 유형이 있습니다.
trigger so the trigger can respond to a login event now in this tutorial we're going to focus on the dml triggers the insert update delete and And for the DML triggers, we have two types.
18:14:49
우리는 후행 트리거와 대신 트리거가 있습니다.
We have after triggers and as well we have instead of triggers.
18:14:54
이름에서 알 수 있듯이, 후행을 사용하면 이벤트가 발생한 후에 실행될 수 있습니다.
So as the name suggests, if you use after, so it can be executed after the event.
18:15:00
대신 트리거는 모든 일이 발생할 때까지 기다릴 수 없는 것입니다.
And the other type that instead of, it's something that cannot wait until everything happens.
18:15:05
따라서 이번에는 트리거가 이벤트 후가 아니라 이벤트 중에 실행될 수 있습니다.
So this time, the trigger can be executed during the event, not after it.
18:15:10
이제 이를 이해하기 위해 정말 좋은 사용 사례를 살펴볼 수 있습니다.
So now in order to understand all of this, we can have a really nice use case.
18:15:18
이제 사용 사례는 감사 로그를 유지하는 것입니다. 우리가 의미하는 바는 무엇일까요? 예를 들어, 직원 테이블을 살펴보겠습니다.
And now the use case is about maintaining an audit logs. So what we mean with that? Let's have, for example, the table employees.
18:15:25
직원 데이터는 일반적으로 매우 민감한 정보입니다. 여기서 우리는 어떤 직원이 추가되었는지, 급여 업데이트, 직원 해고를 볼 수 있습니다.
The employee data are usually very sensitive informations because there we can see which employees are added, the salary updates, the employee terminations.
18:15:35
이것은 테이블을 매우 중요하게 만듭니다. 우리는 이 테이블에서 발생하는 모든 변경 사항을 추적하고 싶기 때문입니다.
And this makes the table very important because we would like to track all those changes that is happening to this table.
18:15:41
따라서 우리는 삽입, 업데이트, 삭제할 때마다 이러한 모든 변경 사항에 대한 로그를 유지하고 나중에 분석하고 싶습니다.
So each time we are inserting, updating, deleting, we would like to maintain a log about all those changes in order to analyze it later.
18:15:49
물론 이러한 로그는 규정 준수 및 감사인에게 매우 중요합니다.
It is, of course, very important such a logs for the compliance and the auditors.
18:15:53
문제가 발생할 경우, 우리는 로그를 통해 언제 이 일이 발생했는지, 누가 변경했는지, 무엇이 정확히 변경되었는지를 이해할 수 있습니다.
And in case there is like a problem, we can go to the logs to understand when this happened, who made the changes and what exactly changed.
18:16:02
이제 로그를 유지하기 위해 트리거의 힘을 사용할 수 있습니다.
And now in order to maintain logs, we can use the power of triggers.
18:16:06
우리가 할 일은 직원 테이블에 트리거를 연결하는 것입니다.
So what we're going to do, we're going to go and attach like a trigger on the table employees.
18:16:11
직원에게 새 데이터를 삽입할 때마다 우리는 또 다른 이벤트를 트리거하고 있습니다.
And each time we insert a new data to the employees, we are triggering another events.
18:16:17
이 새로운 직원은 감사 로그에 삽입되어 이 활동에 대한 기록을 로그에 남길 수 있습니다.
So what can happen, this new employee can be inserted in the audit logs in order to have a record about this activity in the logs.
18:16:25
즉, 직원 테이블에 데이터를 삽입할 때마다 자동으로 로그에 데이터를 삽입하고 있습니다.
So that means each time you are inserting data to the table employees, you are automatically inserting data inside the logs.
18:16:33
이것은 트리거에 대한 정말 놀라운 사용 사례입니다. 그러니 구현해 봅시다. 자, 이제 트리거의 구문을 빠르게 확인해 봅시다.
And this is really amazing news case for the triggers. So let's go and implement it. OK, so now let's check quickly the syntax of the triggers.
18:16:39
우리는 일반적으로 트리거를 생성하는 것으로 시작하고, 그 다음 트리거 이름을 정합니다.
So we start with the usuals create trigger, then the trigger name.
18:16:43
그 다음에는 이 트리거가 어떤 테이블에서 작동할지를 지정해야 합니다.
and then we have to specify on which table this trigger
18:16:46
하나의 테이블 위에 트리거를 연결하고 나서 우리는
can be built in so now we are attaching like a trigger
18:16:49
SQL에서 이 트리거가 언제 발생할지를 정의해야 합니다.
on top of one table and after that we have to
18:16:52
트리거를 실제로 트리거하는 것이 무엇인지 정의할 수 있습니다.
define for the sql when this trigger can happen so
18:16:56
그 후 또는 대신에 정의해야 할 연산자가 있습니다.
what is actually triggering the trigger and here you can define
18:16:59
그런 다음 또는 대신에 정의해야 합니다.
after or instead then you have to define the
18:17:02
연산자를 정의해야 하며, 먼저 '그런 다음' 또는 '대신'을 정의한 후, 삽입, 업데이트, 삭제 또는 그 중 하나와 같은 작업을 정의해야 합니다. 이를 통해 SQL에 정확히 언제 이 작업이 발생해야 하는지를 알려줍니다.
operator so first you have to define like after or instead of and then we have to define the operation so insert update delete or one of them and with that you are telling SQL when exactly this should happen.
18:17:14
이제 그 후에, 트리거가 발생했을 때 SQL에 어떤 일이 발생할 수 있는지를 알려야 합니다.
And now after that, we have to tell SQL what can happen if that trigger is triggered.
18:17:19
여기서 우리는 시작과 끝이 있으며, 트리거가 발생했을 때 어떤 일이 발생할 수 있는지를 설명하는 여러 SQL 문이 있습니다.
So here we have like begin and end and then we have like several SQL statements that's going to describe what can happen once we have the trigger.
18:17:27
그게 전부입니다. 보시다시피 구문이 매우 간단합니다. 자, 이제 단계별로 진행해 보겠습니다.
So that's it. As you can see, the syntax is very simple. Okay, so now let's do it step by step.
18:17:32
먼저, 로그 정보를 저장할 수 있는 테이블을 생성하고 싶습니다.
First, I would like to create a table where we can store the logs information.
18:17:36
그래서 우리는 로그 정보를 저장할 수 있는 테이블을 만들 것입니다.
So it's going to be very simple table we're going to say create table then
18:17:39
그것은 매우 간단한 테이블이 될 것이고, 우리는 테이블을 생성하겠다고 말할 것입니다.
we're going to call it sales employee blogs
18:17:43
우리는 이것을 판매 직원 블로그라고 부를 것입니다.
and we're going to have the following columns inside it so
18:17:46
그 안에 다음 열이 있을 것입니다.
let's start with the primary key it's going to be the log id and the
18:17:49
우선 기본 키부터 시작하겠습니다. 로그 ID가 될 것입니다.
data type int and then we're going to have like a sequence so we're going to have
18:17:53
데이터 유형은 정수형이고, 다음은 시퀀스가 될 것입니다.
identity and this is the primary key let's
18:17:56
정수형 데이터 유형이 될 것이고, 다음은 로그 메시지가 될 것입니다.
go to the next one it's going to be the employee id and the
18:17:59
그래서 우리는 그것을 varchar로 설정할 것입니다.
data type going to be int the next one is going to be the log message
18:18:03
255로 설정할 것이고, 다음으로 넘어갑니다.
so let's have it as a the varchar and i'm
18:18:06
우리는 잠금 날짜를 가질 것이고, 다음은
gonna have it like 255 and then to the next
18:18:09
날짜 또는 날짜 시간이라고 말할 것입니다. 이제 실행해 보겠습니다.
one we're gonna have the lock dates and then we're gonna have like let's
18:18:12
이제 데이터베이스에 새로운 테이블이 생겼습니다.
say a date or a date time so that's it let's go and execute
18:18:16
다음 단계로, 우리는 트리거를 생성할 것입니다.
it and with that we have a new table inside our database now
18:18:19
트리거를 생성하겠다고 말할 것이고, 이렇게 trg라고 부를 것입니다.
the next step with that we're gonna go and create our trigger so
18:18:22
삽입 후 직원이라고 부를 것이고, 이제 테이블을 정의해야 합니다.
we're gonna say create trigger and i'm gonna call it like this trg it is just a perfect to indicate this is a trigger and i'm just gonna call it
18:18:31
이제 우리는 직원 테이블에 트리거가 있다고 말하고 있습니다.
after inserts employee and now we have to define the table so it's going to be on sales employee
18:18:40
이제 논리를 정의해야 합니다.
so now with that you are saying we have now a trigger on the table employees
18:18:43
삽입 후를 사용할 것입니다.
and now we have to define the logic so we're going to use after
18:18:47
새 레코드가 삽입된 후 어떤 일이 발생해야 하는지 정의할 것입니다.
inserts so that means after we insert any record to the table employees the following things should happen so we're going to say as and then begin
18:18:57
그리고 끝내고, 그 사이에 우리의 논리를 가질 수 있습니다.
and end and in between we can have our logic so
18:19:00
새 레코드가 직원 테이블에 삽입된 후 어떤 일이 발생할 수 있는지 알아보겠습니다.
what can happen after a new record is inserted to the employees
18:19:03
우리는 직원 로그에 새 레코드를 삽입할 것입니다.
we're going to go and insert a new record to the employee
18:19:06
판매 직원 로그에 삽입할 것입니다.
logs so we're going to have inserts into sales
18:19:10
여기 세 개의 열, 직원 ID가 있을 것입니다.
employee logs and we're
18:19:13
로그 메시지와 로그 날짜가 있을 것이고, 어떤 값이 삽입될지 선택하겠습니다.
going to have here the three columns employee id the
18:19:17
로그 메시지와 로그 날짜를 위해 삽입될 값은 쿼리에서 가져올 것입니다. 그래서 우리는 선택할 것이고, 직원 ID도 말할 것입니다.
log message and the log dates so now which value is going to be inserted it's going to be like from a query so we're going to say select and we're going to say as well employee id
18:19:29
그리고 로그 메시지는 사용자 정의할 수 있습니다. 예를 들어, 새로운 직원이 추가되었다고 가정해 보겠습니다.
and for the log message we can have customized one like let's say a new employee added
18:19:36
그리고 그것은 직원 ID와 같을 것입니다.
and it's going to be equal to the employee id so
18:19:39
직원 ID를 얻기 위해서는 이렇게 될 것입니다. 이제 다음으로 로그 날짜가 필요합니다. 날짜를 가져올 것입니다.
in order to have the employee id it's going to be like this so that's it now to the next one we need the log date it's going to be get dates
18:19:50
이제 당신은 이렇게 말할 수 있습니다. 알겠어요, 그런데 이 직원 ID는 어디서 오는 건가요? 테이블에서 가져올 것입니다.
And now you might say, okay, but where this employee ID is coming from? Well, it's going to come from the table from inserted.
18:19:57
그렇다면 실제로 무엇이 삽입되나요?
So what is actually inserted?
18:20:00
새로운 데이터를 모두 보유하는 특별한 가상 테이블입니다.
special virtual table that holds all the new
18:20:03
우리 직원 테이블에 삽입된 데이터이므로 직원 내부에 삽입하는 모든 것이 사용 가능합니다.
inserted data to our table employees so anything we
18:20:06
이 테이블 안에 있으며, 물론 이것은 실행 중에만 사용할 수 있습니다.
are inserting inside the employees will be available inside
18:20:10
이 트리거의 실행 동안만 사용할 수 있습니다. 이제 밖으로 나가서
this table and of course this is only available during
18:20:13
이 쿼리 밖으로 나가서 삽입된 테이블을 쿼리할 수 없습니다.
the execution of this trigger so you cannot go now outside
18:20:17
아무것도 찾을 수 없습니다. 이것은 우리가 직원 테이블에 하는 모든 것을 포함하는 가상 테이블과 같습니다.
of this query and start querying the table inserted because
18:20:20
많은 정보가 포함되어 있습니다. 예를 들어, 급여, 나이 등이 있습니다.
you will not find anything this is only like a virtual table that contains anything that we are doing to the table employees and you find
18:20:28
이제 삽입된 것에 대한 내용은 이렇습니다. 이제 우리는
lot of informations like the salary the age and so on
18:20:31
메시지에 모든 것이 문자열로 되어 있는지 확인해야 합니다.
so that's it for the inserted now we have to make
18:20:34
직원 ID는 정수이므로 형 변환을 해야 합니다.
sure that in our message we have everything as a string
18:20:37
형 변환을 하고, 그런 다음 이렇게 말할 것입니다.
because the employee id is an integer so we have to cast
18:20:40
그렇게 캐스팅하고 나면 우리는 이렇게 말할 것입니다.
it so cast and then we're gonna say as
18:20:44
이렇게 하지 않으면 오류가 발생하므로 트리거가 준비된 것 같습니다. 직원 테이블에 새로운 트리거가 생겼고, 이제 첫 번째 질문은 이 트리거가 언제 발생할 수 있느냐는 것입니다.
far char like this otherwise we'll get an error so i think we have our trigger ready we have a new trigger on the table employees and now the The first question is when this trigger can happen?
18:20:56
음, 직원에게 데이터를 삽입한 후에 발생할 수 있습니다. 그리고 두 번째 질문은 무슨 일이 일어날 것인가입니다.
Well, it can happen after inserting data to the employees. And then the second question, what's going to happen?
18:21:03
음, 이 이벤트가 발생하면 여기에서 전체가 실행되어 로그에 삽입, 직원 ID, 메시지 및 이 일이 발생할 때의 날짜를 기록합니다.
Well, once we have this event, the whole thing here going to be executed where we are saying insert to the logs, the employee ID, the message, and as well the date when this happens.
18:21:14
그리고 우리는 삽입된 가상 테이블에서 모든 정보를 가져올 수 있습니다. 그래서 준비가 된 것 같습니다.
And we can get all those informations from the table, the virtual table inserted. So I think we are ready.
18:21:20
가서 실행해 봅시다. 이제 객체 탐색기로 가서 우리의 데이터베이스로 가서 직원 테이블로 가서 트리거로 갑니다.
Let's go and execute it. So now if you go to the object explorer to our database, let's go to our table employees and then to the triggers.
18:21:28
여기 처음 오셨다면, 방금 생성한 새로운 트리거를 볼 수 있습니다.
So if you're fresh over here, you can see our new trigger that we just created.
18:21:33
그래서 이렇게 해서 우리는 트리거를 정의했고 준비가 되었습니다. 이제 다음 단계는 우리의 트리거를 실행하는 것입니다.
So with that, we have defined our trigger and we are ready. Now the next step is that we're going to go and trigger our trigger.
18:21:40
자, 이제 트리거를 정의했으니 준비가 되었습니다. 다음 단계는 트리거를 실행하는 것입니다.
So let's go and do that. Let's have a new query. But first I'm going to have a look to our logs.
18:21:46
판매 직원 로그를 조회해 보겠습니다.
So sales employee logs. So let's query this one.
18:21:51
로그가 비어 있는 것을 보실 수 있습니다. 직원 테이블에 아무것도 삽입하지 않았기 때문입니다.
and as you can see our logs is empty because we didn't insert anything to the table employees let's go and do that let's trigger our trigger so what we're gonna do we're gonna say inserts into
18:22:01
직원 테이블에 삽입할 것입니다.
sales employees and we're gonna have the following
18:22:04
여섯 명의 직원 데이터를 입력할 것입니다.
values so we are at the counter i think
18:22:07
첫 번째 이름은 마리아, 성은 그리고 직책은 인사부로 하겠습니다.
six let's have the first name maria the last name and then we're gonna have the position it's gonna be the
18:22:16
예를 들어 생일을 정해보겠습니다. 여기 여성 직원이 있습니다.
hr for example the birth dates let's pick something i don't know we have a female here
18:22:24
그리고 급여를 정해보겠습니다.
and the salary let's go and get this
18:22:27
급여와 계층을 정해보겠습니다.
salary and the hierarchy it can be for example three so
18:22:30
이제 실행해 보겠습니다. 그 결과를 보실 수 있습니다.
let's go and execute it and with that as you can see we have
18:22:33
새로운 데이터를 직원 테이블에 삽입했습니다. 이제 로그를 확인해 보겠습니다.
inserted the new data to the employees let's check now the
18:22:36
여기 직원 번호 6에 대한 로그가 있습니다.
logs so let's query it so we
18:22:39
우리는 좋은 메시지를 가지고 있으며, 이 일이 발생한 시점도 있습니다.
have here nice log about the employee number six and
18:22:42
다른 직원을 삽입할 수 있습니다.
we have a nice message and when this did happen of
18:22:45
일곱 번째 직원을 같은 데이터로 삽입해 보겠습니다.
course you can go and insert another employee let's
18:22:49
로그를 확인해 보겠습니다. 또 다른 로그가 생겼습니다.
say seven with the same data so let's do that
18:22:52
새로운 직원에 대한 로그가 생겼습니다. 정말 놀라운 사례입니다.
and check the logs and with that we have another
18:22:55
데이터에 대한 로그를 유지하기 위해서입니다.
log for the new employee so this is really amazing use case
18:22:58
삽입된 횟수에 대한 분석을 할 수 있습니다.
in order to maintain a log to your data and you can go
18:23:01
물론 삽입뿐만 아니라 업데이트 및 삭제에 대해서도 가능합니다.
and make like some analysis on how many insert it
18:23:04
매우 간단합니다.
happens and of course not only on the inserts you can have
18:23:07
SQL에서 트리거를 만드는 방법입니다. 자, 친구들.
it on the update delete so as you can see it is very simple
18:23:11
트리거에 대한 모든 내용입니다. 이제 모든 개념을 다뤘습니다.
this is how we create a triggers in sql all right my friends so
18:23:14
이제 SQL에 대해 배워야 할 모든 주제를 다뤘습니다.
that's all about the triggers with that with with that we
18:23:17
다음 장에서 계속 진행하겠습니다.
have covered now with that we have covered now all the concepts and
18:23:21
이제 다음 장에서 배워야 할 SQL의 모든 개념과 주제를 다뤘습니다.
topics that you have to learn about sql now in the next chapter
18:23:24
이제 성능에 관한 내용이 될 것이며, 쿼리를 작성하기 시작할 때
it's going to be about the performance so as you start writing queries
18:23:27
그리고 계속해서 몇 가지 쿼리가 느려지는 것을 알게 될 것입니다.
and so on you will start noticing some queries
18:23:30
이번 장에서는 성능을 최적화하는 다양한 기술을 배울 것입니다. 첫 번째이자 가장 유명한 방법은 데이터베이스에 인덱스를 구축하는 것입니다.
are really slow now what we can do in this chapter we're going to learn different techniques on how to optimize the performance and the first and the very famous one is to go and build indexes in databases.
18:23:41
그럼 이것이 무엇을 의미하는지 이해해 봅시다. 인덱스란 무엇인가요?
So let's understand what this means. So what is an index?
18:23:48
인덱스는 쿼리 속도를 향상시키기 위해 행에 빠르게 접근할 수 있도록 하는 데이터 구조입니다.
An index is a data structure that provides a quick access to the rows to improve the speed of your queries.
18:23:56
인덱스는 데이터 검색 프로세스를 가속화하기 위한 데이터베이스의 안내서와 같습니다. 특히 큰 테이블이 있는 경우에 그렇습니다.
So an index is like a guide for your database in order to speed up the process of searching for data, especially if you have like big tables.
18:24:04
이제 인덱스가 무엇인지 이해하기 위해, 거대한 책이 있다고 상상해 보세요. 특정 주제나 장을 찾고 싶습니다.
So now in order to understand what are indexes, Imagine you have a huge book and you want to find a specific topic or a chapter.
18:24:11
찾고 있는 주제를 찾기 위해 단일 페이지를 넘기는 대신, 책 뒷부분에 있는 인덱스를 사용하여 바로 해당 페이지로 점프할 수 있습니다.
Instead of flipping a single page in order to find the topic that you are searching for, you would use the index at the back of the book in order to jump straight to the right page.
18:24:22
그리고 그것이 바로 인덱스가 데이터에 대해 하는 일입니다.
And that's exactly what index does, but for your data.
18:24:25
인덱스를 이해하기 위해 제가 사용하는 또 다른 비유는 인덱스를 큰 호텔로 생각하는 것입니다.
Another analogy that I use in order to understand indexes is, think about the indexes as a big hotel.
18:24:32
이제 호텔에 가이드가 없다고 가정해 보겠습니다. 방 번호 501을 찾고 싶습니다.
Now, let's say that in the hotel, we don't have any guides and you would like to find the room number let's say 501.
18:24:39
그럼 어떻게 할 건가요? 층별로 방을 검색하고 각 방을 확인해야 합니다.
Now what you gonna do you gonna go and search for your room floor by floor and checking each room until you find your room.
18:24:46
하지만 다행히도 호텔에는 번호 매기기 시스템이 있고, 리셉션에서 지도를 요청하여 어떤 건물의 어떤 층에 방이 있는지 이해할 수 있습니다.
But instead of that thankfully hotels have a numbering system and you can ask for a map from the reception in order to understand in which building in which floor you can find your room.
18:24:57
그냥 지도를 따라가고 아마 몇 개의 표지판을 보면
So by just following the map and maybe some signs it's
18:25:01
그렇게 큰 호텔에서 방을 찾는 것이 매우 빠를 것입니다.
going to be very quickly to locate and find your room in such a big
18:25:04
그리고 그것이 바로 각 데이터베이스가 필요한 것입니다.
hotel and that's exactly what each database needs it
18:25:07
데이터베이스가 올바른 데이터를 찾고 위치를 파악하는 데 도움을 주기 위해 인덱스가 필요합니다.
needs an index in order to help the database finding
18:25:10
모든 것을 스캔하지 않고도 말이죠.
and locating the right data without having to
18:25:14
이제 당신이 나에게 물어본다고 가정해 봅시다.
scan everything and now let's say that you ask me you
18:25:21
이 큰 테이블이 있고 인덱스를 사용하여 쿼리를 빠르게 하고 싶습니다. 내 첫 번째 질문은
what i have this big table and i would like to speed
18:25:24
이 테이블로 정확히 무엇을 하고 있는지입니다.
up the queries using indexes and my first question
18:25:27
이 테이블을 텍스트 검색에 사용하고 있나요, 아니면 이 테이블로 복잡한 분석을 하고 있나요?
gonna be what are you exactly doing with this table are
18:25:30
그 이유는
you using this table to search for a text or are you doing
18:25:33
이 질문을 하는 이유는 서로 다른 경우가 있기 때문입니다.
like complex analysis with this table and the reason
18:25:37
왜 제가 이 질문을 하는지에 대한 이유는 우리가 서로 다른
why i'm asking this is that we have different
18:25:40
목적을 위해 데이터베이스에서 서로 다른 인덱스를 가지고 있기 때문입니다. 이제
indexes in databases for different purposes so now let's
18:25:43
데이터베이스에서 우리가 가진 다양한 인덱스 유형을 빠르게 살펴보겠습니다. 저는 데이터베이스의 인덱스를
have a quick look to the different types of indexes that we have in database i divide the indexes in databases into
18:25:49
세 가지 범주로 나눕니다. 첫 번째는 구조에 따라
three categories the first one is by the structure how
18:25:53
데이터베이스가 데이터를 조직하고 참조하는 방법입니다.
the database is organizing and referencing the data
18:25:56
여기에는 클러스터형 인덱스와
and here we have two types the clustered index and
18:26:00
비클러스터형 인덱스의 두 가지 유형이 있습니다. 이들은 매우 중요합니다.
the non-clustered index those are very important
18:26:03
이해하는 데 도움이 됩니다. 이제 인덱스에 대한 또 다른 범주가 있습니다.
to understand now we have another category for the indexes
18:26:06
저장 방식에 따라 나눌 수 있으며, 이
we can divide them by the storage and in this
18:26:09
범주에서는 데이터가 어떻게 저장되는지에 대해 이야기합니다.
category we are talking about how the data is stored
18:26:12
물리적으로 데이터베이스에 저장되는 방식입니다. 그래서 두 가지 유형이 있습니다.
physically in the database so we have two types
18:26:16
우리는 행 저장 인덱스와 열
we have the row store index and the column
18:26:19
저장 인덱스가 있습니다. 세 번째 유형은 함수와
store index and the third type is the functions and
18:26:22
여기에는 두 가지 유형이 있습니다. 고유 인덱스와
here we have two types we have the unique index
18:26:25
필터링된 인덱스가 있습니다. 이제 각 인덱스 유형은
and the filtered index now each index type
18:26:28
자신만의 특성이 있지만 항상 트레이드오프가 있습니다. 일부는 읽기 성능을 개선할 수 있고, 다른 하나는 삽입 및 업데이트 작업을 개선할 수 있습니다.
has its own strings but as well there is always a trade-off some might improve their read performance the other one might improve the insert and update operations
18:26:39
그래서 작업에 적합한 인덱스 유형을 선택하는 것이 중요합니다.
So it's all about choosing the right type of index for the job.
18:26:42
이제 여러분이 할 일은, 각 유형에 대해 깊이 파고들어 어떻게 작동하는지, 그리고 어떻게 생성할 수 있는지 이해하는 것입니다.
So now what you're going to do, we're going to go and deep dive into each of those types in order to understand how they work and how we can create them.
18:26:49
우리는 첫 번째 범주인 구조부터 시작할 것입니다. 클러스터형 인덱스와 비클러스터형 인덱스가 있습니다.
And we will start with the first category, the structure. We have the clustered index and the non clustered index.
18:27:00
이제 인덱스가 데이터베이스에서 어떻게 작동하는지 파고들기 전에, 먼저 데이터베이스 테이블에서 어떤 일이 발생하는지 이해해봅시다.
Now, before we dive into how the indexes works in databases, let's understand first what happens to the database tables
18:27:07
새로운 인덱스를 사용하지 않으면
if you don't use any index when you create a new
18:27:10
데이터베이스에 테이블을 생성할 때 고객과 같은
table in your database like for example the customers
18:27:13
테이블이 있다고 가정해 보겠습니다. 예를 들어 20명의 고객이 있는
table where you have let's say 20 customers inside
18:27:16
테이블을 가지고 있다고 가정할 때, 클라이언트 측에서 보게 될 것은
this table what you're gonna see at the client side is like
18:27:19
행과 열이 있는 스프레드시트와 같은 테이블입니다.
spreadsheets like a table with rows and
18:27:22
열과 행이 있는 스프레드시트처럼 보이지만
columns but behind the scenes the database store it a
18:27:26
데이터베이스는 데이터를 조금 다르게 저장합니다.
bit differently it's gonna store the data in a data file
18:27:29
이 파일 안에 데이터가
on the desk and inside this file the data
18:27:32
페이지라고 불리는 블록 안에 저장될 수 있습니다.
can be stored inside blocks called pages so
18:27:36
행과 열처럼 저장되지 않습니다.
it's not like rows and columns that are stored inside
18:27:39
데이터 파일 안에 페이지가 있습니다.
data files and inside the data files we have pages
18:27:42
페이지란 데이터베이스에서 데이터 저장의
so what is a page a page is the
18:27:46
단위이며 고정 크기는 8킬로바이트입니다.
unit of data storage in a database and it
18:27:49
SQL 데이터베이스는 그 안에 무엇이든 저장할 수 있습니다.
is a fixed size of eight kilobytes where
18:27:52
테이블의 행이나
the sql database can store anything inside it
18:27:55
열, 메타데이터, 인덱스를 저장할 수 있습니다.
it can store inside it the rows of your tables or
18:27:58
데이터와 상호작용할 때마다 SQL은
columns metadata indexes and every time you are interacting with your data the sql is reading
18:28:06
페이지에 읽고 씁니다.
and writing to those pages so as you can see the sql
18:28:09
SQL은 데이터를 행과
is not storing the data inside like rows and
18:28:12
열처럼 저장하지 않습니다.
columns so if you are running a query the sql is
18:28:15
쿼리를 실행할 때 SQL은
not like selecting a specific column it
18:28:18
데이터 페이지를 읽기 위해 항상 맞춥니다.
always fits a data page in order to read the
18:28:21
이 페이지 안의 행과 주요 두 탭은
rows inside this page and the main two tabs
18:28:24
데이터 페이지와 인덱스 페이지입니다.
that we're gonna learn is the data page and the index page so how the data page looks like it is divided
18:28:31
데이터 페이지는 여러 섹션으로 나뉩니다.
into multiple sections the first section is the page header
18:28:34
첫 번째 섹션은 페이지 헤더입니다.
where the database can store key information about the metadata
18:28:37
데이터베이스는 메타데이터에 대한 주요 정보를 저장할 수 있습니다.
like the page id and it has the following format it starts with the file id like one and then we have a unique number for each page so for example 150.
18:28:47
페이지 ID와 같은 형식을 가지고 있습니다.
so the page header is a fixed size of 96 bytes
18:28:50
페이지 헤더는 고정 크기 96바이트입니다.
now to the next section we can have a variable size this is where your data row is going to be stored so your actual data i row is going to be stored in this section
18:29:00
다음 섹션은 가변 크기를 가질 수 있습니다.
and the SQL gonna try and fits as many rows as
18:29:03
한 페이지에 가능한 많은 행을 넣으려고 하고, 이는 물론
it can in one single page and this of course depends on
18:29:07
각 행의 크기에 따라 다릅니다. 그래서 큰 테이블이 있다면
the size of each row so if you have like a large table
18:29:10
행이 정말 크기 때문에 SQL이
where the rows are really big so SQL can fit
18:29:13
한 페이지에 몇 개의 행만 넣을 수 있습니다. 이제
only few rows in one single page and now moving
18:29:16
데이터 페이지의 마지막 섹션으로 넘어가면
on to the last section in the data page we have the
18:29:19
오프셋 배열이 있습니다. 이것은 빠른 인덱스와 같습니다.
offset array this is like a quick index for
18:29:23
이 페이지에 저장된 행을 추적하여
the rows stored inside this page it It keeps track of
18:29:26
각 행이 시작되는 위치를 알 수 있도록 하여 SQL이 특정 행을 쉽게 찾을 수 있게 합니다.
where each rows begins so that the SQL can easily locate a specific row without having a scale like scanning the entire page in order to find a row.
18:29:35
이것이 데이터 페이지의 구조입니다. 그리고 이것이 SQL이 데이터베이스에 데이터를 저장하는 방식입니다.
So this is the structure of the data page. And this is exactly how the SQL stores data inside the databases.
18:29:43
이제 고객 테이블과 20개의 행이 있는 예제로 돌아가 보겠습니다. SQL이 이러한 페이지를 어떻게 생성하는지 살펴보겠습니다.
So now back to our example where we have the customers table and 20 rows. So let's see how SQL gonna be creating those pages.
18:29:50
이 테이블에서 인덱스를 사용하지 않는다면, 이제 어떤 일이 발생할 수 있을까요?
Now if you are not using any index in this table. So now what can happen?
18:29:54
SQL은 고객 데이터를 삽입할 때 이 페이지에 데이터를 삽입할 수 있습니다.
SQL can insert the data inside those pages as you are inserting the data inside the customers.
18:30:00
예를 들어, 고객을 12, 5, 15, 6, 7과 같이 먼저 삽입하면 SQL은 데이터를 정확히 그렇게 데이터 페이지에 삽입합니다.
So maybe first you are inserting the customers like 12, 5, 15, 6, 7 and SQL gonna insert it to the data pages exactly like that.
18:30:09
즉, SQL은 테이블에 삽입하는 대로 데이터를 삽입하고 있습니다.
So that means SQL is just inserting the data as you insert it to the table.
18:30:13
각 데이터 페이지가 오직 다섯 개의 행만 담을 수 있다고 가정해 보겠습니다.
So let's say each data page is like fitting only five rows.
18:30:17
다섯 명의 고객을 삽입한 후, SQL은 다음 행을 위해 또 다른 데이터 페이지를 생성합니다.
So after we insert five customers, SQL gonna go and create another data page for the next rows.
18:30:23
다음 페이지에서 SQL은 다음 다섯 명의 고객을 삽입할 것입니다.
So in the next page, the SQL gonna insert the next five customers.
18:30:28
페이지가 가득 차면 다음 고객을 추가하기 위해 또 다른 데이터 페이지를 생성합니다.
And once it's full, it's gonna create another data page in order to start adding the next customer
18:30:33
예를 들어, 20명의 고객을 위해 4개의 페이지가 생길 때까지.
until we have like, for example, four pages for the 20 customers.
18:30:37
이제 이 4개의 페이지 안의 고객을 확인하면, 전혀 정렬되어 있지 않음을 알 수 있습니다.
So now if you check the customers inside those four pages, you see that they are not sorted at all.
18:30:43
이는 이 시나리오에서 인덱스를 사용하지 않기 때문입니다. 우리는 이 구조를 힙 구조라고 부릅니다.
And that's because in this scenario, we are not using any index. So we call this structure as a heap structure.
18:30:50
힙 테이블은 클러스터형 인덱스가 없는 테이블입니다.
So a heap table is a table without a clustered index.
18:30:54
즉, 행이 특정한 순서 없이 무작위로 저장됩니다.
That means the rows are stored randomly without any particular order.
18:30:59
이것은 실제로 나쁘지 않습니다. 이 테이블에 데이터를 삽입하는 것이 매우 빠르기 때문입니다.
This is not really bad because it's going to be very quick to insert data inside this table.
18:31:05
하지만 물론, 이 테이블에서 무언가를 찾는 것은 매우 느릴 것입니다. 이것이 첫 번째 트레이드오프입니다.
But of course, finding something from this table is going to be very slow. So this is the first trade-off.
18:31:10
빠른 쓰기지만 읽기는 매우 느립니다.
You have a very fast writes but very bad reads.
18:31:15
모든 종이를 정리하지 않고 서랍에 던지는 것처럼 생각해 보세요.
Think about it like you are throwing all your papers in a drawer without organizing them.
18:31:20
서랍에 물건을 매우 빠르게 던질 수 있습니다. 하지만 나중에 특정 종이를 찾으려면 매우 오랜 시간이 걸릴 수 있습니다.
So you can toss things very quickly in this drawer. But if you want to search for a specific paper later, it can be very long process until you find it because nothing's in order.
18:31:30
이제 SQL이 이 테이블에서 무언가를 읽을 때 어떻게 처리하는지 봅시다. 고객 ID 14를 검색한다고 가정해 보겠습니다.
So now let's see how the SQL can handle if you read something from this table. Let's say that you are searching for the customer with the ID 14.
18:31:38
SQL은 이 고객을 찾는 방법을 전혀 모릅니다.
So now SQL has totally no idea where to find this customer.
18:31:42
SQL은 각 데이터 페이지를 가져오고 각 행을 스캔하기 시작할 것입니다.
So SQL is going to start fetching each data page and start scanning each row.
18:31:46
SQL은 첫 번째 데이터 페이지에서 시작하여 스캔을 시작합니다. 여기서 14를 찾지 못할 것입니다.
So it's going to start with the first data page and start scanning. Well, SQL will not find 14 here.
18:31:52
SQL은 다음 페이지로 이동하여 ID 14를 검색하면서 스캔을 계속합니다.
So SQL is going to go to the next page and start scanning as well, searching for the ID 14 and nothing going to be found.
18:31:58
세 번째 페이지에서도 같은 일이 발생합니다. SQL은 14를 찾지 못합니다.
The same thing for the third page as well. SQL will not find 14. So SQL is going to go to the last data page.
18:32:05
이 데이터 페이지에서 네 개의 행을 스캔한 후, SQL은 고객 번호 14를 찾게 됩니다.
And there after scanning four rows in this data page, finally, SQL is going to find the customer number 14 and it's going to return it for the clients.
18:32:13
고객을 찾기 위해 SQL은 네 개의 다른 페이지를 읽고 19개의 행을 스캔했습니다.
So as you can see, in order to find one customer, SQL did read four different pages and scanned like 19 rows in order to find the customer.
18:32:23
이 과정을 전체 테이블 스캔이라고 부릅니다.
And this process, we call it full table scan.
18:32:26
전체 테이블 스캔은 SQL이 특정 행을 찾기 위해 전체 테이블을 페이지별로, 행별로 스캔하는 것을 의미합니다.
So the full table scans means SQL is scanning the entire table page by page and row by row in order to find specific row.
18:32:35
이 테이블에서는 큰 문제가 아닐 수 있지만, 수십만 또는 수백만 개의 행이 있는 큰 테이블에서는
And of course, for this table, maybe it's not a big deal. But if you have like a big table where you have like hundreds of thousands or maybe millions of rows,
18:32:44
힙 구조를 검색하는 것은 매우 고통스럽고 느릴 수 있습니다.
searching through the heap structure can be very painful and slow in order to locate one row.
18:32:49
그래서 SQL 데이터베이스에서 인덱스가 필요한 이유입니다.
And here exactly why we need indexes in SQL databases.
18:32:53
첫 번째 유형의 인덱스인 클러스터드 인덱스를 이해해 봅시다.
So let's understand the first type of indexes, the clustered index.
18:33:01
클러스터드 인덱스를 생성하면 어떤 일이 발생하는지 이해해 봅시다.
all right so now let's understand what can happen if you create clustered index
18:33:04
고객의 ID 열에 클러스터드 인덱스를 생성한다고 가정해 보겠습니다.
in your table so say you create a clustered index on the id column of the customers so the first thing that can happen
18:33:12
모든 데이터를 물리적으로 정렬하게 됩니다.
is quill gonna physically sort all the data
18:33:15
ID 열을 기준으로 행이 재배열됩니다.
based on the column id so the rows gonna rearrange
18:33:18
각 데이터 페이지에서 가장 낮은 값부터 가장 높은 값까지 정렬됩니다.
in each data page from the lowest to the highest so on the first page we're gonna have the first
18:33:25
고객 ID 1, 2, 3, 4가 포함됩니다.
customer id number one then two three four
18:33:28
마지막 페이지에 도달할 때까지 계속됩니다.
five until we reach in the last page the last
18:33:31
고객 번호 20이 마지막 페이지에 있습니다.
customer number 20 so as you can see the first page has
18:33:34
가장 낮은 값과 마지막 페이지에는
the lowest value and the last page has the
18:33:37
가장 높은 값이 있습니다. 그래서 그게 전부는 아닙니다.
highest value so that's not all the
18:33:40
다음 단계는 이스라엘이 구조를 시작하는 것입니다.
next step is that israel gonna go and start structuring
18:33:44
그리고 B3를 구축하는 것입니다. B3는 균형 트리의 약자입니다. 데이터가 거꾸로 된 트리 형태로 저장되는 계층 구조입니다.
and building the b3 so what is a b3 a b3 short for balance tree it is hierarchical structure that stored the data as a tree upside down.
18:34:03
루트에서 시작하여 루트 노드가 되고 계속해서
It start with the root, the root node and then it keep
18:34:06
가지가 뻗어 나가 결국
branching out until we reach eventually the
18:34:09
리프 노드와 루트 노드 사이의 노드들
leaves between the leaf nodes and the root node we
18:34:12
이 섹션을 중간 노드라고 부르며, 루트와 리프 사이에 하나의 레벨 또는 여러 레벨이 있을 수 있습니다.
call this section the intermediate nodes so it could be like one level or multiple levels between the root and the leaves and
18:34:20
SQL이 B 트리를 구성하면, 특정 정보를 찾기 위해 B 트리를 탐색하는 것이 매우 쉬워질 것입니다.
And once SQL construct the B tree, it's going to be very easy for SQL to navigate through the B tree in order to find specific information.
18:34:28
그럼 SQL이 클러스터 인덱스를 위해 B 트리를 어떻게 구축하는지 살펴보겠습니다.
So let's see how SQL is building the B tree for the clustered index.
18:34:32
리프 노드와 클러스터 인덱스의 B 트리가 실제 데이터, 데이터 페이지를 포함한다는 것을 이해하는 것이 매우 중요합니다.
Now very important to understand that that the leaves, the leaf nodes and the B tree for the clustered index contain the actual data, the data pages.
18:34:42
따라서 여러분의 정렬된 데이터베이스와 데이터는 리프 레벨에 저장됩니다.
So all your nice sorted databases and your data is stored at the leaf level.
18:34:48
그 후 SQL은 중간 노드를 구축하기 시작할 수 있습니다. 여기서 데이터베이스는 다양한 유형의 페이지를 사용할 수 있습니다.
And after that SQL can start building the intermediate nodes. And here the database can use different type of pages.
18:34:55
우리는 인덱스 페이지가 있습니다. 인덱스
We have the index page. So in the index
18:34:58
페이지에서는 실제 데이터, 즉 전체 행을 찾을 수 없습니다.
page we cannot find the actual data the entire rows
18:35:01
대신 인덱스 페이지는 다른 인덱스에 대한 포인터를 포함하는 키
but instead the index page stores a key
18:35:05
값을 저장합니다.
value that contain a pointer to another index
18:35:08
예를 들어, 여기에서 우리는 키 값 하나가 있고, 그 값은 데이터 페이지의 ID가 될 것입니다. 따라서 여기에는 데이터에 대한 전체 행이 없고, 다른 데이터 페이지에 대한 포인터만 있습니다.
page or to a data page so for example we
18:35:11
따라서 여기서는 SQL에게 ID가 1과 5 사이에 있는 경우 데이터 페이지 ID 1:100에서 찾을 수 있다고 말하고 있습니다.
have here the value one the key and then the value gonna be the id of the data page so here we don't have like the whole row about the data we have here only a pointer to another data page.
18:35:23
그리고 이 인덱스 페이지에 또 다른 포인터를 저장할 수 있으며, SQL에게 ID가 6과 10 사이에 있는 경우 두 번째 데이터 페이지에서 찾을 수 있다고 말할 수 있습니다.
So here we are telling SQL if you are searching for IDs between one and five, you can locate it at the data page ID one double point 100.
18:35:32
이것이 인덱스 페이지의 구조입니다. 이 페이지는 다른 페이지에 대한 포인터만 포함합니다.
And then we can store in this index page another pointer where we can tell SQL if you are searching between six and 10, then you can locate it at the second data page.
18:35:43
두 번째 두 페이지도 마찬가지이며, SQL은
So this is the structure of the index page. It contains only pointers to another page.
18:35:48
ID가 11과 15 사이에 있는 경우 세 번째 페이지 1:102에서 찾을 수 있다고 말하는 또 다른 인덱스 페이지를 생성할 수 있습니다.
And the same thing for the second two pages, the SQL can
18:35:51
마지막 그룹인 16과 20 사이에는 마지막 페이지, 즉 페이지 번호 1:103에 대한 또 다른 포인터가 있습니다.
create another index page where it's going to say if you are searching for IDs between 11 and 15, you can find it at the third page one double point 102.
18:36:01
ID가 16과 20 사이에 있는 마지막 그룹에 대해 마지막 페이지 1:103에 대한 또 다른 포인터를 가지고 있습니다.
And for the last group between 16 and 20, we have another pointer to the last page to the page number one double point 103.
18:36:09
그래서 이 색인 페이지 안에는 각 클러스터의 각 ID 그룹에 대한 포인터가 있습니다.
So as you can see inside those index pages, we have like a pointer for each group of IDs for each cluster.
18:36:16
그래서 고객 그룹 1에서 5 사이에는 하나가 있습니다.
So for the group of customers between one and five, we have one
18:36:19
두 번째 그룹인 6에서 10 사이에는 포인터가 있습니다.
pointer and for the second group between six and ten we
18:36:22
여기에는 포인터가 없다는 것을 의미합니다.
have another pointer so that means we don't have here
18:36:25
각 행에 대한 포인터가 있습니다.
a pointer for each row we have a pointer
18:36:29
각 클러스터의 각 그룹에 대한 포인터가 있습니다.
for each group for each cluster that's why
18:36:32
클러스터형 색인이라고 부릅니다.
we call it clustered index now once a scale
18:36:35
중간 노드를 구축한 후 마지막 노드인 루트 노드를 구축합니다.
is done building the intermediate nodes it's going to go and build the last node the root node where it says if you are searching for customers between
18:36:43
고객을 검색하는 경우 1과 10 사이에 색인으로 이동합니다.
1 and 10 then go to the index
18:36:46
ID가 1.200인 페이지로 이동합니다.
page with the id 1.200 so
18:36:49
루트 노드가 다른 색인 페이지를 가리키고 있습니다.
that means the root node here is pointing to another
18:36:53
데이터 페이지가 아닌 색인 페이지를 가리킵니다.
index page not directly to the data page and
18:36:56
두 번째 색인에 대한 또 다른 포인터가 필요합니다.
the same thing we need another pointer for the second index
18:36:59
고객이 11에서 20 사이에 있습니다.
page so the customers between 11 and 20
18:37:02
ID가 1.201인 색인 페이지로 이동합니다.
go to the index page with the id 1.201 and
18:37:07
클러스터형 색인을 생성하면 데이터 페이지에서 모든 데이터를 물리적으로 정렬합니다.
this is exactly what can happen if you create a clustered index in sql first it's gonna go and physically sort all your data in the data pages.
18:37:17
SQL은 모든 것을 정렬하고 처음부터 데이터를 정렬해야 합니다.
So if it's from the first time sorted randomly, SQL has to arrange everything and sort the data from the scratch.
18:37:24
루트 노드에서 색인 페이지를 구축합니다.
And then it's gonna go and build this structure where you have in the root node, an index page in the intermediate nodes, the index pages,
18:37:32
리프 레벨에서 실제 데이터가 있습니다.
but at the leaf level, at the leaves, we have the actual data, the data pages.
18:37:37
이제 테이블을 쿼리할 때 어떤 일이 발생할 수 있는지 봅시다.
So now let's see what can happen if you query the table
18:37:41
ID 번호 14를 검색하는 경우입니다.
where you search for the id number 14 so it's going to
18:37:44
어떤 포인터를 사용할지 확인합니다.
check which pointer to use since 14 is in
18:37:47
11에서 20 사이의 그룹에 있습니다.
the group between 11 and 20 it's going to go and use the second
18:37:50
ID가 1.201인 색인 페이지로 이동합니다.
pointer to the index page with the id one double point
18:37:54
여기에서 SQL이 이 색인 페이지를 열고 포인터를 확인합니다.
201 and here the sql going to open this index page
18:37:57
그리고 포인터를 확인하니 14는 11과 15 사이에 있으므로 데이터 페이지 포인터를 사용하게 됩니다.
and check the pointers so since 14 is between 11 and 15 it's going to go and use the pointer to the data page one double
18:38:06
포인트 102와 함께 SQL은 올바른 데이터 페이지, 즉 세 번째 페이지를 찾았고 이제 SQL은 이 데이터 페이지를 열어 고객 ID 번호 14를 찾을 수 있습니다.
point 102 and with that sql located the correct data page the third page and now sql can open this data page and find the customer id number 14.
18:38:18
보시다시피 SQL이 매우 빠르게 올바른 데이터 페이지를 찾았습니다.
so as you can see it was very fast for sql to locate the
18:38:21
루트에서 세 번의 점프만으로 올바른 데이터 페이지로 이동했습니다.
correct data page with only three jumps from the root
18:38:24
중간 노드로의 노드에서 SQL은 빠르게 찾을 수 있었습니다.
node to the intermediate nodes the sql were able to find fast
18:38:27
올바른 데이터 페이지를 찾았고 여기서 SQL은 단지
the correct data page and here sql needs only to
18:38:30
하나의 데이터 페이지를 읽기만 하면 됩니다.
read one data page instead of reading as we saw
18:38:33
우리가 보았던 것처럼 여러 데이터 페이지를 읽는 대신에.
in the heap structure four different data pages and
18:38:37
힙 구조에서 서로 다른 네 개의 데이터 페이지와
of course you might say but still here we are reading like three pages
18:38:40
물론 여러분은 이렇게 말할 수 있습니다. 하지만 여전히 우리는 세 페이지를 읽고 있습니다.
well reading an index page is very fast compared to
18:38:43
인덱스 페이지를 읽는 것은 데이터 페이지를 읽는 것에 비해 매우 빠릅니다.
the data page because reading a data page is always
18:38:46
데이터 페이지를 읽는 것은 항상 인덱스 페이지를 읽는 것보다 느립니다.
slower than reading an index page so as you can see this
18:38:50
그래서 보시다시피 이 p3 구조는 클러스터형 인덱스 구조가
p3 structure the clustered index structure did
18:38:53
SQL과 데이터베이스가 올바른 데이터를 올바른 데이터 페이지에서 찾도록 도왔습니다.
help the sql and the database to locate the
18:38:56
불필요한 읽기 작업 없이 서로 다른 데이터베이스에서 이 클러스터형 인덱스가 SQL 데이터베이스에서 어떻게 작동하는지 정확히 보여줍니다.
right data in the right data page without having unnecessary read operations on different databases and this is exactly how that clustered index works in the sql database
18:39:12
좋습니다. 이제 두 번째 유형으로 넘어가서
all right so now we're gonna move to the second type and we're gonna understand how
18:39:15
SQL이 비클러스터형 인덱스를 어떻게 구축하고 생성하는지 이해해 보겠습니다.
exactly sql build and create the non-clustered
18:39:19
자, 이제 우리는 힙 구조로 돌아갑니다.
index so let's go so now we are back to the heap structure
18:39:22
우리 테이블에는 인덱스가 없고 데이터가
where our table don't have any index and our data
18:39:25
데이터 페이지 내에 무작위로 저장되어 있습니다. 이제 만약
are stored randomly inside the data pages and now if you
18:39:28
고객에 대한 비클러스터형 인덱스를 생성하면
go and create a non-clustered index on the customer
18:39:31
무슨 일이 일어날 수 있는지, 그리고 여기서 큰 차이가 있습니다.
id what can happen and here's the big difference that
18:39:34
SQL은 물리적인 실제 데이터에 대해
sql will not touch or change
18:39:37
아무것도 건드리거나 변경하지 않을 것입니다.
anything on the physical actual data
18:39:41
데이터 페이지는 그대로 유지되고 아무것도 변경되지 않으며 SQL은 즉시 B 구조를 구축하기 시작합니다.
on the data pages so the data page is gonna stay as it is and nothing gonna be changed and the sql start immediately building the B structure.
18:39:50
그래서 인덱스 페이지를 즉시 구축하기 시작할 것입니다. 이 인덱스 페이지는 우리가 이전에 배운 것과 조금 다릅니다.
So it's going to start immediately building an index page. And this index page is a little bit different than the one that we have learned previously.
18:39:57
그래서 인덱스 페이지이기 때문에 포인터를 설정하기 시작할 것입니다.
So since it's an index page, it's going to start pointing
18:40:00
하지만 이번에는 키인 고객 ID에서 시작할 것입니다. 그래서 하나는 고객 ID입니다.
But this time is going to start in the key, the customer ID. So one is the customer ID.
18:40:06
그리고 이제 값, 포인터는 데이터 페이지 ID가 아닙니다. 우리는 더 구체적으로 설명할 것입니다.
And now the value, the pointer, it will not be the data page ID. We will be more specific.
18:40:11
그래서 우리는 정확히 행이 저장된 주소를 가질 것입니다.
So we're going to have like an address where exactly the row is stored.
18:40:16
그래서 파일 ID와 페이지 번호로 시작할 것입니다. 고객 ID 하나는 페이지 1에 저장되어 있습니다, 더블 포인트 102.
So it's going to start with the file ID, the page number, because the customer ID one is stored in the page one, double point 102.
18:40:25
하지만 SQL은 행의 오프셋 번호도 추가할 것입니다.
But SQL is going to go add as well the offset number of the row.
18:40:29
페이지에서 이 ID를 정확히 찾을 수 있는 위치와
where exactly in the page we can find this id and
18:40:32
전체를 우리는 R ID라고 부를 수 있습니다.
the whole thing we can call it an r id the
18:40:36
행 식별자이므로 이제 인덱스 페이지가 어떻게
row identifier so now let's see quickly how the index page
18:40:39
내부의 행을 정확히 가리키는지 빠르게 살펴보겠습니다.
is pointing exactly to the row inside
18:40:42
데이터 페이지를 가리키고 있으므로 행 식별자의 첫 번째 부분은
the data page so the first part of the row identifier is
18:40:46
데이터 페이지 ID에 매핑되고, 그 다음에
mapping to the data page id and then from
18:40:49
96은 오프셋으로 가는 경로를 제공하며, 이는 행 번호 1의 정확한 위치입니다.
the 96 it's going to take us to the offset and that's exactly the location of the row number one so 96
18:40:56
96은 우리가 찾기 시작할 수 있는 부분입니다.
is the part where we can start finding the
18:40:59
행 번호 1과 정확히 연결되는 곳으로 가게 됩니다.
row number one and that's gonna takes us exactly to
18:41:03
정보를 읽을 수 있는 장소로 가게 됩니다.
the place where we can read the information about the
18:41:06
행 ID 번호 1에 대한 정보를 읽을 수 있는 장소입니다.
row id number one so this is how the index page
18:41:09
정확한 위치를 찾고 있습니다.
is locating the exact place of the
18:41:12
행들로 SQL은 계속 진행하여
rows so SQL can go and continue and assign
18:41:16
각 고객 ID에 정확한 위치에 대한 포인터를 할당합니다.
for each customer id a pointer to the exact location so as you can see now in the index page we don't
18:41:22
우리가 인덱스 페이지에서 볼 수 있는 것처럼
have like a pointer for each group of customers
18:41:25
각 ID에 대한 포인터가 있습니다.
like we have learned in the clusters index we have now
18:41:29
이 유형의 인덱스 페이지를 우리는 롤 로케이터 페이지라고 부릅니다.
a pointer for each id and this type of
18:41:32
그래서 이제 계속 진행하여 포인터를 매핑할 것입니다.
index page we call it role locator page
18:41:35
이제 계속해서 포인터를 매핑할 것입니다.
so now it's going to go and continue and map a pointer
18:41:38
우리 테이블에 있는 각 고객 ID에 대해
for each customer id that we have inside our table so
18:41:42
데이터 페이지를 가리키는 여러 인덱스 페이지가 생길 것입니다.
we will have multiple index pages pointing to our data page so as you can see we have a lot of
18:41:47
포인터와 인덱스 내부의 데이터가 있습니다.
pointers and the data inside the index
18:41:50
페이지는 물론 정렬되어 있지만 데이터 페이지 내부는
page is of course sorted but inside the data pages
18:41:54
그대로 두고 이제 그 인덱스 페이지가
it left as it is and now those index pages
18:41:57
원시 식별자를 저장할 수 있습니다.
that has the raw identifier can be stored
18:42:00
p3의 리프 레벨에서
at the leaf level of the p3 so
18:42:04
리프 레벨에서는 실제 데이터가 없고 데이터 페이지가
at the leaf level we don't have the actual data the data pages
18:42:07
포인터가 있는 인덱스 페이지가 있으며 실제 데이터로
we have index pages where we have pointers then to the actual data and then it's going to go and start building the
18:42:14
중간 노드를 구축하기 시작할 것입니다.
intermediate nodes it's exactly like the clustered index
18:42:17
클러스터 인덱스와 정확히 같습니다.
where it's going to point to another index page
18:42:20
다른 인덱스 페이지를 가리킬 것입니다.
so between one and five customers it's going to be in the
18:42:24
하나에서 다섯 고객 사이에 있을 것입니다.
index page number 200 so the next step is
18:42:27
인덱스 페이지 번호 200에서 다음 단계는
going to go and build the intermediate nodes it's going to be exactly like the
18:42:30
중간 노드를 구축하는 것입니다.
clustered index nothing going to be changed it's like the same
18:42:33
클러스터 인덱스와 같습니다.
structure so it is an index page pointing to another index page but this time for a group of customers and then we're going to have as well
18:42:41
구조는 인덱스 페이지가 다른 인덱스 페이지를 가리키는 것입니다.
the root node so again we call this structure as
18:42:44
고객 그룹을 위한 것입니다.
a p3 structure where they point to another
18:42:47
루트 노드입니다.
data pages but the data pages are not part
18:42:50
이 구조를 p3 구조라고 부릅니다.
of the p3 so now let's say if you are searching
18:42:53
그들은 다른 데이터 페이지를 가리킵니다.
for the customer id number 14 what's gonna happen
18:42:56
데이터 페이지는 p3의 일부가 아닙니다.
is going to start again from the root node and then
18:42:59
이제 고객 ID 번호 14를 검색한다고 가정해 보겠습니다.
it's gonna find the pointer to the intermediate node and then jump
18:43:02
무슨 일이 일어날까요?
to the next step to the intermediate node and then it's gonna find the pointer
18:43:06
11과 15 사이의 인덱스 페이지로
to the index page between 11 and 15 and
18:43:09
이 인덱스 페이지를 스캔할 것입니다 그리고
then it's gonna gonna go and scan this index page and
18:43:12
고객 ID 번호 14에 대한 정보를 찾습니다
find okay for the customer id number 14 we have
18:43:15
다음 주소를 찾습니다 그래서 정확한 위치를 찾을 것입니다
the following address so it's gonna go and locate the exact
18:43:18
데이터베이스와 정확한 위치를 찾습니다
database and as well the exact place of
18:43:22
행으로 즉시 점프할 수 있습니다
the row so it can go and jump immediately to the row
18:43:25
다른 것을 스캔하지 않고 여기서
without scanning anything else so here this time with
18:43:28
비클러스터 인덱스를 SQL이 읽었습니다
the non-clustered index the sql did read
18:43:31
세 가지 다른 인덱스 페이지와 마지막 데이터
three different index pages and finally the one data
18:43:34
데이터를 찾기 위한 페이지입니다 그래서 비교해보면
page in order to find the data so if you compare to
18:43:37
클러스터 인덱스와 비교할 수 있습니다
the clustered index you can see that we have here one extra layer
18:43:41
행의 정확한 위치를 찾기 위해 스캔할 추가 인덱스 페이지
one extra index page to be scanned in order
18:43:44
이것이 SQL이 비클러스터 인덱스에 대해 P3를 생성하는 방법입니다
to find the right place of the row and this is how sql
18:43:47
비클러스터 인덱스에 대해 P3를 생성합니다
creates the p3 for the non-clustered index
18:43:50
정보를 찾기 위해 스캔하는 방법입니다
and how it scans it in order to find the
18:43:53
모든 정보
information all
18:43:58
좋아요, 이제 클러스터형 인덱스와 비클러스터형 인덱스를 생각할 때 책을 떠올립니다. 클러스터형 인덱스는 목차와 같습니다.
right so now when i think about the clustered index and the non-clustered index i think about a book you can think of the clustered index like the table of contents
18:44:08
목차의 앞부분에 있으므로 목차가
at the front of the table so the table of contents gonna
18:44:11
각 장을 찾는 방법을 알려줍니다.
tells you where to find each chapter and the chapters
18:44:14
장들은 목차처럼 정확히 정렬되어 있습니다.
are exactly sorted like the table of contents
18:44:17
그리고 이것이 바로 클러스터형 인덱스가 하는 일입니다. 하지만
and this is exactly what the clustered index does but
18:44:21
이제 반면에 비클러스터형 인덱스는
now on the other hand think about the non-clustered index as
18:44:24
책의 끝에 있는 인덱스처럼 생각할 수 있습니다. 책의 인덱스는 주제, 용어 및 키워드의 매우 자세한 목록입니다.
the index that you can find at the end of the book the index of the book is a very detailed list of topics terms and keywords
18:44:34
어디에서 찾을 수 있는지를 정확히 가리킵니다.
where it points exactly to the location where you can find
18:44:37
책의 내용과 주제에 대해
it in the book and the content and the topic of
18:44:40
책은 책의 색인처럼 정렬되지 않습니다.
the book is not sorted like the index of the book
18:44:43
그리고 이것이 비클러스터 인덱스가 하는 일입니다.
and this is exactly what the non-cluster index does it
18:44:46
데이터와 함께 공존하는 추가 목록입니다.
is co-existing with the data it is an extra list
18:44:50
우리가 데이터를 찾을 수 있는 정확한 위치를 가리킵니다.
where it can point exactly where we can find the data
18:44:53
우리 테이블 안에 있습니다. 자, 이제 이 두 가지를
inside our table all right so now let's put those two
18:44:56
나란히 놓아 이들 간의 차이를 이해해 봅시다. 클러스터 인덱스의 구조는 P3입니다.
indexes side by side to understand the differences between them so the structure of the clustered index is a P3 where it starts with the root node where we have an index page.
18:45:06
이 인덱스 페이지는 중간 노드를 가리키고 있습니다.
This index page is pointing to the intermediate nodes where we have as well index pages.
18:45:11
그 인덱스 페이지는 실제 데이터, 데이터 페이지를 가리킵니다.
And those index pages are pointing to the actual data, to the data pages.
18:45:16
클러스터 인덱스의 실시간 수준에서 데이터 페이지, 실제 데이터가 있습니다.
So at the live level of the clustered index, we have the data pages, the actual data.
18:45:21
클러스터 인덱스의 특징은 데이터 페이지 내에서 데이터를 물리적으로 정렬한다는 것입니다.
Now, what's special about the cluster index is that it physically sort the data inside those pages.
18:45:27
여기 모든 것이 물리적으로 재배치되고 정렬됩니다.
So everything here is physically rearranged and sorted.
18:45:31
비클러스터 인덱스에 대해 이야기하고 있다면, P3도 있습니다.
Now if you are talking about the non-clustered index, we have as well a P3.
18:45:35
루트 노드와 같은 방식으로, 인덱스 페이지가 중간 인덱스 페이지를 가리킵니다.
So the same thing as a root node, we have an index page pointing to an intermediate index page.
18:45:41
이번에는 중간 노드가 다른 인덱스 페이지를 가리킵니다.
But this time the intermediate nodes are pointing to another index page.
18:45:46
클러스터 인덱스의 리프 레벨에서 실제 데이터, 데이터 페이지가 있습니다.
They are not pointing like the cluster index to a data page. are pointing to index page.
18:45:52
반면 비클러스터 인덱스의 리프 레벨에서는 실제 데이터가 없고 인덱스 페이지가 있습니다.
So now if you check this structure, you can see that at the leaf level for the clustered index, we have the actual data, the data pages.
18:45:59
하지만 그 인덱스 페이지는 실제 데이터, 데이터 페이지를 가리킵니다.
But on the other side, at the leaf level for the non-clustered index, we don't have the actual data, we have index pages.
18:46:05
큰 차이점은 데이터 페이지가 P3의 일부가 아니라는 것입니다.
But those index pages are pointing to the actual data, to the data pages.
18:46:11
비클러스터 인덱스의 P3는 단지
But the big difference of that, the data pages are not part of the P3.
18:46:16
데이터를 포함하지 않는 별도의 구조입니다.
The P3 of the non-clustered index is just a
18:46:19
우리는 오직 인덱스 페이지만 있고 그것은
separate structure that does not involve any data
18:46:22
데이터 페이지를 가리키지만 아무것도 변경하지 않습니다.
so we have only index pages and it
18:46:25
물리적으로 데이터와 함께 있지만 실제로는
just points to the data pages without changing anything
18:46:28
이 두 가지 유형의 인덱스를 가질 수 있습니다.
physically with your data but in reality
18:46:31
클러스터 인덱스와 비클러스터 인덱스입니다.
what happened is that you can have those two types of
18:46:35
클러스터형 및 비클러스터형 인덱스
indexes the clustered and the non-clustered indexes in
18:46:38
하나의 테이블에서 비클러스터형 인덱스의 리프 레벨이
one table so what can happen the leaf level of the non-clustered index can be pointing to the
18:46:45
클러스터형 인덱스의 데이터 페이지를 가리킬 수 있습니다.
data pages of the clustered index because those index
18:46:48
페이지가 정렬되어 있는지 여부는 신경 쓰지 않습니다.
pages don't care whether those pages are sorted
18:46:52
그냥 올바른 페이지를 가리키게 됩니다.
or not it's just gonna go and point to the correct
18:46:55
데이터를 가리키는 두 가지 다른 B3 구조가 있습니다.
page and to the correct rule so that means we have now like
18:46:58
테이블에 클러스터형 인덱스를 하나만 생성할 수 있습니다.
two different b3 structures that are pointing to the data and here there is like one thing that you have to understand that that you can create only one clustered index on a table
18:47:10
데이터를 정렬할 수 있는 방법이 하나뿐입니다.
and this rule really makes sense because you can sort the data only in
18:47:14
물리적으로 데이터를 한 번만 정렬할 수 있습니다.
one way in sql and that's of course makes sense because
18:47:17
SQL 데이터베이스에서는 클러스터형 인덱스를 하나만 생성할 수 있습니다.
you can sort the data physically only once and that's
18:47:20
물리적으로 데이터는 한 가지 방법으로만 정렬될 수 있습니다.
why in sql databases you are allowed to create only one
18:47:23
클러스터형 인덱스는 한 가지 방법으로만 정렬됩니다.
clustered index because physically the data can be sorted
18:47:27
한 가지 방법만이 아니라 다른 방법에서도
only in one way but in the other hand in the
18:47:30
비클러스터형 인덱스는 동일한 데이터 페이지를 가리킵니다.
non-clustered index you can create as many non-clustered index you need so you can create three four and all of them are pointing to the
18:47:38
비클러스터형 인덱스는 데이터 페이지를 저장하지 않습니다.
same data pages because in the p3 of the non-clustered
18:47:41
데이터에 대한 포인터만 저장합니다.
index you don't store any data pages we store
18:47:44
가장 중요한 차이점입니다.
only pointers to the data and you could have like multiple pointers
18:47:47
두 인덱스의 주요 차이점입니다.
so this is the most important and the main difference
18:47:51
클러스터형 인덱스는 물리적으로 정렬됩니다.
between those two indexes now if you put it side by side we have
18:47:54
클러스터형 인덱스는 P3에서 행을 정렬하고 저장합니다.
learned that the clustered index gonna go and physically
18:47:57
비클러스터형 인덱스는 별도의 P 구조를 생성합니다.
sorts and stores the rows at the p3 but
18:48:01
실제 데이터에 대한 포인터를 포함합니다.
the non-clustered index is gonna go and create a separate p structure with pointers to the actual
18:48:07
클러스터형 인덱스를 주요 인덱스라고 부릅니다.
data and by the way the clustered index we call
18:48:10
각 테이블에서 사용할 수 있는 주요 인덱스입니다.
it the main index that we could use in
18:48:13
가장 중요한 인덱스입니다.
each table so the clustered index is the main
18:48:16
가장 중요한 것 중 하나입니다.
one the most important one that you can go and use
18:48:19
이제 데이터베이스의 각 테이블에서
in each table in your database now as we learned if
18:48:22
최대 생성할 수 있는 인덱스의 수에 대해 이야기하고 있습니다.
you are talking about the number of indexes you can create maximum
18:48:26
각 테이블에 하나의 인덱스가 있지만 비클러스터 인덱스의 경우
one index for each table but for the non-clustered
18:48:29
제한이 없으며 각 테이블에 대해 여러 인덱스를 생성할 수 있습니다.
index there is no limitations you can go and create multiple indexes for each table and now if you go and compare them
18:48:36
읽기 성능에 대해 이야기하고 있습니다.
about the read performance how fast we can get data
18:48:39
클러스터 인덱스를 사용하면 더 빠릅니다.
using clustered index well it is faster
18:48:42
비클러스터 인덱스보다 더 빠릅니다.
than the non-clustered index and that's because in
18:48:45
비클러스터 인덱스에는 이 추가 레이어가 있습니다.
the non-clustered index we have this extra layer at the
18:48:49
p 트리의 리프 노드에서 이로 인해
leaf node from the p tree and because of this
18:48:52
추가 레이어가 있으면 SQL이 추가 작업을 해야 합니다.
having extra layer that means sql has to do extra job
18:48:56
데이터를 찾기 위해 클러스터 인덱스가 더 빠릅니다.
in order to find the data that's why clustered index is faster
18:48:59
비클러스터 인덱스보다 더 빠릅니다. 하지만 이제 반대로
than the non-clustered index but But now in the other hand, if we are talking about the right performance, how fast we can insert data to the tables?
18:49:08
올바른 성능, 즉 테이블에 데이터를 얼마나 빨리 삽입할 수 있는지에 대해 이야기하고 있습니다.
Well, writing data to a table with a clustered index is slower than the non-clustered index.
18:49:14
클러스터 인덱스를 가진 테이블에 데이터를 쓰는 것은 비클러스터 인덱스보다 느립니다.
And that's because as you are inserting data to the table, SQL has always to check the data pages.
18:49:20
테이블에 데이터를 삽입할 때 SQL은 항상 데이터 페이지를 확인해야 합니다.
Is everything sorted correctly? And if not, SQL has to go and start physically sorting the data again in order to have the correct order.
18:49:29
모든 것이 올바르게 정렬되어 있습니까? 그렇지 않으면 SQL이 데이터를 다시 정렬해야 합니다.
So there is a lot of stress in order to sort the data with the clustered index. But in the other hand, in the non-clustered index, we don't have this.
18:49:36
클러스터 인덱스와 함께 데이터를 정렬하는 데 많은 스트레스가 있습니다.
So the physical data is going to stay as it is. We are just creating nice new pointers.
18:49:42
비클러스터 인덱스에서는 이러한 문제가 없습니다.
So if you are writing to a table where you have a clustered index, it's going to be slower than writing to a table where you have non-clustered index.
18:49:49
물리적 데이터는 그대로 유지됩니다.
And of course, the fastest way to write data to a table is to not have indexes at all. So a heap structure.
18:49:57
단순히 새로운 포인터를 생성하고 있습니다.
So SQL just go and start inserting data inside
18:50:00
클러스터 인덱스가 있는 테이블에 쓰면 느려집니다.
those data pages without creating any extra structures
18:50:04
비클러스터 인덱스가 있는 테이블에 쓰는 것보다.
so as you can see it's like always a trade-off you
18:50:07
인덱스가 전혀 없는 테이블에 데이터를 쓰는 것이 가장 빠릅니다.
can read fast but you can write slower so you cannot
18:50:10
힙 구조입니다.
have like everything now we are talking about the storage
18:50:13
효율성 클러스터 인덱스가 더 나을 것입니다
efficiency the cluster index is going to be better
18:50:16
저장소에 비해 비클러스터 인덱스가 더 나은 이유입니다
with the storage than the non-clustered index and that's because
18:50:19
비구조화 인덱스와 같은 이유로
of the same reason with the non-structured index we have
18:50:22
이 추가 인덱스 페이지와 인덱스 페이지가 필요하고
this extra layer of index pages and index pages
18:50:25
그래서 그들은 클러스터 인덱스보다 더 많은 저장소를 낭비할 수 있습니다
needed storage and that's why they can waste more storage than
18:50:29
클러스터 인덱스에 대해 이야기하고 있다면
the clustered index now if you are talking about the use cases
18:50:32
클러스터 인덱스를 사용할 때는
when to use clustered index well if you have like a column
18:50:35
이 열은 몇 가지 기준을 충족해야 합니다
this column has to have a few criteria in order to
18:50:38
클러스터 인덱스의 좋은 후보가 되려면 먼저
be good candidate for the clustered index first it's going
18:50:41
열 안의 값이 고유해야 하고, 두 번째로 이 열의 값은 자주 변하지 않아야 합니다
to be good if the values inside the columns are unique and second and it is way more important than that the values of this column should not change a lot
18:50:51
이 열이 많은 업데이트 연산자를 가지고 있고 데이터가 계속 변경된다면
Because if this column having a lot of update operators and the data is keep changing, that means each time SQL is going to go and start sorting the data again left and right.
18:51:02
그래서 자주 변경되는 열은 클러스터와 인덱스에 좋지 않습니다
So having a column that is frequently changing, it's not good for clusters and dicks.
18:51:07
그래서 테이블의 기본 키가 완벽한 후보입니다. 첫째, 그들은 고유합니다
And that's why the primary keys of tables are a perfect candidate. Because first, they are unique.
18:51:13
둘째, 우리는 기본 키 값을 업데이트하지 않습니다
And second, we will never go and update a primary key value. We always append a new primary key value.
18:51:20
그래서 기본 키가 클러스터 인덱스에 완벽한 이유입니다
And that's why primary keys are perfect for clustered index.
18:51:23
또한 클러스터 인덱스를 사용하는 또 다른 이유는 범위 쿼리의 성능을 최적화하기 위해서입니다
And one more thing where I go and use clustered index is that to optimize the performance of a range query.
18:51:30
하나의 값과 다른 값 사이의 데이터를 쿼리할 때 클러스터 인덱스는 매우 잘 작동합니다
If you are querying the data between one value and another one, clustered index works really well.
18:51:35
비클러스터 인덱스에 대해 이야기한다면
Now, in the other hand, if we are talking about the non-clustered index, we could use it on columns that are used in the search conditions.
18:51:42
또는 기본 키를 사용하지 않고 테이블을 조인할 때
Or if you are joining tables without using the primary keys, then you can go and apply the non-clustered index in order to have faster joins.
18:51:49
정확한 값, 정확한 일치를 검색할 때 성능을 최적화하는 데 사용할 수 있습니다
or you can go and use it to optimize the performance if you are searching for an exact value, exact match.
18:51:56
그래서 클러스터와 비클러스터 인덱스 간의 주요하고 중요한 차이점입니다
So those are the main and important differences between the clustered and the non-clustered indexes.
18:52:05
좋습니다, 이제 SQL로 가서 연습하기 전에
All right, so now before we go to SQL and start practicing, I would like to show you the syntax of the index. So it's very, very simple.
18:52:12
인덱스의 구문을 보여드리고 싶습니다
It starts with create and then we can define whether it is clustered or non-clustered.
18:52:19
create로 시작하고 클러스터인지 비클러스터인지 정의할 수 있습니다
and then the keyword index but this section is optional
18:52:22
그래서 아무것도 정의하지 않으면 기본값은 비클러스터가 될 수 있습니다
so if you don't define anything the default can
18:52:25
비클러스터 인덱스가 기본값이 될 수 있습니다.
be the non-clustered so if you say create index
18:52:29
SQL 서버가 비클러스터 인덱스를 생성합니다.
the sql server gonna go and create non-clustered index
18:52:32
인덱스의 이름을 정의해야 합니다.
then after that we have to go and define the name of the index and then we have to tell sql which table we have to create the index in on table name and then we can go and define
18:52:44
인덱스에 대해 하나의 열 또는 여러 열을 정의합니다.
one column or multiple columns for the index and
18:52:47
여러 열로 구성된 인덱스를 복합 인덱스라고 합니다.
we call an index with multiple columns as composite
18:52:50
예를 들어, 클러스터 인덱스를 생성할 수 있습니다.
index so for example we can go and create a
18:52:53
클러스터 인덱스를 생성하는 명령을 사용합니다.
clustered index using this command create clustered
18:52:56
인덱스 이름을 지정한 후 테이블과 ID를 지정합니다.
index the index name and then we specify the
18:52:59
고객 테이블의 ID를 기반으로 클러스터 인덱스를 생성합니다.
table and the id so we are saying create clustered
18:53:03
비클러스터 인덱스를 생성하려면 비클러스터 인덱스를 생성합니다.
index based on this column the id from the table customers
18:53:06
하나의 열을 사용하고 있지만 복합 인덱스를 생성할 수 있습니다.
and if we want to create a non-clustered index you say create non-clustered index and the same thing so so far
18:53:13
여러 열로 구성된 복합 인덱스를 생성할 수 있습니다.
we are using one column in the index, but we can go and create a composite index with multiple columns like the following example.
18:53:20
기본값이 비클러스터 인덱스가 될 것입니다.
So we can say create an index. And as you can see, we skipped here defining the type.
18:53:24
여기서 두 개의 열, 성과 이름을 지정합니다.
And that's because the default going to be non clustered index.
18:53:28
SQL에서 데이터를 정렬하는 방법을 지정합니다.
And now here we are specifying two columns, the last name and the first name.
18:53:32
성은 데이터 내에서 정렬되어야 합니다.
And as you can see, we specifying as well for SQL, how to sort the data.
18:53:37
페이지는 오름차순으로 정렬됩니다.
So we are saying last name should be sorted inside the data
18:53:40
이름은 반대로 정렬되어야 합니다.
page ascending lowest to the highest but
18:53:43
최고에서 최저로 정렬할 수 있습니다.
the first name should be the way around from the highest
18:53:47
데이터 페이지에서 물리적으로 정렬됩니다.
to the lowest so you can control how the data can be sorted
18:53:50
인덱스를 생성하는 구문은 매우 간단합니다.
physically in the data page so as you can see it is very
18:53:53
SQL로 돌아가서 첫 번째 질문은 어디인가요?
simple this is the syntax for creating index in sql
18:53:56
데이터베이스에서 인덱스를 찾을 수 있습니다.
all right so back to sql and the first question is where
18:53:59
여기서 개체 탐색기로 이동하여 탐색할 수 있습니다.
do we find indexes in the database well you
18:54:03
예를 들어 고객 테이블을 확인할 수 있습니다.
can go and explore it if you go to the object explorer over here and
18:54:06
예를 들어 고객과 같은 우리의 판매 데이터베이스에서 테이블을 확인할 수 있습니다.
check any tables from our sales db for example the customers and
18:54:09
여기 인덱스라는 폴더가 있으니 확장하면
here you have a folder called indexes so if you expand it
18:54:12
여기 내가 만들지 않은 인덱스를 찾을 수 있습니다.
you will find here an index i didn't create
18:54:15
데이터베이스의 인덱스 중 하나이지만 이스라엘 세이버에서
any of those indexes in the database but in israel saver
18:54:19
열 중 하나를 기본으로 정의하면
if you define any of the columns as a primary
18:54:22
이스라엘 세이버가 기본적으로 사용할 키입니다.
key that israel saver gonna go by default
18:54:25
클러스터형 인덱스를 생성하는 중입니다.
creating a clustered index for the
18:54:28
기본 키에 대해 클러스터형 인덱스를 생성하는 것이 항상 의미가 있기 때문에, 기본 키에 대해 기본적으로 생성됩니다. 처음에 고객의 기본 키가 있고, 그것이 클러스터형으로 설정되어 있습니다.
primary key because it makes always sense to create a clustered index on the primary key so this one is created as a default and as you can see at the start we have like a key primary key customer and then it is clustered.
18:54:39
이제 처음부터 시작하고 싶습니다. 그래서 인덱스 없이 새 테이블을 생성하고 싶습니다.
Now I would like to start from the scratch. That's why I would like to go and create a new table without any indexes.
18:54:45
우리가 할 일은 고객 테이블을 새 테이블로 로드하는 것입니다.
So what we're going to do, we're going to go and load the table customers into a new table.
18:54:49
그걸 어떻게 할 수 있을까요? sales customers에서 select star를 사용할 것입니다.
So how we can do that, we're going to go and say select star from sales customers.
18:54:57
from 앞에 새로운 테이블로 넣겠다고 말할 것입니다.
And before the from, we're going to say into a new table so it's going to be
18:55:02
db customers로, 이렇게 합시다.
db customers so like this let's
18:55:05
계속 진행하고 실행해 보겠습니다. 이제 왼쪽으로 가서 새로 고침을 하면
go ahead and execute it so now if you go to the left side and refresh
18:55:08
테이블에서 이제 db customers라는 새 테이블을 찾을 수 있습니다.
the tables you can find we have now a new table called
18:55:12
이제 인덱스가 있는지 확인해 보겠습니다. 인덱스는 비어 있으므로 아무것도 없습니다.
db customers now let's go and check whether we have any indexes inside it so indexes it is empty so we don't have anything no
18:55:20
클러스터형 인덱스도 없고 다른 것도 없으며 이 테이블은
clustered index or anything else and this table has the
18:55:23
힙 구조의 구조를 가지고 있습니다. 그래서
structure of heap structure so the
18:55:26
데이터가 무작위로 삽입되며 정렬되지 않았습니다.
data are inserted there randomly it is not sorted and
18:55:30
여기서 예를 들어, 고객 ID가 1인 것을 선택한다고 가정해 보겠습니다.
if i go over here and for example let's say i'm going to
18:55:33
이 새 테이블에서 선택하고
select from this new table where
18:55:37
고객 ID가 1과 같고
customer id equal one and
18:55:40
실행하면 SQL 서버가 이 고객 ID를 찾기 위해 테이블에서 전체 스캔을 수행했습니다. 그래서 우리의 새 테이블 db customers는
i execute it the sql saver did a full scan on the table in order to find this customer id so our new table db customers is
18:55:50
힙 클러스터입니다. 하지만 그것을 변경해 보겠습니다. 우리가 할 일은
heap cluster but let's go and change that what
18:55:53
새 클러스터형 인덱스를 생성하는 것입니다.
we're going to do we're going to go and create a new clustered index so
18:55:56
클러스터 인덱스를 생성하겠습니다.
we're going to say create clustered index
18:56:01
그런 다음 인덱스의 이름을 지정하겠습니다.
and then we're going to go and give it a name for the index we
18:56:04
일반적으로 다음과 같은 인덱스를 따릅니다. 인덱스는 접두사로 사용하고 그 다음에 테이블 이름을 지정합니다. 예를 들어 db customers와 인덱스 키를 사용합니다.
usually follow the following index so we have index as prefix and then after that we specify the table name so db customers and then the key for the index
18:56:15
테이블을 인덱싱하는 데 사용하는 열입니다.
So the column that you are using in order to index the table.
18:56:18
인덱스 이름에 대해 동일한 명명 규칙을 유지하는 것이 중요합니다. 나중에 인덱스를 모니터링할 때 이해하기가 매우 쉬워질 것입니다.
This is important to stick with the same naming convention for the index name, because later as you are monitoring your indexes, it's going to be really easy to understand.
18:56:26
좋습니다. 이 인덱스는 DB customers 테이블을 위한 것이며, 고객 ID를 인덱싱하는 데 사용합니다.
Okay, this index is for the table DB customers, and we are using the customer ID to index.
18:56:32
이제 어떤 테이블에서 인덱스를 수행할지 지정하겠습니다.
So now after that, we're going to go specify on which table we are doing the index.
18:56:36
판매 DB 고객 테이블에서 인덱스를 지정하겠습니다.
So on sales DB customers, and then we're going to specify that column name.
18:56:44
고객 ID를 기반으로 클러스터 인덱스를 생성하라고 요청하고 있습니다. 이제 실행해 보겠습니다.
So we are saying build for me a clustered index based on the customer ID. So now let's go and execute it.
18:56:50
보시다시피, 데이터가 5행밖에 없기 때문에 매우 빠릅니다. 데이터베이스가 모든 데이터 페이지를 매우 빠르게 전환했습니다.
So as you can see, it's very fast because we have only five rows. So the database just switched all the data pages very fast.
18:56:57
이제 새 인덱스를 확인해 보겠습니다. 새로 고침하고 들어가 보겠습니다.
Now let's go and check our new index. So let's go and refresh and let's go inside it.
18:57:02
이제 고객 ID를 기반으로 한 새 클러스터 인덱스가 생성된 것을 볼 수 있습니다.
And now we can see that we have our new index clustered index based on the customer ID.
18:57:07
이제 우리는 여러 개의 클러스터 인덱스를 생성할 수 없다는 것을 배웠습니다. 이를 테스트해 보겠습니다.
Now, as we learned, we cannot create multiple clustered index, but let's go and test that.
18:57:12
전체를 가져와서 여기서 이름으로 클러스터 인덱스를 생성하고 싶다고 가정해 보겠습니다.
So I will just take the whole thing and let's say I would like to create a clustered index based on the first name as well here.
18:57:23
실행해 보겠습니다. SQL이 이 테이블에서 클러스터 인덱스를 하나 이상 생성할 수 없다고 말하고 있습니다.
So let's go and execute it. So as you can see, SQL is saying you cannot create more than one clustered index on this table.
18:57:31
즉, 클러스터 인덱스를 하나만 생성할 수 있습니다. 인덱스를 생성한 후 잘못된 열을 선택했으며 이름으로 변경하고 싶다고 가정해 보겠습니다.
That means we can create only one clustered index. And let's say that after you created the index, you chose the wrong column and you would like to change it to the first name.
18:57:41
우리가 해야 할 일은 인덱스를 삭제하는 것입니다.
so what we're gonna do we have to go and drop the index
18:57:44
인덱스를 삭제하라고 말합니다.
so we say drop index and
18:57:47
그런 다음 인덱스 이름이 필요합니다. 이 인덱스입니다.
then you need the index name it was this one
18:57:51
어떤 테이블을 지정해야 합니다. 그래서
and then you have to specify which table so
18:57:54
판매 tb 고객 테이블이 될 것입니다.
it's gonna be sales tb customers like
18:57:58
이렇게 하면 새로 고침하면 더 이상 인덱스가 없고 테이블이 힙 구조로 돌아갑니다.
this so if i do it like this and let's
18:58:02
이것에 대한 올바른 클러스터 인덱스를 생성할 수 있습니다.
go and refresh again you can see that we don't have any indexes anymore and the table is backed as a heap structure and now you can go and
18:58:09
솔직히 고객 ID로 유지하겠습니다.
create the correct clustered index for this
18:58:12
이름에 클러스터 인덱스를 생성하지 않겠습니다.
table but to be honest i'm gonna stick with the customer id so
18:58:16
첫 이름에 클러스터형 인덱스를 만들지 않을 것입니다. 왜냐하면
i will not create a clustered index on the first name because
18:58:19
첫 이름은 고유하지 않기 때문에 여러 고객이 같은 이름을 가질 수 있습니다.
the first name of course is not unique you can have like maybe multiple
18:58:22
같은 이름을 가진 고객이 있을 수 있고 업데이트도
customers having the same name and as well updates
18:58:25
첫 이름에서 발생할 수 있으며 이는 매우 비용이 많이 들 것입니다.
could happen in the first name and that's going to be very expensive
18:58:28
즉, 고객 ID에 대한 인덱스를 유지할 것입니다.
so that means i'm going to stick with my index on the
18:58:31
고객 ID에 대한 인덱스를 유지할 것이며 이제
customer id let's go and execute it and now i have
18:58:34
다시 내 테이블에 인덱스가 있습니다. 이제 테이블에서 다음 선택 문을 가지고 있다고 가정해 보겠습니다.
again my index on my table now let's say that that i have the following select statements from our tables so customers
18:58:46
그리고 성을 검색하고 있습니다.
and i'm searching for the last name where
18:58:49
브라운을 검색하고 있다고 가정해 보겠습니다. 실행해 보겠습니다. 고객이 점점 더 많아지고
let's say we are searching for brown so let's go and execute it so let's say that we are getting more and more customers and our table is getting bigger
18:58:57
테이블이 커지고 있습니다.
and i frequently use this query so
18:59:00
이 쿼리를 자주 사용합니다.
i'm searching for specific customers using the last name
18:59:03
특정 고객을 성으로 검색하고 있습니다.
so what you can do we can go and create a non-clustered
18:59:06
비클러스터형 인덱스를 생성할 수 있습니다.
index for the last name in order to improve the performance of this query so let's go and create that so we're going to say create non-clustered
18:59:15
성에 대한 인덱스를 생성하여 이 쿼리의 성능을 개선할 수 있습니다.
index and now we're going to give it the name using the
18:59:18
이 인덱스의 이름을 지정할 것입니다.
naming convention so db customers and we're
18:59:22
이름 지정 규칙을 사용하여 db 고객으로
going to use the last name for this index so on sales db customers and we will use the column last name for the index.
18:59:32
이 인덱스에 성을 사용할 것입니다.
So let's go and execute it.
18:59:35
이제 실행해 보겠습니다.
And now if you go to our indexes and refresh, we will find our new index over here.
18:59:41
이제 인덱스로 가서 새 인덱스를 찾을 수 있습니다.
And as you can see, it says it is none clustered and as well, none unique. We will talk about the uniqueness later.
18:59:47
보시다시피, 비클러스터형이며 고유하지 않다고 표시됩니다.
So as you can see, it's very easy. We have just created a non-clustered index on the last name.
18:59:52
고유성에 대해서는 나중에 이야기하겠습니다.
And now as we learned, we can go and create multiple non-clustered index on the same table.
18:59:57
예를 들어, 이제 우리는 우리의.
Let's say, for example, now we our.
19:00:00
쿼리는 이렇게 생겼고 우리는 첫 번째를 검색하고 있습니다.
query looks like this we are searching for the first
19:00:03
이름을 예를 들어 값이 안나인 경우 이제 이
name using for example the value anna and now this
19:00:06
쿼리는 자주 발생하고 아마 느릴 수 있으므로 우리는 가서
query happens a lot and maybe slow so we can go and
19:00:09
새로운 비클러스터 인덱스를 생성합니다.
create a new non-clustered index so
19:00:12
이렇게 하고 비클러스터 인덱스를 위해
let me just have it like this and for the non-clustered
19:00:15
비클러스터 인덱스를 항상 지정할 필요는 없습니다.
index you don't have to specify always like non-clustered index
19:00:18
기본값으로 비클러스터 인덱스가 됩니다.
as default it's going to be non-clustered so we can skip
19:00:22
여기서 첫 번째 이름이라고 부릅시다.
that and here let's call it first name
19:00:25
우리가 사용하는 열은
and the column that we are using is the
19:00:28
첫 번째 이름이므로 진행합시다.
first name so let's go
19:00:31
이 인덱스를 생성하고 이제 새로 고침합시다.
and create this index and now let's go and refresh
19:00:34
우리의 인덱스와 SQL이 첫 번째 이름에 대한 비클러스터 인덱스를 생성했습니다.
our indexes and as you can see sql did create a non-clustered index for the first name so if you don't specify the type of the index it's going to be as a default non-classered index.
19:00:50
좋습니다. 이제 복합 인덱스에 대해 이야기해봅시다.
All right, so now let's talk about the composite index. It is an index that has multiple columns inside the same index.
19:00:57
지금까지 인덱스에서 하나의 열만 사용했습니다.
So far, we have used only one column in the index, but we can go and specify multiple columns.
19:01:04
때때로 WHERE 조건이 복잡하기 때문입니다.
And that's because sometimes our where conditions are complicated and based on multiple columns.
19:01:10
예를 들어, 국가가 미국인 경우를 가정해봅시다.
So, for example, let's say that we are searching for country equal to USA.
19:01:16
동시에 점수가 500보다 커야 한다고 말하고 있습니다.
And at the same time, we are saying the score should be higher than 500.
19:01:21
이 조건에서는 두 개의 열을 사용하고 있습니다.
So, that means in this condition, we are using two columns and we would like to speed up this query. So, how are we going to do it?
19:01:27
인덱스를 생성하고 이름을 지정하겠습니다.
So, we're going to go and create, let's say, an index and give it a name.
19:01:32
DB 고객과 국가를 지정하겠습니다.
DB customers and let's say country
19:01:36
판매에 대한 점수입니다.
score on sales
19:01:39
DB 고객과 이제
DB customers and now
19:01:42
지금 다음 작업을 수행하는 것이 매우 중요합니다
it is very important to do the following thing now
19:01:45
우리는 가서 정의해야 합니다 열 목록을
we have to go and define a list of columns that
19:01:49
이 인덱스에 포함되기를 원하는 것이며, 쿼리와 동일한 순서를 얻는 것이 매우 중요합니다.
you want to be included in this index and it is very crucial and important that you get the same order as your query so your
19:01:58
쿼리는 국가로 시작하고 그 다음에 점수가 옵니다.
query start with the country and then the score
19:02:01
인덱스에서도 동일한 작업을 수행해야 합니다.
you have to do it the same thing in the index so
19:02:04
첫 번째 열은 국가가 되고 그 다음은
the first column is going to be the country and then the
19:02:07
점수는 같은 순서여야 합니다
score so it must be the same order as
19:02:11
당신의 쿼리를 기반으로 이 인덱스를 생성합시다
your query so let's go and create this
19:02:14
인덱스를 생성하면 테이블은 다음과 같아질 것입니다
index and if you go to the indexes over here you can see that we have created our new index so now once you create such an index and your table gonna be like
19:02:23
이 인덱스를 항상 업데이트해야 합니다
always updating this index you have to be committed and
19:02:26
쿼리에서 데이터를 필터링하려면
responsible so in your queries if you want to filter the data
19:02:29
국가와 점수를 사용하여 항상 국가부터 시작하세요
using country and score always start with the country
19:02:32
그런 다음 점수를 사용해야 합니다
then the score in order to be able to
19:02:36
인덱스 최적화를 사용하세요
use the index optimizer so if you do it like
19:02:39
이렇게 하면 인덱스가 작동할 수 있습니다
this the index can be working but if you go
19:02:42
쿼리를 반대로 시작하면 인덱스를 사용할 수 없습니다
and query the way around so you start with the score and then the country the sql will not be
19:02:49
쿼리를 조정하거나 인덱스를 재생성해야 합니다
using your index so either you adjust your
19:02:52
이 스위치를 기반으로 인덱스를 재생성해야 합니다
queries or you have to go and recreate the
19:02:56
복합 인덱스의 순서에 주의하세요
index based on this switch so be very
19:02:59
순서가 매우 중요합니다
careful with the composite indexes the order is very
19:03:02
쿼리와 정확히 일치해야 합니다
critical so you're gonna have it exactly like
19:03:05
두 열에 대한 멋진 인덱스가 생겼습니다
the query and now you might say you know what now we have like
19:03:08
국가를 사용하면 질문이 생깁니다
a nice index for those two columns what can happen if i go and use in my query only one of them like for example
19:03:16
이 쿼리를 실행하면 SQL이 이를 사용합니까
the country so now the question is if i go and
19:03:19
점수가 없어도 인덱스를 사용합니다
execute this query is the sql is using this
19:03:22
예, 왼쪽을 따르기 때문입니다
index even though that i don't have the score well
19:03:26
가장 왼쪽 접두사 규칙을 따릅니다
yes because it follows the left
19:03:29
항상 왼쪽 열을 사용하는 경우 인덱스를 사용할 수 있습니다
most prefix rule so this means sql
19:03:32
여기서 인덱스의 국가가 왼쪽에 있습니다
can use the index if you are using always the
19:03:35
왼쪽 열을 건너뛰면 작동하지 않습니다
left columns so here in our index country is on the left that's why it is working over here but if you go and skip the left column
19:03:44
예를 들어 점수만 선택하면 작동하지 않습니다
it will not work so if you go over here for example and say let's go and select only the score
19:03:52
500보다 높은 것
and it is like higher than 500 what
19:03:56
우리는 이 쿼리에서 국가를 건너뛰었습니다
we have done we have skipped the country in this query
19:03:59
그래서 작동하지 않을 것입니다
and that's why it will not be working so as long as
19:04:02
왼쪽 열을 포함하면 작동합니다
you are including the left columns it will work even though it is only one column so in this scenario the first query gonna use the index the
19:04:11
두 번째는 사용하지 않을 것입니다
second one will not be using it so now let me give you a
19:04:14
네 개의 열을 사용하는 인덱스가 있다고 가정해 보겠습니다
very simple example in order to understand how this works so let's
19:04:17
a b c d 이제 쿼리에서 a 열을 타겟팅하면
say that we have an index using four columns a
19:04:20
인덱스를 사용할 수 있습니다
b c d now in your query if you go and target the column a
19:04:23
a와 p를 사용하면 같은 일이 발생할 수 있습니다
the index can be used now the same thing can
19:04:26
인덱스를 사용할 수 있습니다
happen if you go and use a and p so if you are using those two columns you will be using the index so those are where the Index will be used.
19:04:37
이제 인덱스가 사용되는 시나리오를 살펴보겠습니다
So now let's have the scenarios where the index once
19:04:42
B 열로 즉시 이동하면
Be used so for example if you go and just jump
19:04:45
왼쪽 열 a를 사용하지 않기 때문에
immediately to the column B So you are not using
19:04:48
인덱스를 사용하지 않을 것입니다
the left column the a that's why you will not be
19:04:51
쿼리에서 a를 사용하고
using the index and as well in your query If you are using a
19:04:55
조각을 건너뛰고 있습니다
and you are skipping the piece So you I have a
19:04:58
항상 왼쪽 열을 사용해야 합니다
and then see you will not be using the index so
19:05:01
여기서 a p c를 사용하면
you have always to use always the left columns so
19:05:04
인덱스를 사용할 것입니다
here if you are using a p c you
19:05:07
d로 점프하고 건너뛰면 인덱스를 사용하지 않을 것입니다
will be using the index and let's see here you are using a p
19:05:10
인덱스이므로 이것이 왼쪽 접두사 규칙을 의미합니다
and then you jump and skip to the d you will not be using
19:05:13
복합 인덱스를 사용하여
the index so this is what we mean with the leftmost prefix rule
19:05:17
하나의 인덱스 내에서 여러 열을 사용하는 경우 주의하십시오
by using the composite index so if you
19:05:20
정의하는 열의 순서에 주의하십시오
are using multiple columns inside one index be careful with
19:05:23
이제 두 번째 범주로 넘어가겠습니다
the order of the columns that you are defining all right
19:05:26
이 카테고리에 대한 모든 내용은 클러스터형 및 비클러스터형 인덱스입니다. 이제 저장소에 따라 인덱스에 대해 이야기하는 두 번째 카테고리로 넘어가겠습니다.
so that's all for this category clustered and non-clustered index now we're going to move to the second category where we talk about the indexes by the storage the raw store and the column store
19:05:41
이제 테이블이 있고 여러 행과 여러 열이 있다고 가정해 보겠습니다.
so now let's say that we have a table we have multiple rows and multiple columns now
19:05:45
로스터 인덱스를 사용하면 이것이 전통적인 방식입니다.
if we use a roster index this is the classical
19:05:49
우리 테이블이 여러 행으로 나뉘게 될 수 있습니다.
one what can happen our table gonna be split it
19:05:52
여러 행으로 나뉘게 되고, 각 그룹은
into multiple rows and as we learned each group of
19:05:55
데이터 페이지에 저장됩니다. 즉, 우리는
rows is going to be stored inside a data page so that means we
19:05:58
데이터를 행 단위로 정리하고 있다는 뜻입니다.
are organizing the data row by row which means
19:06:01
각 행의 모든 열이 함께 저장됩니다.
all the columns for each row going to be stored together
19:06:05
이것이 데이터베이스가 데이터를 정리하는 전통적인 방식입니다.
this is the traditional way on how the
19:06:08
데이터베이스는 정보를 행 단위로 저장하지만, 반면에
databases organize their data where the informations
19:06:11
열 저장 인덱스를 사용하면 SQL이 테이블을 나누게 됩니다.
are stored row by row but now on the other side if
19:06:14
여러 개의 개별 열로 나누고
you use column store index the sql gonna go and split
19:06:17
SQL은 하나의 열의 값을 함께 저장할 수 있습니다.
your table into multiple separate columns and
19:06:20
데이터 페이지에 저장되므로, 페이지를 열면
then sql can go and store the values of one column together
19:06:24
하나의 열의 값만 찾을 수 있습니다.
in data page so that means if you go and open
19:06:27
전체 행을 찾을 수는 없습니다.
a data page you will find only the values of one
19:06:30
예를 들어, 이름이 첫 번째인 경우, 첫 번째 이름 정보만 볼 수 있습니다.
column you will not find the entire row so
19:06:33
이 데이터 페이지에서는 성 정보는 볼 수 없습니다.
if it's like the first name you will see only the first name informations
19:06:36
비교해보면, 로스터 인덱스는 데이터를 행 단위로 저장하고
you will not see the last name information in this data page so
19:06:39
열 저장 인덱스는 데이터를 열 단위로 저장합니다. 이는 매우 높은 수준의 표현입니다.
if you compare them the roster index store the data row
19:06:43
열 저장 인덱스가 저장되는 방식에 대한 것입니다. 자세히 알아보겠습니다.
by row the column store index stores the data column by column so this is a very high level representation
19:06:49
고객을 위한 테이블이 있다고 가정해 보겠습니다.
on how the column store index is stored as you know me we go in details in order to understand exactly how sql works with the column store index so let's go
19:07:03
세 개의 열, ID, 이름 및 상태가 있습니다.
all right so now let's say that we have a table for the customers we have
19:07:06
약 200만 개의 행, 200만 명의 고객이 있습니다.
three columns id name and status and as
19:07:09
기본적으로 테이블은 힙으로 구축될 수 있습니다.
well we have around two million rows two million customers and
19:07:13
기본적으로 테이블은 힙으로 구축될 수 있습니다.
as we learned as a default the table can be built as a heap
19:07:16
데이터 페이지 내에서 행이 행별로 저장되는 구조입니다. 하지만 이제 이 테이블 위에 열 저장소 인덱스를 생성합니다.
structure where the rows are stored row by row inside data pages but now we go and create a column store index on top of this table so now once you do that
19:07:26
SQL은 프로세스를 거쳐야 합니다.
sql gonna go through a process in order to
19:07:29
열 저장소를 구축하기 위해 SQL은 데이터를 행 그룹으로 나누어야 합니다.
build the column store so the first step is sql can
19:07:32
SQL 서버에서 각 행 그룹은 약
go and divide the data the rows into row groups now in sql server each row group can contain around
19:07:39
100만 개의 행을 포함할 수 있습니다. 이 예에서 우리 테이블은
like 1 million row so in this example our table can
19:07:42
두 개의 행 그룹으로 나눌 수 있습니다. 첫 번째는 100만 개의
be split into two row groups the first one million
19:07:45
행이 하나의 그룹에 있고 두 번째는 다른 행 그룹에 있습니다.
row in one group and the second one in another row group
19:07:49
이제 여러분은 저에게 물어볼 수 있습니다. 우리는 열에 대해 이야기하고 있는데 왜
now you might ask me we are talking about columns why we are splitting the
19:07:52
행을 나누고 있습니까? 이는 성능을 최적화하고 병렬 처리를 수행하기 위한 사전 단계입니다.
rows well this is just a pre-step in order just to
19:07:55
물론 데이터는 이렇게 저장되지 않을 것입니다. 이제 두 번째 단계가 있습니다.
optimize the performance and to do parallel processing and
19:07:59
다음 단계에서는 열을 세분화할 것입니다. 이제 각 행 그룹에 대해
of course the data will not be stored like this because we have the second step now in the next step is going to go and segment
19:08:06
데이터를 열별로 나누기 시작합니다.
the columns so now is clearly go for each row group
19:08:09
그래서 우리는 이를 열 저장소라고 부릅니다. 왜냐하면 우리는
and start splitting the data by the columns and
19:08:12
서로 다른 열을 분리하고 있기 때문입니다. 즉, 우리는 하나의
that's why we call it a column store because we are separating the
19:08:16
세그먼트를 ID에, 또 하나는 이름에, 그리고
columns from each others so that means we have one
19:08:19
세 번째는 상태에 대해 가지고 있습니다. 이는 각 행 그룹에 대해 발생할 수 있습니다.
segment for the id another one for the name and a
19:08:22
이제 이 프로세스의 세 번째 단계로 이동할 것입니다.
third one for the status and this can happen for each
19:08:25
데이터 압축이 있으며, 이는 가장
row group and now is going to move to the third step in this process we
19:08:29
중요한 단계입니다. 왜냐하면
have the data compression and this is the most
19:08:32
열 저장소가 매우 빠른 이유입니다.
important step in this process because it is
19:08:35
이 프로세스에서 원시 저장소와 비교할 때
the reason why column store is very fast compared
19:08:38
데이터 압축을 수행하는 다양한 기술이 있습니다.
to the raw store so in this process there are like different
19:08:42
가장 유명한 것은 사전을 생성하는 것입니다.
techniques on how to do data compression and the most
19:08:45
예를 들어 열 상태를 살펴보겠습니다.
famous one is that it's gonna go and create like a dictionary
19:08:48
예를 들어 상태 열을 살펴보면
let's take for example column status the
19:08:51
고객의 상태는 활성 또는 비활성입니다
status of the customer whether it is active or inactive
19:08:54
활성 및 비활성이라는 단어가 반복될 것입니다
so the word active and inactive gonna be repeated
19:08:58
200만 번 반복될 것입니다. 고객이 200만 명이기 때문에
like two million times because we have two million customers and since it is like string it is like taking a lot of space
19:09:04
문자열처럼 많은 공간을 차지합니다
and storage but now instead of that we're gonna go and compress
19:09:08
저장소가 필요하지만 이제 대신 압축할 것입니다
the data so first it's gonna go and create a dictionary
19:09:11
데이터를 먼저 사전으로 만들 것입니다
by replacing the value active and
19:09:14
활성 및 비활성을 더 작은 값으로 대체하여
inactive into smaller values like one and
19:09:17
하나와 둘 사이의 매핑이 생깁니다
two so we have like a mapping between the long
19:09:20
긴 값을 작은 값으로 저장한 후
value to a small value and after that is gonna store
19:09:24
데이터 스트림처럼 두 개의 값만 있습니다
like a data stream where we have like only two values
19:09:27
하나 둘 하나 둘 그래서 큰 스트림을 가질 수 있습니다
one two one two so we can have like a big stream of
19:09:30
200만 행이므로 각 열에 대해 이 작업을 수행할 것입니다
two million rows so it's gonna go and do this for
19:09:33
각 열의 크기는 서로 다른 값의 수에 따라 달라집니다
each column and with that the size of each column gonna
19:09:36
각 열에 있는 서로 다른 값의 수에 따라 달라집니다
be changed depends of course on how much different values
19:09:39
데이터 크기를 줄이고 성능을 높이기 위해
you have in each column so this step is very important in
19:09:42
모든 것이 정리되고 압축되면 결과를 데이터베이스에 저장합니다
order to reduce the size of the data and as well to
19:09:45
여기서 일반 데이터베이스를 사용하지 않고
increase the performance so now once everything is organized and compressed isquale gonna go and start storing the results in databases but here is quill will not use
19:09:57
대신 LOP라는 특별한 데이터 페이지를 사용할 수 있습니다
the standard databases that you have learned previously but instead it can use a special data page called LOP, large object page.
19:10:05
이제 일반 데이터 페이지의 구조를 비교해 보겠습니다
So now let's quickly compare the structure of the normal data page that we have learned in the raw store with the new one, the column store, the LOP data page.
19:10:13
각 페이지에는 헤더가 있습니다. 이는 모든 데이터 페이지와 같습니다
So as usual, each page has a header. This is same as any data page. But the next section is going to be the segment header.
19:10:20
다음 섹션은 세그먼트 헤더가 될 것입니다
It has like metadata information about the column segment that is stored in this page.
19:10:25
이 페이지에 저장된 열 세그먼트에 대한 메타데이터 정보가 있습니다
Like we have the segment ID, the row group ID, the column ID.
19:10:30
세그먼트 ID, 행 그룹 ID, 열 ID가 있습니다
And it has as well very important information, the ID to the dictionary page.
19:10:35
사전 페이지에 대한 ID와 같은 중요한 정보가 있습니다
So the dictionary page is as well a type of pages in SQL.
19:10:39
사전 페이지는 SQL의 페이지 유형 중 하나입니다.
It has as well a header, but inside it we have like a mapping.
19:10:43
헤더가 있지만 내부에는 매핑이 있습니다.
So it maps the original value, the long one, the inactive to the smaller version of this value.
19:10:49
예를 들어 원래 값, 긴 값, 비활성 값을 이 값의 더 작은 버전으로 매핑합니다.
for example one and that's all for the dictionary page it has
19:10:52
예를 들어 하나가 있고, 이것이 사전 페이지에 대한 모든 것입니다.
the mapping between the original values and the smaller
19:10:55
원래 값과 더 작은 값 간의 매핑입니다.
values and beneath the segment header we can have
19:10:59
세그먼트 헤더 아래에 우리가 가질 수 있습니다.
now the important place where our data can be stored we have the
19:11:02
이제 우리의 데이터가 저장될 중요한 장소입니다.
data stream so it is like sequence of ids
19:11:05
데이터 스트림은 ID의 시퀀스와 같습니다.
from the dictionary that represents the
19:11:08
사전에서 이 값을 나타냅니다.
values of the columns side by side and of course we cannot fit the whole one million rows inside this data stream we're gonna have like multiple lop data pages
19:11:18
열이 나란히 있는 값이며, 물론 이 데이터 스트림에 전체 백만 행을 담을 수는 없습니다.
So this is how exactly the SQL stores your data if you decided to go with the column store. So let's go back to the process.
19:11:26
이것이 SQL이 데이터를 저장하는 방식입니다.
So back to the process. As you can see, SQL is storing the data as LOP data storage. So this is the last step.
19:11:33
열 저장소를 선택했다면, 프로세스로 돌아가 보겠습니다.
And with that, SQL did convert your table into a column store.
19:11:37
프로세스로 돌아가 보겠습니다.
So now we cannot just create a column store without defining whether it is clustered index or non-clustered index.
19:11:43
SQL이 LOP 데이터 저장소로 데이터를 저장하고 있습니다.
So let's start with the first one, the clustered column store index. So if you create such an index, SQL of course will not be building a B3 structure.
19:11:52
이것이 마지막 단계입니다.
SQL is going to use exactly this structure, the column store structure.
19:11:56
SQL이 테이블을 열 저장소로 변환했습니다.
So as we learned, the clustered index is a complete makeover of your table.
19:12:01
이제 클러스터드 인덱스인지 비클러스터드 인덱스인지 정의하지 않고는 열 저장소를 만들 수 없습니다.
When you apply it, then SQL is going to format everything column wise.
19:12:05
첫 번째, 클러스터드 열 저장소 인덱스부터 시작하겠습니다.
And it is fully replacing the old row based table structure that we have at the start.
19:12:10
이런 인덱스를 만들면 SQL은 B3 구조를 구축하지 않습니다.
So once you apply the clustered column store index, it will not leave anything behind.
19:12:15
SQL은 정확히 이 구조, 열 저장소 구조를 사용할 것입니다.
and your table going to be completely structured as a column store.
19:12:19
클러스터드 인덱스는 테이블의 완전한 변화를 의미합니다.
And one more thing, which is makes sense, of course, all the columns from the original table can be converted to a column store.
19:12:25
적용하면 SQL은 모든 것을 열 단위로 형식화합니다.
So it is not leaving anything behind it. But in the other hand, if you are using a non-clustered column store index, as we learned, it is like a companion to your existing table.
19:12:36
그리고 시작할 때 우리가 가진 이전의 행 기반 테이블 구조를 완전히 대체합니다.
So it co-exists with the table and it will not replace anything.
19:12:41
클러스터드 열 저장소 인덱스를 적용하면 아무것도 남기지 않습니다.
So the column store index can be an additional thing that is stored beside your table.
19:12:47
그리고 테이블은 완전히 열 저장소로 구조화됩니다.
So that means the original table will not be deleted at all like the clustered column store index.
19:12:52
첫 번째는 이전의 행 기반 저장소, 일반 테이블입니다.
The first one is in the old row based storage, the regular table, the first one.
19:12:58
그리고 귀하의 데이터는 열 저장소 인덱스의 별도 구조에 저장될 것입니다.
And your data is going to be as well stored in a separate structure in the column store index.
19:13:02
그리고 물론 비클러스터형 열 저장소 인덱스에서는 원래 테이블 외부에 추가 인덱스를 생성하고 있습니다.
And of course, in the non-clustered column store index, since we are creating an extra index outside of your original table,
19:13:11
이 과정에 포함될 열을 정의할 수 있습니다. 모든 열이 아닐 수도 있습니다. 예를 들어 상태만 선택할 수 있습니다.
you can go and define which column should be included in this process. It must not be all the columns. You can go, for example, with only the status.
19:13:18
즉, 고객의 상태에 대한 하나의 열에 대해서만 열 저장소 인덱스를 구축하는 것입니다.
So that means you build a column store index only for one column for the status of their customers.
19:13:24
이것이 클러스터형 열 저장소 인덱스와 비클러스터형 열 저장소 인덱스를 의미하는 것입니다.
So this is what we mean with the clustered column store index and the non-clustered column store index.
19:13:33
좋아요, 친구들. 이제 왜 우리가 이런 작업을 하는지 물어볼 수 있습니다. 왜 데이터를 열로 나누는지요.
All right, friends. So now you might ask me why we are doing all those stuff. Why I would split my data by the columns.
19:13:40
그 이유는 분석 때문입니다. 분석에서는 많은 데이터 집계와 큰 테이블에 대한 복잡한 쿼리가 있습니다.
Well, it's all because of analytics, because in analytics, we have like big complex query where we have a lot of data aggregations and stuff on big tables.
19:13:49
그리고 행 저장소 인덱스는 이러한 큰 쿼리의 성능을 향상시키기 위해 완벽하게 설계되었습니다.
And the road store index is perfectly designed in order to improve the performance of such big queries.
19:13:56
그래서 SQL 데이터베이스인 SQL Server와 BI 도구인 Tableau 및 PowerBI가 이 방법을 채택하여 데이터 분석가에게 빠른 플랫폼을 제공하게 되었습니다.
And that's why SQL databases like SQL Server and as well BI tools like Tableau and PowerBI did adopt this method in order to offer fast platform for data analyzers.
19:14:08
이제 열 저장소 인덱스가 행 저장소 인덱스보다 데이터 분석에 훨씬 빠른 이유를 이해해 봅시다.
So now let's understand exactly why the column store index is way faster for data analysis than the row store index.
19:14:15
다시 말해, 고객 테이블이 있고 다섯 명의 고객이 있다고 가정해 보겠습니다. ID, 이름 및 상태가 있습니다.
So let's go. So again, we have the customers tables and let's say we have like five customers where we have ID, name and status.
19:14:21
이전에 배운 대로, 행 저장소 인덱스를 사용하는 경우 데이터는 여러 데이터 페이지에 저장될 수 있습니다.
And as we learned before, if we are using row store index, the data can be stored in multiple data pages.
19:14:27
각 데이터베이스에는 한 고객에 대한 전체 기록, 즉 전체 정보가 있을 수 있습니다.
And in each database, we can have the whole record, the whole information about one customer.
19:14:32
이 예에서는 세 개의 데이터 페이지가 있을 것입니다. 그러나 열 저장소 인덱스를 사용하는 경우 약간 다르게 저장됩니다.
So for this example, we're going to have like three data pages. But if you are using the column store index, it's going to be stored a little bit differently.
19:14:39
첫 번째 열인 ID는 하나의 데이터 페이지에 저장됩니다. 여기서 SQL은 이미 짧기 때문에 사전을 구축하지 않습니다.
So the first column, the ID is going to be stored in one data page. And here the SQL will not go and build a dictionary because the IDs are already short.
19:14:47
모든 ID가 포함된 하나의 데이터 스트림이 있을 것입니다. 이제 다음 열 이름은 별도의 데이터 페이지에 저장되며, 각 이름이 하나의 작은 값에 매핑되는 추가 사전 페이지가 있을 것입니다.
So we're going to have like one data stream with all IDs. And now for the next column name, it's going to be stored in a separate data page where we're going to have an extra dictionary page where each name is going to be mapped to one small value.
19:14:59
데이터는 압축되어 저장 공간을 절약하게 됩니다.
So the data is going to be compressed and we're going to save storage now the
19:15:02
데이터베이스는 세 번째 열인 상태에 대해 더 많은 데이터 페이지를 생성할 것입니다.
database is going to create for the third column the status one
19:15:05
활성 상태의 경우 하나, 비활성 상태의 경우 두 개가 있을 것입니다.
more data page and the dictionary here is going to be very small so
19:15:08
데이터 스트림에는 오직 ID만 저장됩니다.
for active we're going to have one and for the inactive we're going to have two
19:15:11
사전의 ID만 저장됩니다. 이제 열 저장소가 더 빠른 이유를 이해해 봅시다. 다음 쿼리를 보겠습니다.
and in the data stream we will be storing only the ids
19:15:14
활성 고객의 총 수를 찾고 싶습니다. 쿼리는 select count star from customers입니다.
of the dictionary so now let's understand why the column store is faster let's have the following query we want to find the total number of customers that are active
19:15:24
상태가 활성인 데이터로 필터링할 것입니다.
So we have the query select count star from customers and we're going to filter the data by the status where it is equal to active.
19:15:32
이제 원시 저장소로 테이블을 쿼리하면 먼저 데이터를 수집해야 합니다.
So now if we query the table with the raw store what can happen is we'll have first to go and collect the data.
19:15:37
그래서 이제 원시 스토어로 테이블을 쿼리하면 발생할 수 있는 것은 데이터를 수집해야 한다는 것입니다.
So it's going to go to the first data page and collect the first two customers then to the second to the third and so on.
19:15:43
그래서 첫 번째 데이터 페이지로 가서 첫 번째 두 고객을 수집한 다음 두 번째, 세 번째로 계속 진행할 것입니다.
And as you can see SQL here is reading everything the whole row the ID the name the status.
19:15:48
그리고 여기 SQL은 모든 것을 읽고 있습니다. 전체 행, ID, 이름, 상태를 읽고 있습니다.
Even though that for the query we actually we don't need all those informations.
19:15:53
쿼리에 대해 실제로 모든 정보가 필요하지는 않습니다.
We just need to count how many customers we need with the status active.
19:15:58
우리는 단지 활성 상태인 고객이 몇 명인지 세어야 합니다.
But still, SQL cannot go and selectively only reading the status. SQL has to read the whole record.
19:16:05
하지만 여전히 SQL은 상태만 선택적으로 읽을 수 없습니다. SQL은 전체 레코드를 읽어야 합니다.
So after SQL has all the data, it's going to go and filter the data. So it's going to go and remove the inactive rows.
19:16:11
SQL이 모든 데이터를 수집한 후에는 데이터를 필터링할 것입니다. 비활성 행을 제거할 것입니다.
And then SQL is going to do the aggregate operation. And with that, we're going to get three rows.
19:16:16
그리고 나서 SQL은 집계 작업을 수행할 것입니다. 그로 인해 우리는 세 개의 행을 얻을 것입니다.
So that's why the total count of active customers is going to be three. But now let's see how SQL is going to query the column store.
19:16:23
그래서 활성 고객의 총 수는 세 명이 될 것입니다. 이제 SQL이 열 저장소를 쿼리하는 방법을 살펴보겠습니다.
So SQL first have to analyze, okay, which columns do I need actually for this query? Well, we need only the status.
19:16:29
SQL은 먼저 분석해야 합니다. 이 쿼리에 실제로 어떤 열이 필요한지 확인해야 합니다. 우리는 상태만 필요합니다.
So SQL will not go and open all three data pages and read it.
19:16:33
그래서 SQL은 세 개의 데이터 페이지를 열고 읽지 않을 것입니다.
SQL will target only one data page, the data page where we have the column status.
19:16:38
SQL은 오직 하나의 데이터 페이지, 즉 상태 열이 있는 데이터 페이지만 대상으로 삼을 것입니다.
So it's going to take this very simple data stream, and then it's going to go and understand the dictionary, and it's going to go and remove all the values where it is equal to two.
19:16:47
그래서 이 매우 간단한 데이터 스트림을 가져가고, 사전을 이해하고, 값이 2인 모든 값을 제거할 것입니다.
So without in the output, we have only three values, and SQL is going to go and do a very quick count for those values.
19:16:52
그래서 출력에서 우리는 세 개의 값만 가지게 되고, SQL은 그 값들에 대해 매우 빠른 카운트를 수행할 것입니다.
So in the output, we will get as well three total number of active customers.
19:16:56
그래서 출력에서 우리는 활성 고객의 총 수가 세 개가 될 것입니다.
So now if you compare this intermediate result sets from the Rostor and the column store, you can see that in the Rostor, we have fetched and retrieved a lot of unnecessary information for this query.
19:17:08
이제 로스터와 열 저장소의 중간 결과 집합을 비교하면, 로스터에서 이 쿼리에 대해 불필요한 정보를 많이 가져왔음을 알 수 있습니다.
And this, of course, going to make the speed of the query very slow.
19:17:12
그리고 이것은 물론 쿼리 속도를 매우 느리게 만들 것입니다.
But in the column store, SQL reads exactly what it needs for this aggregation.
19:17:16
하지만 열 저장소에서는 SQL이 이 집계에 필요한 것만 정확히 읽습니다.
And we didn't read any extra information about the names of the customers, the IDs.
19:17:22
우리는 고객의 이름이나 ID에 대한 추가 정보를 읽지 않았습니다.
It didn't like open any extra data pages. It exactly gets the data that it needs for the aggregation.
19:17:28
추가 데이터 페이지를 열지 않았습니다. 집계에 필요한 데이터만 정확히 가져옵니다.
And that's exactly why the performance of queries where we have aggregations and data analyzes is going to be very fast if you are using column store compared to the row store.
19:17:39
그래서 집계와 데이터 분석이 있는 쿼리의 성능이 매우 빠른 이유입니다.
So that's why we use column store for big data and data analytics. All right.
19:17:44
열 저장소를 사용하는 경우 로우 저장소에 비해 성능이 매우 빠릅니다.
So now let's summarize the differences between the row store and the column store indexes side by side. So let's start by the definition.
19:17:51
그래서 우리는 대량 데이터와 데이터 분석을 위해 열 저장소를 사용합니다. 알겠죠.
the row store gonna go and organize and store the data row by
19:17:54
이제 로우 저장소와 열 저장소 인덱스의 차이점을 나란히 요약해 보겠습니다. 정의부터 시작하겠습니다.
row it is really nice method if you need a lot of columns in
19:17:57
로우 저장소는 데이터를 행별로 조직하고 저장합니다.
one row but in the other hand the column store index
19:18:00
데이터를 저장하고 열별로 정리할 것입니다.
gonna go and store the data and organize it column by column
19:18:03
특정 열에 집중하고 있다면 정말 좋습니다.
which is really great if you're focusing on specific column now
19:18:07
저장 효율성에 대해 이야기한다면 행 저장 인덱스가
if you are talking about the storage efficiency the row store index
19:18:10
열 저장 인덱스에 비해 더 많은 공간을 차지할 것입니다.
gonna take more space compared to the column store index and that's because as we learned the column store gonna go and compress
19:18:17
대량의 테이블이 있을 경우 많은 저장 공간을 절약할 수 있습니다.
the data which can save a lot of storage if you have large tables
19:18:20
이제 그들의 더 중요한 다음 포인트로 넘어갑니다.
now to the next point which is more important about their
19:18:23
성능, 읽기 및 쓰기 최적화에 대해
performance the read and write optimizations we
19:18:26
원시 저장소에서는 더 균형 잡힌 성능을 제공합니다.
can say for the raw store things are more balanced so you
19:18:29
쓰기 및 읽기 작업 모두에서 괜찮은 속도를 얻을 수 있지만
will get a decent speed for both write and read operations but
19:18:33
열 저장소는 다릅니다. 데이터 분석을 할 때 빠릅니다.
things in the column store is different it is fast for
19:18:37
특히 읽기 속도가 빠르지만
reading especially if you are doing data analytics but
19:18:40
데이터를 쓰는 것은 느립니다.
writing data like inserting and updating it is
19:18:43
페이지에 데이터가 기록될 때까지 여러 단계가 필요합니다.
slower because as we learned there are like multiple steps until
19:18:47
한편으로는 분석 속도를 최적화하고
the data is written in the pages so in
19:18:50
다른 한편으로는 데이터를 변경하는 것이
one hand you are optimizing the speed of your analytical
19:18:53
행 저장 인덱스보다 느립니다.
queries but in the other hand changing data it is
19:18:56
이제 다음 포인트인 입력 및 출력 효율성에 대해 이야기해봅시다.
slower than the raw store index now let's talk about the next
19:18:59
원시 저장 인덱스는 그렇게 좋지 않습니다.
point input and output efficiency well the raw store index
19:19:02
많은 열을 검색해야 하기 때문입니다.
it's not really good because you are retrieving a lot of
19:19:05
디스크 저장소에서 많은 데이터를 읽어야 합니다.
columns so a lot of data should be read from
19:19:08
쿼리에 답하기 위해서입니다. 하지만
the disk storage in order to answer your queries but
19:19:12
열 저장소는 더 낮습니다.
in the other hand for the column store it is lower and
19:19:15
쿼리에 필요한 데이터와 열을 정확히 타겟팅하기 때문입니다.
that's because it targets exactly the data and
19:19:18
디스크 저장소에서 읽는 데이터가 적어질 것입니다.
columns that is needed for the query so there will be generally
19:19:21
물론 빠른 읽기 성능을 얻는 이유입니다.
less data that is read from the disk storage and of
19:19:24
물론, 그래서 우리는 빠른 읽기 성능을 얻고 있습니다. 이제 우리는
course that's why we are getting fast read performance so now we
19:19:28
원시 저장소 인덱스에 가장 적합한 시스템이 무엇인지 생각하고 있습니다.
are thinking which systems are best for raw store index
19:19:31
원시 저장소 인덱스는 구형 TB 시스템의 온라인 거래 시스템에 매우 적합합니다.
well the roster index is very suitable for the old tb systems online transactional systems like banking and commerce systems where the full records are are accessed very frequently.
19:19:42
반면에, 열 저장소 인덱스는 OLAP에 적합합니다.
But in the other hand, the column store index is great for OLAP.
19:19:46
OLAP 시스템은 데이터 웨어하우스, 데이터 리그, 비즈니스 인텔리전스와 같은 온라인 분석 처리입니다.
OLAP systems are online analytical processing where you have like data warehouses, data league, business intelligence, you're building reports and analyzes.
19:19:55
대량의 데이터 세트와 매우 복잡한 집계 쿼리가 있습니다.
You have large data sets and very complicated aggregated queries
19:20:00
따라서 그러한 프로젝트가 있다면 열 저장소 인덱스가 최선입니다.
So if you have such a project, then the column store index is the way to go.
19:20:03
즉, 원시 저장소 인덱스의 사용 사례는
So that means the use case for the road store
19:20:06
고주파 거래가 있는 경우, 시스템이 신속하게 레코드에 접근해야 하고
index, if you have high frequency transactions, where the system has to quickly access records and the use case for the column store is big data analytics, where the SQL has to scan large data sets.
19:20:18
열 저장소의 사용 사례는 대량 데이터 분석입니다.
So those are the main differences between the road store index and the column store index.
19:20:28
좋습니다. 이제 열 저장소 인덱스의 구문을 확인해 보겠습니다.
all right so now let's check the syntax of the column store index well it
19:20:31
정말 간단합니다. 우리가 할 일은 열 저장소
is really easy what you're gonna do we're gonna just put a column store
19:20:34
키워드를 클러스터형 또는 비클러스터형 사이에 넣는 것입니다.
keyword between the clustered or non-clustered and
19:20:38
인덱스입니다. 이를 지정하면 SQL에
the index so once you specify that then you are telling sql
19:20:42
열 저장소 인덱스를 생성하겠다고 알리는 것입니다.
you want to create a column store index and the rest is gonna stay as it is now if you want to create a row column store then you
19:20:49
그 외에는 그대로 유지됩니다. 이제 행 열 저장소를 생성하려면
don't have to specify anything there is no keyword for the row
19:20:52
아무것도 지정할 필요가 없습니다. 행에 대한 키워드는 없습니다.
store so as we learned before we can go and create a non-clustered
19:20:55
그래서 이전에 배운 대로 비클러스터형
index and clustered index and both of those syntax
19:20:58
인덱스와 클러스터형 인덱스를 생성할 수 있습니다.
is going to tell sql we are creating row store index
19:21:02
이 두 구문은 SQL에 행 저장소 인덱스를 생성한다고 알려줍니다.
but if you go and use the column store keyword
19:21:05
하지만 열 저장소 키워드를 사용하면
then you are telling sql that you want to create either
19:21:08
클러스터형 또는 비클러스터형 열 저장소 인덱스를 생성하겠다고 SQL에 알리는 것입니다.
clustered or non-clustered column store index and here there is like a syntax rule if you are creating a clustered column index then you must
19:21:16
여기에는 구문 규칙이 있습니다. 클러스터형 열 인덱스를 생성하는 경우
not specify anything for the columns so you cannot go
19:21:20
열에 대해 아무것도 지정할 수 없습니다.
and specify anything like an id or country or any
19:21:23
ID나 국가와 같은 것을 지정할 수 없습니다.
columns over here because it makes no sense once you
19:21:26
클러스터 열 저장소라고 말하면 모든 열이
say cluster column store then all the columns
19:21:29
새 구조에 포함될 것입니다. 그래서 이것이
gonna be included in the new structure so this
19:21:32
열 저장소 인덱스의 구문입니다. 알겠죠? 그러면
is the syntax of the column store index all right so
19:21:35
이제 다시 스케일로 돌아가서 열 저장소 인덱스를 어떻게 생성할 수 있는지 확인해 보겠습니다. 이전에 생성한 db 고객 테이블을 확인하고 인덱스로 가면
back to scale let's check how we can create column store index now if you check our table here db customers that we have created previously and we go to the indexes you
19:21:44
몇 개의 인덱스를 생성한 것을 볼 수 있고 그 중 하나는
see that you have created few indexes and one of them is
19:21:48
클러스터 인덱스입니다. 이것은
the clustered index this one is
19:21:51
행 저장소 인덱스입니다. 그래서 우리의 테이블은 행으로 나뉘어 있습니다.
a row store index so our table is split
19:21:54
이제 가서 변경해 보겠습니다. 테이블을 열로 나누도록 하겠습니다. 클러스터 열 저장소를 생성하겠습니다.
by the rows now let's go and change that let's
19:21:57
인덱스를 만들고 이름을 db 고객 인덱스로 지정할 것입니다. 그리고 이 인덱스는 테이블에 있을 것입니다.
make our table split it by the columns using the column store so we're gonna say create clustered column store
19:22:07
판매 db 고객과
index and we're going to give it the name index db customers and it's going to be on the table
19:22:14
판매 데이터베이스 고객 및
sales db customers and
19:22:18
그래서 가서 확인해 보겠습니다. 실행하면
here if you go and specify a column it's going to be a mistake
19:22:21
실패한다고 나옵니다. 키 목록이거나
so let's go and check that so if you go and execute it
19:22:24
열이 허용되지 않기 때문에 이럴 수 없습니다.
it says it fails because key lists or
19:22:27
그래서 그것을 제거하고 이제 올바른 구문이 있습니다. 이제
the columns is not allowed so we cannot have this
19:22:30
다시 실행하면 또 다른 오류가 발생할 것입니다. 왜냐하면
so let's remove it and now we have the correct syntax let's
19:22:34
하나의 테이블에 클러스터 인덱스를 두 개 이상 가질 수 없다고 합니다.
execute it again we will get another error because
19:22:37
이미 하나가 있으므로 결정해야 합니다.
it says in one table you cannot have more than
19:22:40
테이블을 열로 나눌 것인지 행으로 나눌 것인지
one clustered index we have already one you have to decide
19:22:43
그렇기 때문에 이전 인덱스를 삭제해야 합니다.
do you want to split your table by columns or by
19:22:46
그래서 이렇게 인덱스를 삭제하겠습니다.
rows that's why we have to go and drop the previous
19:22:50
이전 인덱스를 삭제해야 하므로 이렇게 인덱스를 삭제하겠습니다.
index so we're going to do it like this drop index
19:22:53
그리고 인덱스의 이름이 필요합니다. 이렇게 하고
and i need the name of the index like this and
19:22:56
그 테이블 이름을 지정해야 합니다. 그래서
then we have to specify that table name so
19:23:02
그게 다야 이제 인덱스를 떨어뜨리자
that's it let's drop the index now if
19:23:05
새로 고침하면 더 이상 클러스터 인덱스를 볼 수 없습니다
you refresh we cannot see anymore our clustered index
19:23:08
이제 인덱스를 다시 확인해 보겠습니다
and our query should be working so let's do
19:23:11
이제 새로운 클러스터 인덱스가 생겼습니다
that now let's check the indexes again and
19:23:14
이번에는 컬럼 저장소입니다
now as you can see we got a new clustered index but
19:23:18
아이콘이 바 차트처럼 보입니다
this time it is column store now you can see at the start
19:23:21
또는 분석 및 보고서처럼 보입니다
we have like an icon it looks like a bar chart
19:23:24
컬럼 저장소를 만드는 주된 목적은 바 차트를 갖는 것입니다
or like analytics and reports and that's because the
19:23:27
따라서 여러 개의 클러스터 인덱스를 생성할 수 없습니다
main purpose of creating column store is to have a bar
19:23:30
최대 하나만 가질 수 있습니다
chart so now of course we cannot go and create multiple clustered
19:23:34
이제 첫 번째 이름에 대해 생성해 보겠습니다
column index we can have maximum only one so
19:23:37
또 다른 인덱스를 생성할 것입니다
now if you say you know what let's go and create for the first name
19:23:40
여기에서 전체를 복사한다고 가정해 보겠습니다
another index but this time it's going to be a column store
19:23:43
예를 들어 첫 번째 이름이라고 부르고 정의하겠습니다
so if i go and copy the whole thing over here and let's say it is none clustered column
19:23:50
이제 실행해 보겠습니다
index and let's call it for example first name and we define over here the first name
19:23:59
오류가 발생할 것입니다
so that's it let's go and execute it you
19:24:02
여러 개의 컬럼 저장소 인덱스를 생성할 수 없습니다
will see that we will get an error where a skill tells us you
19:24:05
각 테이블에 대해 하나의 컬럼 저장소 인덱스만 생성할 수 있습니다
cannot create multiple column store indexes
19:24:08
클러스터형 또는 비클러스터형인지 결정해야 합니다
that means you can create only one column
19:24:11
SQL 서버에서는 이 제한이 있습니다
store index for each table and you have to decide whether it is a clustered or non-clustered and you cannot create like the raw store multiple non-clustered index.
19:24:21
다른 데이터베이스에서는 여러 개의 컬럼 저장소 인덱스를 사용할 수 있습니다
So you are allowed only with one column store index. But this limitation is only here in the SQL server.
19:24:29
Azure SQL 서버에서는 가능합니다
In other databases, I know that is allowed to use multiple column store indexes.
19:24:34
첫 번째 인덱스를 삭제하고 필요한 비클러스터형 인덱스를 생성할 수 있습니다
Like in the Azure SQL server, you can do that. So now in order to practice and you would like to create a non-clustered column store index,
19:24:42
첫 번째 인덱스를 삭제합시다
you can drop the first one and you can go and create the one that you need as a non-clustered index. So actually, let's go and do that.
19:24:48
이 테이블의 인덱스입니다
Let's drop the first one. So drop index.
19:24:52
비클러스터형 인덱스를 실행하면 됩니다
This is our index on this table. Let's do that.
19:24:56
비클러스터형 인덱스를 실행하면
And once you execute the non clustered
19:25:00
열 스타 인덱스가 작동할 것이고, 여기서 새로 오신 분들은
column star index is going to work and if you're fresh over here you
19:25:03
비클러스터형 열 저장소를 보게 될 것입니다.
will see that we have a non-clustered column store
19:25:06
첫 번째 이름에 대한 인덱스입니다. 이제
index for the first name okay so now as we
19:25:09
열 저장소가 데이터를 압축하고
learned that the column store gonna go and compress the data and
19:25:13
전체 테이블에 필요한 저장소가 줄어들 것입니다.
the storage that is needed for the entire table gonna be less
19:25:16
원시 저장소보다 적을 것이므로, 그것이
than the raw store so let's see whether that
19:25:19
정말 사실인지 확인하기 위해서는
is really true now in order to check this i will not do that
19:25:22
데이터베이스 판매 DB에서 그렇게 하지 않을 것입니다.
in the database sales DB because everything here is already small
19:25:25
여기 모든 것이 이미 작기 때문에
we're gonna go and use another database we have
19:25:29
우리는 다른 데이터베이스를 사용할 것입니다.
the adventure works DW2022 and
19:25:32
모험 작업 DW2022와
if you have a newer version that's okay so now what is the plan we're gonna
19:25:35
더 최신 버전이 있다면 괜찮습니다. 이제 계획은
go and create three identical copies of one table and
19:25:39
하나의 테이블의 세 개의 동일한 복사본을 만들 것입니다.
we're gonna have different structures so the first one gonna be the heap structure the second one gonna be row store structure and the third one gonna be column store structure and then we're gonna go and compare the storage
19:25:50
첫 번째는 힙 구조, 두 번째는 행 저장소 구조, 세 번째는 열 저장소 구조가 될 것입니다.
of those three so now we have to go and pick one of those tables we need one big table so for example the fact internet sales so let's see how we can do that let's start with the heap structure
19:26:01
그런 다음 저장소를 비교할 것입니다.
we're going to say select star into a
19:26:04
그 세 개의 테이블 중 하나를 선택해야 합니다.
new table so it's going to be the fact internet sales and underscore hp for the heap and we're going to get it from the table
19:26:14
사실 인터넷 판매이므로
facts internet sales so
19:26:18
이와 같고 여기서 데이터베이스를 전환하는 경우 매우 중요합니다.
like this and here it's very important if you are switching databases you have
19:26:21
데이터베이스를 사용해야 하므로 모험을 사용할 것입니다.
to go and use the database so it's going to be use adventure
19:26:24
작업 dw 2022이므로
work dw 2022 so
19:26:28
전환하고 있는지 확인하기 위해 시작할 때 이것을 실행하세요.
execute this at the start to make sure that you are switching
19:26:31
새 데이터베이스로 전환하고 이제 우리의 힙을 실행해 보겠습니다.
to the new database and now let's go and execute our heap
19:26:34
구조이므로 이를 통해 60,000개의 행을 가진 힙 테이블을 생성했습니다. 그리고 우리는
structure so with that we have created heap table as you can see 60 000 rows and since we
19:26:40
클러스터형 인덱스를 정의하지 않았기 때문에 이 테이블은
didn't define any clustered index this table
19:26:43
이제 힙 구조가 될 것이고 다른 테이블을 생성하겠습니다.
is going to be a heap structure now let's go and create another table
19:26:46
클러스터형 행 저장소 인덱스를 사용할 곳입니다.
where we use clustered row store index
19:26:49
전체를 복사할 것입니다.
so what we're going to do we're going to copy the whole thing over
19:26:52
여기서 우리는 이것을 행 저장소라고 부를 것입니다.
here and we're going to call this row store
19:26:56
물론 이름을 rs로 변경할 것입니다.
and we're going to go of course change the name to rs but
19:26:59
여전히 같은 테이블을 대상으로 하고 있으니 시작할 때 실행하겠습니다. 클러스터형 행 저장소로 만들기 위해 인덱스를 생성해야 합니다.
still we are targeting the same table so let's go and execute this at the start but now in order to make it as clustered row store we have to go and create an index.
19:27:08
이렇게 클러스터형 인덱스를 생성합니다.
So it's going to be like this creates clustered index.
19:27:13
기본값으로 행 저장소를 지정할 필요가 없습니다. 행 저장소가 될 수 있습니다.
We don't have to specify the raw store because it is as a default. It can be a raw store.
19:27:18
인덱스 팩트, 인터넷 판매 RS라고 부르겠습니다. 그리고 기본 키를 추가하겠습니다.
So let's call it index facts, internet sales RS and then the primary key.
19:27:27
키와 이제 테이블이 필요합니다.
So the key and now we need the table
19:27:31
팩트, 인터넷 판매 RS와 이제
fact, internet sales RS and now we need the
19:27:37
기본 키의 열이 필요합니다. 기본 키가 무엇인지 모르니 확인해 보겠습니다.
columns the primary key well actually i don't know what is the primary key so let's go and check that
19:27:42
복합 기본 키입니다. 판매 주문 번호와 판매 주문이 될 것입니다.
so it is a composite primary keys so it's going to be the sales order number and sales order
19:27:51
라인 번호처럼 이렇게 실행하겠습니다. 클러스터형 행 인덱스가 생겼습니다. 여기서 무엇이 있는지 확인하겠습니다.
line number like this so let's go and execute this and with that we have clustered row index i'm going to go and check what do we have over here so let's go and refresh everything
19:28:02
이제 두 개의 테이블이 있습니다. 힙과
so we have now two tables the heap and the
19:28:05
행 저장소입니다. 확장하고
raw store so let's extend it and check the
19:28:08
인덱스를 확인하겠습니다. 클러스터형 인덱스가 있습니다.
indexes and as you can see we have that clustered index
19:28:11
이제 세 번째 테이블이 필요합니다. 열 저장소 인덱스입니다. 전체를 복사하겠습니다.
now we need the third table it's going to be the column store index i'm just going to go and copy the whole thing over here so this is the column
19:28:21
여기서 cs가 될 것입니다. 열 저장소에 대한 열이 필요하지 않습니다. 열 저장소 키워드를 추가하는 것을 잊지 마세요.
store gonna be here cs and cs and of course we don't need any columns for the column store and And don't forget to add the column store keyword.
19:28:34
클러스터형 열 저장소 인덱스를 생성합니다. 여기서 이름을 바꿔야 합니다.
So create clustered column store index. And we have to rename as well over here. So let's go and execute our new stuff.
19:28:41
먼저 테이블을 생성합니다. 그런 다음 열 저장소 인덱스로 변환합니다.
So we create first the table. And then we convert it to a column store index. So let's go and do that.
19:28:47
테이블을 새로 고치고 확인해야 합니다. 이것이 세 번째 테이블입니다.
And we have to go and refresh and check our tables. So this is our third table. And let's go and check the indexes.
19:28:54
클러스터형 열 저장소가 있습니다. 이제 완료되었습니다.
And we have clustered column store. All right. So now we are done.
19:28:58
세 개의 서로 다른 테이블이 있습니다. 이제 확인하겠습니다.
we have our three different tables now let's go and check
19:29:01
세 개의 테이블의 저장소를 확인하겠습니다.
the storages of those three tables so now let's
19:29:04
가서 첫 번째 테이블인 힙 테이블을 확인해 보겠습니다.
go and check our first table the heap table so right click on
19:29:07
속성으로 가서 여기에서 많은 정보를 볼 수 있습니다.
it and go to the properties and now we can see here a lot
19:29:10
저장소 페이지를 클릭하고
of informations about our table but we are interested on the storage
19:29:14
저장소에 대한 몇 가지 정보를 볼 수 있습니다.
so click here on the page for the storage and
19:29:17
데이터 공간은 약 9메가바이트이고 인덱스 공간은 거의 없습니다.
now we can see here a few informations about the storage and one of them is the data space it is around nine megabytes and the index space is
19:29:25
여기에는 아무것도 없습니다. 이것이 힙 구조의 저장소입니다.
almost nothing so we don't have anything over here so this
19:29:28
이제 원시 저장소로 가보겠습니다.
is the storage of the heap structure we don't have any indexes
19:29:31
rs 및 속성으로 가서
let's go now to the raw store so we're
19:29:34
저장소로 가면 데이터 공간이 정확히
going to go to the rs and properties then let's go to
19:29:38
같습니다. 힙이든 원시 저장소 인덱스든
the storage and now as you can see the data space is exactly
19:29:41
데이터는 데이터 페이지에 행으로 저장되므로 데이터 크기는 변하지 않습니다.
the same and that's because whether it is heap or
19:29:44
이제 인덱스에 대한 저장소를 더 많이 사용하고 있습니다.
raw store index we're going to store the data in data pages as rows so the size of the data itself will not change it will be sorted differently but what's changed here Here is the size of the index.
19:29:55
즉, 클러스터 원시 저장소 인덱스가 있는 테이블의 전체 저장소가
Now we are consuming more storage for the index.
19:29:59
힙 구조보다 더 많다는 의미입니다.
So that means the overall storage of the table with
19:30:02
이제 우리의 열 저장소 인덱스를 확인해 보겠습니다.
a cluster draw store index it is more
19:30:05
cs로 가서
than the heap structure let's go and check now our column
19:30:08
속성으로 가면
store index so to the cs and let's
19:30:11
우리 테이블이 작아지고 있는지 확인해 보겠습니다.
go to the properties and now it is interesting to see whether
19:30:15
저장소로 가면 데이터 공간이 약 1메가바이트입니다.
our table is getting smaller so let's go to the storage and
19:30:18
9메가바이트와 비교하면
as you can see the data space is around one megabyte
19:30:21
작은 숫자이지만 여전히 대폭 줄어들었습니다.
compared to the nine megabyte i know those are
19:30:25
모든 것이 압축되었기 때문에 공간이
small numbers but still it is massively reduced
19:30:28
인덱스 공간을 사용하지 않고 있습니다.
space because everything is compressed and
19:30:31
열 저장소에 이 b3 구조가 없기 때문에
of course we are not using any index spaces because
19:30:34
이 테이블은 다른 테이블보다 훨씬 적은 저장소를 소비하고 있습니다.
we don't have this b3 structure in the column store so as you can see if you compare to the others it is the winner this table that is using the column store
19:30:44
다른 것들보다 훨씬 적은 저장 공간을 사용하고 있습니다.
is consuming way less storage than the others
19:30:48
그래서 이제 저장 공간을 기준으로 순위를 매기고 싶다면
so now if you want to rank it based on the storage the
19:30:51
가장 좋은 것은 열 저장소 인덱스 테이블입니다.
best one is the column store index table
19:30:54
그 다음은 힙 구조를 가진 테이블이고
then the next one is the table with the heap structure and
19:30:58
가장 나쁜 것은 행 저장소 클러스터 인덱스를 가진 테이블입니다. 그래서 사실 열 저장소 인덱스는 다른 유형의 인덱스보다 적은 공간을 사용하고 있습니다.
the worst one is the table with the row store clustered index so that's true the column store index is consuming less space than the other type of indexes
19:31:13
좋습니다. 이제 고유 인덱스란 무엇인가요? 고유 인덱스는
all right so now what is unique index unique index is
19:31:16
데이터에 중복이 없도록 보장할 수 있는 특별한 유형의 인덱스입니다.
a special type of indexes that can make sure no
19:31:19
왜 고유 인덱스가 중요한가요? 첫 번째 이유는
duplicates in your data and there are a couple of reasons why
19:31:23
데이터 무결성을 유지하기 위해서입니다.
is it important to have a unique index the first one and
19:31:26
고유 인덱스는 데이터의 고유성을 보장할 수 있으며, 이는 이메일 주소나 제품 ID와 같은 열이 있을 경우 매우 유용합니다.
the most obvious reason is to have data integrity so
19:31:30
이러한 열에 중복이 있으면 데이터가 매우 엉망이 될 수 있습니다.
the unique index can go and enforce uniqueness in your data and that is very helpful for example if you have a column like an email address or a product ID.
19:31:40
이러한 열에 중복이 있으면 데이터가 매우 엉망이 될 수 있습니다.
Having duplicate in such columns can mess up your data very badly.
19:31:45
따라서 이메일과 같은 열에 고유 인덱스를 두면 데이터에 중복이 없도록 할 수 있습니다.
So having a unique index on a column like an email can make sure there are no sneaky duplicates inside your data.
19:31:52
그리고 고유 인덱스가 중요한 두 번째 이유는 성능을 향상시키기 위해서입니다.
And the second important reason why unique index is important is to improve the performance.
19:31:57
예를 들어, 특정 이메일을 검색하고 있다면 SQL은 이메일 값을 검색하기 시작할 수 있습니다.
So for example, if you are searching for specific email, the SQL can start searching for the email value.
19:32:03
그리고 SQL이 값을 찾으면 SQL은 검색을 중단합니다. 왜냐하면 데이터에 중복이 없다는 것을 확신하기 때문입니다.
And once the SQL find the value, the SQL will stop searching because we are sure that there is no duplicates in the data.
19:32:10
따라서 이를 통해 쿼리 성능을 향상시키고 있습니다.
So with that, you are improving the performance of your queries.
19:32:13
따라서 인덱스를 생성하고 이 열이 고유하다는 것을 알고 있다면, 인덱스를 고유 인덱스로 만들어야 합니다.
So if you are creating an index and you know this column is unique, then make sure to make the index as unique index.
19:32:20
이제 클러스터 인덱스를 다시 살펴보면, B 구조가 있는 경우 이 인덱스를 고유하게 만들면 SQL에 추가 작업을 부여하게 됩니다.
So now if you have a look again to our clustered index, where we have the B structure, if you make this index as unique, then you are giving an extra task for the SQL
19:32:30
모든 고객의 아이디어가 고유하다는 것을 보장해야 합니다.
that's going to go and make sure that all those ideas
19:32:34
SQL은 중복이 없도록 보장해야 합니다.
of the customer can be unique so
19:32:37
데이터 페이지 내에서 전혀 중복이 없어야 합니다.
sql has to guarantee that there are no duplicates
19:32:40
따라서 이제 SQL에 추가 작업을 부여하고 있습니다.
at all inside your data in the data pages
19:32:43
데이터의 고유성을 증명하기 위해 클러스터 인덱스를 구축하는 것이 조금 느려질 것입니다.
so now since we are giving sql an extra task
19:32:47
따라서 새로운 데이터를 삽입하고 데이터를 쓰는 것이 일반 클러스터 인덱스보다 느려질 것입니다.
to prove the uniqueness of the data building the clustered index is going to be a little bit slower so that means inserting new data writing data going to be
19:32:56
정상 클러스터 인덱스보다 느려지지만 이제
slower as the normal clustered index but now
19:33:00
속도 성능에 대해 이야기하고 있다면 우리의 성능은
if you are talking about the rate performance the performance of our
19:33:03
정상 클러스터 인덱스보다 약간 더 빠르게 최적화될 것입니다
query it's gonna be optimized a little bit faster than
19:33:06
정상 클러스터 인덱스보다 약간 더 빠르게 최적화될 것입니다
a normal clustered index so again this trade-off
19:33:10
데이터 쓰기를 느리게 하지만
we are making writing data slower but
19:33:13
쿼리 성능에서 더 많은 속도를 얻고 있습니다
we are gaining more speed on the query performance
19:33:16
이것이 우리가 고유 인덱스라고 부르는 것입니다. 이제 인덱스의 구문을 계속 확장해 보겠습니다. 이제 그것이 고유한지 아닌지를 알기 위해
so this is what we mean with unique index okay so let's keep extending the syntax of the index so now in order to tell whether it is unique or not we can specify
19:33:25
정확히 시작 부분에서 이렇게 말합니다. 생성합니다
it exactly at the start so we say create
19:33:29
고유는 클러스터형 또는 비클러스터형 바로 앞에 있습니다
unique is just before the clustered or non-clustered
19:33:32
그 후에는 열 저장소가 있으며 나머지는 변경되지 않았습니다
and then afterward the column store and nothing changed for the rest
19:33:35
이 키워드를 지정하여 SQL에 알려줄 수 있습니다
so we can specify this keyword to tell sql it should
19:33:38
고유해야 하며 클러스터 인덱스 앞에 아무것도 작성하지 않으면 고유하지 않게 됩니다. 예를 들어, 이것은 인덱스를 생성하라고 합니다. 여기서는 아무것도 지정하지 않았습니다
be unique and if you don't write anything before the clustered index it's gonna be not unique so for example this one says create an index so we didn't specify anything here
19:33:50
인덱스에서 중복이 허용되지만 고유 인덱스를 지정하면 중복이
duplicates are allowed in the index but if you go and
19:33:53
허용되지 않습니다. 매우 간단합니다. 이제
specify a unique index then the duplicates are
19:33:57
허용되지 않으므로 매우 간단합니다. 자, 이제 시작합시다.
not allowed so it is very simple okay so now let's
19:34:00
고유 클러스터를 생성하고 이제 테이블 제품을 타겟팅합시다. 먼저 테이블에서 데이터를 선택합시다. 판매 제품에서요.
go and create unique cluster now let's go and target the table products let's go and first select the data from the table so sales products
19:34:11
실행되었습니다. 이제 카테고리 열에 고유 인덱스를 생성해 보겠습니다. 시도해 봅시다.
and executed now let's see that i'm gonna go and create a unique index on the column category let's Let's go and try it.
19:34:18
고유 비클러스터 인덱스를 생성하세요.
So create unique non clustered index.
19:34:23
그리고 테이블 판매 제품의 이름을 인덱스 제품 카테고리로 지정합시다.
And let's give it the name index products category on the table sales products.
19:34:32
우리는 카테고리 열을 타겟팅하고 있습니다. 자, 이제 실행합시다.
And we are targeting the column category. So let's go and execute it.
19:34:39
이제 카테고리에 중복이 있기 때문에 오류가 발생할 것입니다.
Now we will get an error because the category has duplicates.
19:34:44
테이블을 다시 쿼리하면 중복 값이 있다는 것을 볼 수 있으며 SQL은 이 테이블에 고유 인덱스를 생성할 수 없습니다.
So if you go and query again our table, you can see we have here duplicate values and SQL cannot go and create unique index for this table.
19:34:53
너무 늦었습니다. 하지만 테이블이 비어 있다면 여전히 이 인덱스를 생성할 수 있습니다.
It's too late. But you still can create this index if the table
19:34:56
SQL은 카테고리에 대한 중복 항목을 삽입하는 것을 허용하지 않을 것입니다.
is empty and SQL will not allow you to insert any
19:34:59
물론 그렇게 하면 안 됩니다.
duplicates about the categories and of course it makes
19:35:03
카테고리에 고유 인덱스를 두는 것은 의미가 없습니다.
no sense to have unique index on the categories because
19:35:06
물론 여기서 중복이 발생할 것이지만, 어쩌면 당신은
of course we're gonna get duplicates here but maybe you say you know what
19:35:09
내 제품은 고유하다고 말할 수 있습니다. 제품 이름은
my products are unique the product name should be
19:35:12
고유해야 하며, 이 테이블에 같은 이름의 두 제품을 가질 수 없습니다.
unique and we are not allowed to have in this table two
19:35:15
그래서 당신의 비즈니스에 그런 규칙이 있다면, 제품에 대한 고유 인덱스를 정의할 수 있습니다.
products with the same name so if you have such a rule at your business you can go and define a unique index for the products so let's go and do that now we're gonna go and replace the category with the products
19:35:28
여기서도 같은 일이 발생하므로 우리는
and the same thing over here so we are targeting the
19:35:31
제품 열을 대상으로 하고 있습니다. 이제 이를
column products let's go and excuse it as
19:35:34
보면 작동하고 있습니다. 중복이 없습니다.
you can see now it is working because we don't have any duplicates
19:35:37
테이블 제품 내부에서 확인해 보세요.
inside the table products and if you
19:35:40
여기서 인덱스를 확인하면 우리의
go and check the indexes over here we can see our
19:35:44
새 인덱스를 볼 수 있습니다. 여기 시작 부분에
new index and as you can see at the start here it says it
19:35:47
고유 비클러스터 인덱스라고 표시되어 있습니다. 이제
is a unique non-clustered index now let's go
19:35:50
데이터 무결성을 시도해 보겠습니다. 중복을
and try the data integrity are we allowed not to
19:35:53
이 테이블에 추가할 수 없는지 확인해 보겠습니다.
add any duplicate to this table so let's go and try
19:35:56
그것을 시도해 보겠습니다. 삽입 문을 작성해 보겠습니다.
that out let's have an insert statement let's say inserts
19:35:59
판매 제품에 삽입하고 싶습니다. 제품 ID와
into sales products and i would like only to insert the product id and the product
19:36:08
제품 이름만 삽입하겠습니다. 두 값을 삽입할 것입니다.
name and we're gonna insert two values
19:36:11
새 ID를 가질 것이라고 가정해 보겠습니다.
values let's say we're gonna have a new id
19:36:14
106이지만 중복을 삽입할 것입니다.
106 but we're gonna go and insert duplicate
19:36:18
제품 이름에 대해 이미 '캡'이라는 제품이 있습니다.
for the product name so we're gonna say caps we
19:36:21
이제 중복을 삽입하고 있습니다. 시도해 보겠습니다.
have already a product called caps over here so
19:36:25
이제 오류가 발생할 것입니다. 중복을 삽입할 수 없다고 말합니다.
we are now inserting duplicates let's go and try
19:36:28
이 테이블에 고유 인덱스가 있기 때문입니다.
it now you will get an error saying you cannot insert duplicates
19:36:31
이 인덱스가 이제 우리를 도와주고 있습니다.
to this table because we have a unique index so
19:36:34
내 테이블의 품질을 향상시키고 있습니다. 이것이 방법입니다.
as you can see this index is now helping us and
19:36:38
이 인덱스는 이제 우리의 테이블 품질을 개선하고 있습니다.
improving the quality of my table so this is how
19:36:41
우리는 isqueryl에서 고유 인덱스를 사용하여 작업합니다.
we work with the unique index in isqueryl okay
19:36:48
이제 필터링된 인덱스란 무엇인가요? 필터링된 인덱스는
so now what is a filtered index a filtered index is a
19:36:51
일반 인덱스지만 특정 조건을 충족하는 행만 포함합니다.
regular index but with a twist it only includes rows that meet specific condition so let's understand what this means so again we have our non-clustered index and the p3 structure
19:37:03
이제 리프 노드에서 특정 조건을 충족하는 데이터만 가져옵니다.
So now at the leaf nodes, we will get only the IDs, the data that fulfill a specific condition.
19:37:10
예를 들어, 활성 고객만 원한다고 가정하면 이 조건입니다.
So for example, if we are saying we want only the active customers, this is the condition.
19:37:15
리프 노드에는 활성 고객 ID만 포함됩니다.
So that means on the leaf nodes, we will have only the customer IDs that are active.
19:37:21
비활성 고객은 데이터 페이지와 노드에 포함되지 않습니다.
And any inactive customer will not be included at all at the data page and at the nodes.
19:37:27
따라서 우리의 P 구조는 일반적으로 더 작아질 것입니다.
So that means our P structure is going to be a little bit smaller as usual because we have less data included in the structure.
19:37:35
우리의 인덱스는 일반 비클러스터 인덱스보다 작아질 것입니다.
So our index is going to be smaller than the regular non-clustered index.
19:37:39
이제 질문은 필터링된 인덱스가 왜 중요한가입니다.
So now the question is, why is it important to have a filtered index?
19:37:43
가장 큰 이점은 목표 최적화를 할 수 있다는 것입니다.
Well, the biggest benefit is we're going to have targeted optimizations.
19:37:48
우리의 분석이 항상 활성 사용자에 초점을 맞춘다면 비활성 사용자는 무의미합니다.
So for example, if our analysis always focuses on the active users and the inactive users are totally unrelevance.
19:37:55
필터링된 인덱스에 관련된 데이터만 포함되므로 인덱스가 작아지고 성능이 빨라집니다.
So that means having only relevant subset of data in the index going to make the whole index much smaller, which leads to faster performance.
19:38:06
따라서 우리는 목표 최적화를 하고 쿼리 성능을 개선하고 있습니다.
So it's going to be faster to query this filtered B3 structure.
19:38:11
두 번째 이점은 저장 공간에 관한 것입니다.
So that means we are doing targeted optimizations and we are improving the query performance.
19:38:17
B 구조의 크기가 작아질 수 있으므로 저장 공간이 덜 필요합니다.
Now the second benefit if you think about the storage since
19:38:20
필터링된 인덱스는 인덱스 구조를 작게 만들어 속도와 성능을 개선합니다.
the size of the b structure can be smaller that means we're going to need less storage space in order to store the index which is great thing if you have large tables in your database.
19:38:32
이제 필터링된 인덱스의 구문을 확인해 보겠습니다.
So the filtered index can make the structure of the index smaller which can improve the speed and the performance and as well reduce the storage that is needed for your index.
19:38:43
인덱스를 생성할 때 끝에 where 절과 조건을 추가할 수 있습니다.
Okay so now let's check the syntax of the filtered index. It's very simple. It's like any query.
19:38:48
하지만 SQL 서버는 이 유형의 인덱스를 사용하는 데 매우 제한적입니다.
You can go and add at the end of creating the index, the where clause, and then the condition as you are doing in any select statement.
19:38:56
클러스터 인덱스에서는 필터링된 인덱스를 사용할 수 없습니다.
But the SQL server is very restrictive using this type of index.
19:39:00
비클러스터 인덱스에만 허용됩니다.
So you cannot use filtered index on a clustered index.
19:39:05
클러스터 인덱스를 생성하면 전체 테이블이
So it is only allowed for the non-clustered index because it makes no sense.
19:39:10
재구성되고 정렬되어야 합니다.
if you create a clustered index the entire table
19:39:14
테이블 전체가 재구성되고 정렬되어야 합니다.
should be reorganized and ordered so
19:39:17
데이터의 일부 집합에 대해서만 작동하지 않습니다.
it will not work for only subset of data and as
19:39:20
열에 필터링된 인덱스를 생성할 수 없습니다.
well you cannot create a filtered index on a column
19:39:23
저장소에서 원시 데이터를 사용하는 경우에만 허용됩니다.
store so it is only allowed if you are using raw
19:39:26
저장소에서 필터링된 인덱스와 고유 인덱스를 결합할 수 있습니다.
store but you can go and combine the unique index together with the filtered index there is no restrictions so it can be like this create unique non-clustered
19:39:36
테이블에서 인덱스를 생성한 다음
index on the table and then you specify the
19:39:39
조건을 지정합니다. 이것이 필터링된 인덱스의 구문입니다.
where condition so this is the syntax of the filtered index
19:39:42
이제 다음 쿼리를 가정해 보겠습니다.
and we have these restrictions all right so now let's say
19:39:45
고객 데이터에서 선택하고 있습니다.
that we have the following query where we are selecting data from customers
19:39:48
미국의 고객만 선택하고 있습니다.
but always in our program or in our report we are selecting only the customers from usa so we have the following condition it says where country equal to
19:40:00
그래서 조건은 국가가 USA와 같다고 합니다.
USA and execute. So this is the basics of many queries that we have in our project.
19:40:06
이것이 우리 프로젝트의 많은 쿼리의 기본입니다.
And we are always filtering the customers based on the country. So in one query, we are finding maybe the top customers.
19:40:12
국가에 따라 고객을 필터링하고 있습니다.
And another query, we are finding the average of scores and so on. But we are always filtering the data like this.
19:40:19
또 다른 쿼리에서는 점수의 평균을 찾고 있습니다.
Where country equal to USA. So now since we are using this column a lot. And our table may be getting like million of records.
19:40:26
국가가 USA와 같다고 합니다.
we can go and create non-clustered index on this column.
19:40:30
이 열을 많이 사용하고 있습니다.
So the usual way we go over here and say create non-clustered index and we call it like this index customers country
19:40:41
비클러스터 인덱스를 생성할 수 있습니다.
and then it's going to be on the table sales customers and we select the column country like this.
19:40:49
비클러스터 인덱스를 생성하는 일반적인 방법입니다.
So if you do it like this, SQL going to go and create a
19:40:53
고객 테이블에서 국가 열을 선택합니다.
non-clustered index for all customers not only
19:40:56
이렇게 하면 SQL이 생성됩니다.
from usa but for everything so even
19:40:59
모든 고객에 대한 비클러스터 인덱스입니다.
if the customers come from germany which is not really necessary
19:41:02
미국에서 오는 고객뿐만 아니라
because in our project we only focus on the
19:41:05
독일에서 오는 고객도 포함됩니다.
customers from usa so instead of that we
19:41:08
우리 프로젝트에서는 미국 고객만 집중합니다.
can go and include the where condition inside
19:41:11
그 대신 조건을 포함할 수 있습니다.
our cluster so it's very simple we're gonna go and say where country equal to usa exactly like our
19:41:19
쿼리이므로 이제 생성될 인덱스는
query so now the index that's going to be built it
19:41:22
서브셋에만 집중되고 목표로 할 것입니다
will be focused and targeted only for subset
19:41:25
데이터의 조건이 충족되는 데이터만
of data only for the data that fulfill this
19:41:28
필터링된 인덱스를 생성해 보겠습니다
condition so now let's go and create our filtered
19:41:32
인덱스가 작동하고 있으니 고객의 인덱스를 확인해 보겠습니다
index and it is working let's go and check our
19:41:35
여기에서 새로 고침하면 인덱스가 보입니다. 고유하지 않다고 표시됩니다.
indexes on the customers so let's go to the indexes
19:41:38
시작 부분에서 아무것도 정의하지 않았기 때문에 중복이 허용됩니다.
over here and refresh now we can see our index over here it says it is not unique because we didn't define
19:41:44
여기서 정의한 것이며 필터링되었습니다.
anything at the start so duplicates are allowed of course
19:41:47
따라서 테이블의 모든 행을 포함하지 않습니다.
which is what we defined here and as well it is filtered
19:41:51
조건을 충족하는 행만 포함됩니다.
so it doesn't contain all the rows from your table it
19:41:54
즉, 이제 이 쿼리를 실행하면 인덱스를 사용할 수 있습니다.
contains only the rows that fulfill our condition
19:41:57
쿼리의 행이 인덱스에 포함되어 있기 때문입니다.
so that means now if i go and execute this query the index can be used because the rows of this query is included in the index but if i go over here and say germany
19:42:09
쿼리의 모든 행이 인덱스의 일부가 아니므로 인덱스는 사용되지 않습니다.
and execute the query it's going to be slower because all those rows inside the query
19:42:14
쿼리를 개선하기 위해 필터링된 인덱스를 사용하는 방법입니다.
is not part of our index so this index will not be used at all in order to improve the query so this is how we work with the filtered index in sql
19:42:29
이제 요약하고 어떻게
all right so now we're going to summarize and talk quickly about how to
19:42:32
올바른 인덱스를 사용할지에 대해 빠르게 이야기하겠습니다.
use the right index so when to use which type let's start with the first one we have the heap structure so as we learned
19:42:39
인덱스가 없는 테이블입니다.
it is a table without any index so in
19:42:42
어떤 시나리오에서는 인덱스를 사용하지 않아도 됩니다.
which scenario we don't have to use any indexes in
19:42:45
빠른 삽입이 필요할 경우, 원하신다면
case you want to have fast inserts so if you want to
19:42:48
빠른 성능을 원하신다면 인덱스를 사용하지 마세요.
have a fast right performance then don't
19:42:51
인덱스를 사용하지 않고 기본 힙 구조를 유지하세요.
take any index so you stay with the default with the heap
19:42:54
우리는 일반적으로 중요하지 않은 테이블에서 사용합니다.
structure of your table and we usually use it in not
19:42:57
예를 들어 스테이징 테이블이나 임시 테이블 같은 경우입니다.
very important tables like the staging tables or temporary
19:43:00
데이터를 빠르게 삽입하고 나중에 데이터를 제거하고 싶을 때, 인덱스를 사용할 필요가 없습니다.
tables where we want to insert the data fast and then get rid of the data later so here there is no need to utilize any index
19:43:08
클러스터형 인덱스에 대해 이야기한다면, 우리는 일반적으로 기본 키에 클러스터형 인덱스를 사용합니다.
Now, if you are talking about the clustered index, we usually use the clustered index for primary keys.
19:43:14
데이터베이스의 기본값입니다. 기본 키를 생성하면 SQL이 클러스터형 인덱스를 생성합니다.
It is even a default from the database. If you create any primary keys, then SQL going to go and create a clustered index.
19:43:21
클러스터형 인덱스의 주요 사용법입니다. 기본 키에서 사용합니다.
So this is the main usage of the clustered index. You use it in the primary keys.
19:43:26
테이블에 기본 키가 없으면 데이터를 정렬하는 것이 중요한 다른 열을 선택할 수 있습니다.
And if there's like no primary key in your table, then you can go and pick another column where sorting the data is important.
19:43:33
예를 들어 날짜 열과 같은 것입니다. 클러스터형 인덱스의 좋은 후보가 될 수 있습니다.
Like, for example, a date column. So it could be a good candidate for your clustered index.
19:43:37
이제 다른 유형으로 넘어가면 열 저장 인덱스가 있습니다.
Now, moving on to another type, we have the column store index.
19:43:41
클러스터형 인덱스라고 할 때 클러스터형 행 저장 인덱스를 의미합니다. 이제 질문은 열 저장 인덱스를 언제 사용하는가입니다.
So when I said here clustered index, I mean clustered row store index, of course. Now, the question is, when do we use the column store index?
19:43:49
복잡한 분석 쿼리에서 많은 데이터를 집계하고 있을 때 사용합니다.
If you have like big complex analytical queries where you are aggregating a lot of data, doing data aggregations,
19:43:55
테이블 크기로 어려움을 겪고 있다면 열 저장 인덱스를 사용하세요.
then go for the column store index because it's going to give you amazing performance. And as well, if you are struggling with the size of tables.
19:44:03
매우 큰 테이블이 있다면 열 저장 인덱스를 사용하여 데이터를 압축하고 전체 테이블의 크기를 줄일 수 있습니다.
So if you have a super large table, you can go and use the column store index because it can go and compress the data and reduce the size of the whole table.
19:44:11
이러한 시나리오에서는 열 저장 인덱스를 사용합니다. 행 저장 클러스터형 인덱스는 OLTP 시스템에서 사용합니다.
So for those scenarios, we use the column store index. So again, for the row store clustered index, we use it usually for the OLTP systems where you have a lot of transactions and so on.
19:44:22
열 저장 인덱스는 OLAP 시스템에서 사용합니다.
But for the column store, we use it usually for the OLAP systems where you have a data warehouse, reporting system, business intelligence and so on.
19:44:29
이제 다른 유형으로 넘어가면 비클러스터형 인덱스가 있습니다.
now moving on to another type we have the non-clustered index
19:44:33
비클러스터형 인덱스는 비기본 키 열에 사용합니다.
we usually use this index for non-primary
19:44:36
테이블의 나머지 열이 비클러스터형 인덱스의 후보가 될 수 있습니다.
key columns so that means the rest of the columns of your tables
19:44:39
비클러스터형 인덱스를 사용하는 이유는 여러 가지가 있습니다.
could be candidate for the non-clustered index and there are
19:44:42
예를 들어 외래 키나 두 테이블을 조인하는 데 사용되는 열에서 사용할 수 있습니다.
a lot of reasons why you would do that for example for the
19:44:45
비클러스터형 인덱스를 사용할 수 있는 많은 시나리오가 있습니다.
foreign keys or using it on the columns that are used in order to join two tables and another place where you can use the non-clustered index for the columns that are used for the where clause
19:44:57
기본 키에는 사용하지 않습니다. 이제 다른 유형으로 넘어갑니다.
So there are like many scenarios where we can use the non-clustered index but
19:45:00
이제 필터링된 인덱스가 있습니다. 특정 데이터를 타겟으로 사용합니다.
not for the primary keys now moving on to another type
19:45:03
쿼리와 분석에서 데이터의 하위 집합에 집중합니다.
we have the filtered index we use it in order to target
19:45:07
항상 데이터의 하위 집합에만 집중하므로.
a subset of data so if in our query and analyzes
19:45:10
모든 데이터에 대해 큰 인덱스를 가질 필요가 없습니다.
we are only focusing on a subset of data all time
19:45:13
필터링된 인덱스를 사용하여 인덱스의 전체 크기를 줄일 수 있습니다.
it makes no sense to have one big index for all data we can use the filtered index to have focused index and of course if the size of the index is a problem then you can
19:45:24
인덱스의 전체 크기를 줄이기 위해 필터링된 인덱스를 사용할 수 있습니다.
use a filtered index in order to reduce the overall size of the storage of the index. And then to the last type we have the unique index.
19:45:32
테이블의 데이터 무결성을 보장하기 위해 고유 인덱스를 사용할 수 있습니다.
You can go and use the unique index in order to ensure data integrity of your table.
19:45:37
그리고 또한, 이것은 쿼리의 성능을 약간 향상시킬 수 있습니다.
And as well, it might prove slightly the performance of your query.
19:45:40
그리고 그 이유는 인덱스가 고유할 경우 SQL이 수행해야 할 작업이 줄어들기 때문입니다. SQL이 일치를 찾으면 검색을 건너뜁니다.
And that's because SQL has less tasks to do if the index is unique. Once SQL finds the match, it's going to skip the search.
19:45:47
자, 친구들, 이제 데이터베이스에 인덱스를 생성했고 쿼리가 최적화되어 빠른 성능을 보이지만 작업은 아직 끝나지 않았다고 가정해 봅시다.
So this is a quick summary and guide on when to use which index type that usually help me finding the right index.
19:45:59
안돼! 안돼! 제발 안돼! 안돼!
All right friends, so now let's say that you have created your indexes in your database and your query is optimized and you have fast performance but the job is not done yet.
19:46:08
안돼! 왜냐하면 항상 인덱스가
No God! No God! Please no! No!
19:46:16
조각나고 오래되고 사용되지 않으며
No! Because all the time the indexes get
19:46:19
이것은 쿼리에서 성능 저하를 초래할 수 있습니다.
fragmented outdated unused and
19:46:22
또한 저장 비용과 전체
this can lead to a poor performance in your queries and
19:46:26
데이터베이스의 성능이 떨어지지 않도록 해야 합니다.
as well can increase the storage costs and the overall
19:46:29
데이터베이스의 성능이 떨어지면 안 됩니다.
performance of your database cannot drop down so
19:46:32
인덱스는 자동차와 같아서 유지보수가 필요합니다. 자동차의 오일과 타이어를 교체해야 하는 것처럼 인덱스도 유지 관리가 필요하며 주의를 기울여야 합니다.
indexes like having a car it needs maintenance so you need to change the oil and the tire of the car and the same thing goes for the indexes you have to maintain them they need attention to keep
19:46:44
모든 것이 원활하게 작동하도록 유지해야 합니다. 이제 SQL 프로젝트의 인덱스를 어떻게 관리하고 유지하며 모니터링하는지 보여드리겠습니다.
everything running smoothly. So now I'm going to show you how I manage, maintain and monitor the indexes of my SQL project.
19:46:51
자, 시작해봅시다. 첫 번째이자 가장 중요한 작업은 인덱스 사용량을 모니터링하는 것입니다.
So let's go. The first and the most important task is to monitor the usage of your indexes.
19:47:01
물론, 시간이 지나면서 우리가 스스로에게 물어봐야 할 첫 번째 질문은 우리가 정말로 만든 인덱스를 사용하고 있는가 하는 것입니다.
So of course, the first question we have to ask ourselves over the time, are we using really the indexes that you have created?
19:47:08
그들이 정말로 내 쿼리의 속도를 향상시키고 있는가?
Are they really helping improving the speed of my queries?
19:47:11
아니면 프로젝트 시작 시 좋은 아이디어였지만
Or was it just a good idea at the start of the project and
19:47:15
나중에 아무도 그 인덱스를 사용하지 않았던 것인가? 이는 매우
later no one used those indexes this is very
19:47:18
중요합니다. 사용되지 않는 인덱스가 있다면
crucial because if you are having an unused index
19:47:21
불필요한 저장 공간을 소비하고 있으며
you are consuming unnecessary storage space and
19:47:24
테이블의 올바른 성능이 느려질 수 있습니다.
as well the right performance in the tables can
19:47:27
인덱스를 사용하지 않는다면 이는 완전히 불필요합니다.
be slow which is completely unnecessary if you are not
19:47:30
따라서 이제 우리의 작업은 프로젝트에 있는 각 인덱스의 사용량을 파악하는 것입니다.
using the index so now our task is to find out the
19:47:34
그럼 우리가 어떻게 할 수 있는지 살펴봅시다. 이제 간단히 말해, 우리는
usage of each index that you have in the projects so
19:47:37
db 고객 테이블에 여러 개의 인덱스를 생성했습니다.
let's see how we can do that so now briefly we have created like multiple
19:47:40
그래서 만약
indexes on the table db customers so if
19:47:43
데이터베이스 고객의 인덱스에 가면
you go to the db customers and to the indexes you can see that we have
19:47:46
현재 네 개의 인덱스가 있으며, 이 정보를 보여줄 수 있습니다.
four indexes now you can go and show those informations by
19:47:50
SQL 세이버의 특별 저장 프로시저를 사용하여
using a special stored procedures from the sql saver
19:47:53
sp help index를 호출해 보겠습니다.
called sp help index let's go and do that so
19:47:56
sp help index는 데이터베이스와 함께 제공되는 시스템 저장 프로시저입니다. 이 저장 프로시저는 오직 하나의 값만 필요합니다.
sp help index so it is a system stored procedure that comes with the database so this stored procedure needs only one value and that is
19:48:07
테이블 이름입니다. 여기에는 sales db customers가 있습니다.
the table name so we have it over here sales db customers
19:48:10
쿼리를 실행해 보겠습니다. 현재 네 개의 인덱스가 있습니다.
let's go and query it so we have four indexes
19:48:14
그런 다음 인덱스에 대한 설명이 제공됩니다.
then we have a nice description of the index so it says it
19:48:17
비클러스터 인덱스인지 여부와
is non-clustered index and whether it is column store and
19:48:20
위치가 어디인지 설명합니다. 기본 위치에 있다고 합니다.
it say where it is located so it says it's located on primary
19:48:24
기본은 데이터가 저장되는 파일 그룹의 이름입니다.
primary is the name of the file group where the data
19:48:27
기본으로 저장될 수 있으며, 다음 정보는 인덱스 키입니다.
is stored and as a default can be stored as primary and now the next information we have the index keys it is nice information to understand which
19:48:35
어떤 키가 사용되는지 또는 어떤 열이 인덱스에 사용되는지 이해하는 데 유용한 정보입니다.
keys are used or which columns are used for the index
19:48:38
첫 번째로 두 개의 열이 있다는 것을 알 수 있습니다.
so the first one you can see we have two columns that means it is
19:48:41
복합 인덱스이며, 열 저장소에는 열이 없습니다.
a composite index and of course for the column store we don't
19:48:44
이름과 성이 있습니다. 이 저장 프로시저는 정보를 확인하는 데 매우 유용합니다.
have any columns and then we have the first name last name so
19:48:47
인덱스에 대한 정보를 확인하는 데 집중해 보겠습니다.
this is a really nice quick stored procedure in order to see information
19:48:51
인덱스 사용량을 모니터링하는 방법에 대해 이야기하겠습니다.
about our index okay so now let's focus on our task on how
19:48:54
데이터베이스에는 메타데이터를 프로토콜하는 많은 스키마와 테이블이 있습니다.
to monitor the usage of the indexes now in databases we have a lot of schemas and tables that protocol the metadata
19:49:02
SQL 서버에는 많은 메타데이터를 찾을 수 있는 특별한 스키마가 있습니다.
of our database and in SQL server we have a special
19:49:06
sys라는 스키마로, SQL 서버 메타데이터에 대한 정보를 제공합니다.
schema called sys where you can find a lot of metadata
19:49:09
테이블, 뷰, 열 및
information about the SQL server metadata like
19:49:12
인덱스에 대한 설명입니다. 이제 내부에서 무엇을 찾을 수 있는지 확인해 보겠습니다.
the description of the tables views columns and
19:49:15
테이블 인덱스입니다. sys에서 select star를 실행해 보겠습니다.
as well the indexes so now let's check what we can find inside
19:49:18
여기에는 많은 정보가 있지만, 인덱스에 집중하고 싶습니다.
the table indexes so let's go and do it select star from sys this is the schema name and then as you can see we have a list
19:49:27
많은 정보 중에서 인덱스에 집중하고 싶습니다.
of many informations but we want to focus on the indexes
19:49:30
이제 실행해 보겠습니다. 이제 우리는 방대한
now let's go and execute it now we get a huge
19:49:33
모든 인덱스 목록을 얻었고
list of all indexes that we have and a
19:49:37
각 인덱스에 대한 많은 정보가 있습니다.
lot of informations for each index we
19:49:40
지금 각 열을 이해할 필요는 없지만, 이 테이블에서 주요한 정보를 선택할 것입니다. 그래서 우리가 필요한 것은 객체 ID입니다. 이것이 테이블 ID입니다.
don't have to go and understand now each column but i'm gonna go and select the main important informations from this table so what do we need the object id this is the table id so the object id
19:49:52
그리고 우리는 이름이 있습니다. 그것은 인덱스 이름입니다.
and we have the name. It is the index name.
19:49:57
그리고 여기에서 클러스터형인지 아닌지에 대한 좋은 정보가 있습니다.
And then here we have a nice information whether it is clustered or
19:50:00
비클러스터형이므로 유형을 선택합시다.
non-clustered so let's go and select it type
19:50:03
디스크로서 인덱스 유형이라고 부릅시다.
disk as so let's call it index type
19:50:06
그리고 그것이 기본 키인지 아닌지 확인할 수 있습니다.
and we can go and check whether it is primary key or not so
19:50:10
이 정보도 가져옵시다. 기본입니다.
let's get this information as well is primary
19:50:13
키를 그냥 기본으로 이름을 바꿀 것입니다.
key i will go and just rename it is primary
19:50:16
그리고 우리가 필요한 것은 고유한지 여부입니다.
key and what else do we need whether it is unique
19:50:19
그래서 그것은 가지고 있는 좋은 정보입니다. 그래서 고유합니다.
so it is as well nice information to have so is
19:50:22
물론 많은 것을 가져갈 수 있습니다. 정말로 당신이 모니터링하는 것에 달려 있습니다.
unique so
19:50:27
예를 들어, 비활성인지 여부를 확인할 것입니다. 그래서 비활성입니다.
of course you can go and grab a lot of stuff it depends really on what you are monitoring so for example i'm gonna go and check whether it is disabled or not so is disabled
19:50:37
그래서 그냥 이름을 바꿀 것입니다.
and so i'll just rename it so
19:50:42
그것으로 저는 집중 모니터링을 할 수 있습니다. 모든 정보를 가질 필요는 없습니다. 그래서 실행해 봅시다. 하지만 이제 몇 가지를 변경하고 싶습니다. 예를 들어, 객체 ID는 원하지 않고, 그 테이블의 전체 이름을 원합니다.
with that i have like focus monitoring i don't have to have all those informations so let's go and execute but now i would like to go and change few stuff like for example i don't want the object ID, I would like to have the full name of that table.
19:50:53
그리고 제 데이터베이스의 이벤트 아래에 많은 인덱스가 있습니다.
And as well, there is a lot of indexes that is under events for my database.
19:50:58
그래서 그렇게 하려면 다른 메타데이터 테이블에서 정보를 가져와야 합니다. 그래서 이 인덱스를 호출합시다.
So now in order to do that, you have to go and get the information from another metadata table. So let's go and call this index.
19:51:04
그리고 다른 메타데이터 테이블과 조인합시다. 그것은 테이블이라고 불립니다. 그래서 TBL입니다.
And let's go and join it with another metadata table. It's called tables. So TBL.
19:51:11
그리고 우리는 그것을 사용하여 조인할 것입니다.
And we're gonna go and join it using the so the
19:51:15
인덱스 객체 ID는
index object ID equal
19:51:18
테이블 객체 ID와 같고
to the table object ID and
19:51:22
이 테이블의 내용을 보고 싶다면 우리는 가서 할 수 있습니다.
if you'd like to see the content of this table we can go and
19:51:25
별도로 생성하므로, 우리로부터 스타를 선택하세요.
create separately so select star from our
19:51:28
새 테이블을 생성하므로, 이 테이블의 내용을 봅시다.
new table so let's see the content of this table so you can see we have the name which is the table name and I think that's all what we need we have a lot of other informations about the table well I just need a table name.
19:51:40
시작하므로, TBL 이름을 테이블 이름으로 하겠습니다.
So let's go and do it at the start. TBL name as table name.
19:51:47
더 이상 객체 ID가 필요하지 않습니다.
And I don't need anymore the object ID. But of course, we have to go and use the alias for each of those informations in order to understand those informations comes from the index.
19:51:56
그럼 이제 실행할 준비가 되었습니다.
So let's go and do that. All right. So my query is ready. Let's go and execute it again.
19:52:01
이제 테이블 이름을 가져오고 있습니다.
So now, as you can see, we are getting the table name. And the list is very short because it is only focusing on the tables that you have in the database.
19:52:09
내부 조인 때문에 이 필터가 발생합니다.
and this filter happens because of the inner join but one more thing i
19:52:12
데이터를 정렬하고 싶습니다.
would like to go and sort the data so i'm going to say order by i would
19:52:15
테이블 이름으로 정렬하겠습니다.
like to sort it by the table name and
19:52:18
인덱스 이름으로 정렬하겠습니다.
then the index name all right so now
19:52:21
예를 들어 고객 테이블을 확인해 보겠습니다.
let's go and check for example the table customers you can see that
19:52:24
비클러스터 인덱스가 두 개 있습니다.
we have two non-clustered index and one of them is column
19:52:27
이전 튜토리얼에서 만든 두 개의 저장 인덱스가 있습니다.
store index those two we have created from the previous tutorial and we have an index on the primary key as you can see here is primary key
19:52:34
모든 인덱스의 멋진 목록이 있습니다.
equal to one and this is as well unique so with
19:52:37
데이터베이스에 있는 인덱스 목록이 있습니다.
that we have a really nice list of all indexes that
19:52:41
우리의 작업은 인덱스를 모니터링하는 것입니다.
we have in our database but we are not there yet because
19:52:44
인덱스 사용량을 모니터링하는 것입니다.
our task is how to monitor the
19:52:47
각 인덱스에 대해 가야 합니다.
usage of the index now in order to get the usage for
19:52:50
동적 관리 뷰라는 특별한 뷰로 가야 합니다.
each of those indexes we have to go to a
19:52:53
SQL 서버가 사용량에 대한 많은 통계를 제공합니다.
special view called dynamic management view and
19:52:56
인덱스에 대한 통계를 제공할 수 있습니다.
there the sql server can provide a lot of statistics about the usage
19:52:59
이 테이블을 쿼리해 보겠습니다.
for the index and we can find it as well in the same schema so
19:53:02
같은 스키마에서 쿼리할 것입니다.
let's go and query this table so it's going to be select star
19:53:06
같은 스키마는 .입니다.
from so the same schema is dot the
19:53:09
m 언더스코어 db 언더스코어 인덱스
m underscore db underscore index
19:53:12
사용 통계이니 시작합시다
usage stats so let's go
19:53:15
이 표를 탐색하고 지금 실행해 봅시다
and explore this table and execute it now in
19:53:18
그 통계에서 두 개의 인덱스 사용량을 찾을 수 있습니다
those statistics we can find the usage of two indexes
19:53:22
인덱스 번호 3과 1이 있으며, 우리는 볼 수 있습니다
the index number three and one and we can see there are
19:53:25
인덱스 번호 1의 사용 정보가 세 개 있습니다
like three usage informations of the index number one and
19:53:28
다음으로 사용자 검색, 사용자 스캔 및 사용자
next we have like user seeks user scans and user
19:53:31
조회 수입니다. 이것은 인덱스가 사용된 횟수입니다
lookups so this is how many times the index is used as
19:53:34
검색, 스캔 또는 조회로 이해할 것입니다
seeks or scans or lookups we will understand
19:53:38
우리가 실행 계획에 대해 배우면서 이러한 정보를
those informations as we learn about the execution plan and
19:53:41
여기에서 인덱스가 업데이트된 횟수에 대한 좋은 정보를
here we have a very nice information about how many time
19:53:44
볼 수 있습니다. 여기서는 0입니다
our index got updated so as you can see here is zero
19:53:47
데이터를 추가하지 않았기 때문입니다
because i didn't add any new data after creating
19:53:50
인덱스를 생성한 후 새로운 데이터를
the index but of course all those numbers might be different at
19:53:53
추가하지 않았기 때문에 모든 숫자는 다를 수 있습니다
your side because it depends whether you are doing more queries and
19:53:56
여러분의 경우에는 더 많은 쿼리를 수행하는지에 따라 달라집니다
practicing and you can find here more informations about when
19:54:00
연습하면서 이러한 인덱스의 마지막 사용 시점을 찾을 수 있습니다
was exactly the last usage of those indexes
19:54:03
그리고 많은 유용한 정보가 있습니다. 이제
and many many nice informations so now let's
19:54:06
우리의 쿼리와 이 뷰를 통합해 봅시다
go and integrate this view with our query so
19:54:09
지금 제가 할 것은 왼쪽 조인을 하는 것입니다
now what i'm gonna do i'm gonna do a left join because if i do
19:54:12
내부 조인을 하면 사용된 인덱스만 찾을 수 있습니다
an inner join i will only find the
19:54:15
하지만 저는 데이터베이스의 모든 인덱스를 보고 싶습니다
used indexes but i don't know that because i want to
19:54:18
그래서 왼쪽 조인을 하고 가져올 것입니다
see a full build of all my indexes in the database so
19:54:22
우리의 뷰를 s라고 부르고 조인해야 합니다
left join and we're going to go and get
19:54:25
키에서 s로 조인해야 하므로
our view and call it s and then we have to join
19:54:28
인덱스와 동일한 객체 ID를 가져옵시다
it on the keys so s on so i would say let's
19:54:31
인덱스와 동일한 객체 ID를 가져옵니다.
go and grab the object id equal to the index
19:54:34
물론 객체 ID를 가져와야 합니다.
object id and of course we have to
19:54:37
인덱스 ID에 조인하므로 이렇게 됩니다.
join on the index id so it's going to be the
19:54:40
이제 이 뷰에서 몇 가지 정보를 선택해야 합니다.
index id equal to the index id like this now we have to go and select few informations from this view so i'm going to go and select like all those number of of usage.
19:54:52
사용자가 스캔하는 것과 사용자 탐색을 가져옵니다.
So yes, let's get the user seeks as the user scans and the lookups and maybe as well the user seeks.
19:54:57
사용자가 마지막으로 사용한 시간을 이해하는 데 유용한 정보입니다.
This is the user scans and the look ups and maybe as well the user updates.
19:55:06
마지막 사용자 탐색과 마지막 사용자 스캔입니다.
And it is really nice information to understand when it was the last time used.
19:55:09
여기서 수정하겠습니다. 두 날짜를 하나로 합칠 수 있습니다.
So last user seek and the last user scan.
19:55:17
마지막 탐색이라면 여기서 null이 될 것입니다.
Let me just correct it over here. And actually, I can go and put those two dates in one date, because
19:55:23
이 두 값을 실제로 하나의 열에 넣을 수 있습니다.
If it's like the last seek, it's going to be null over here or the opposite.
19:55:27
여기서 null 함수 Kualis를 사용하여 그렇게 할 수 있습니다.
And now what we can do, we can go and put those two together actually in one column. Because when we have a value over here, it's going to be null and vice versa.
19:55:34
이 전체를 마지막 업데이트라고 부를 수 있습니다.
So we can do that using the null function Kualis. Like this. And we can get this over here.
19:55:41
모든 것을 이름을 바꿀 것입니다.
And we can call the whole thing last update. So like this.
19:55:45
이제 다 끝났습니다. 진행하겠습니다.
And maybe I'm going to go and rename all those stuff.
19:55:56
우리의 새로운 보고서를 확인해 보겠습니다.
all right so now we are done let's go and excuse it okay
19:55:59
이것이 우리의 쿼리입니다.
so let's go and check our new report over here so this
19:56:02
첫 번째 테이블에서 시작하겠습니다.
is our query and let's start with the first table for example the
19:56:05
세 개의 인덱스가 있습니다.
customers and go to the right side and now we can see that we
19:56:08
사용되지 않는 인덱스가 하나만 있습니다.
have three indexes and from these two indexes
19:56:11
비클러스터 인덱스가 사용되지 않고 있습니다.
we have only one index that is not used at all so we can see over here that the non-clustered index on the
19:56:18
국가에 대한 또 다른 인덱스가 있습니다.
country is not being used and that's because we
19:56:21
국가에 대한 인덱스가 있습니다.
have another index about the country that comes from the
19:56:24
테이블을 쿼리하는 것처럼 보입니다.
column store so it could be like this that you are querying the table
19:56:28
이 인덱스를 사용하고 싶습니다.
using the country but the sql saying
19:56:31
이 인덱스는 그다지 유용하지 않습니다.
i would like to go and use this index instead of the first one so
19:56:34
우리는 이 인덱스가 별로 유용하지 않다고 말할 수 있습니다.
we can say okay this one is not really useful maybe we
19:56:37
우리는 그것을 삭제할 수 있고, 나머지 부분을 보면 이 열 저장 인덱스가 두 번 사용되었고 다음은 한 번 사용되었습니다.
can go and drop it right and for the rest you can see okay this column store index is used twice and the next one is once again the numbers at your side might
19:56:46
다를 수 있으며, 다른 모든 테이블을 살펴보면
be different and if we have a look to all other tables we
19:56:49
많은 널 값이 있으므로, 이는 모든 인덱스가
have a lot of nulls so that means all those indexes
19:56:52
고객 데이터베이스에 생성되었음을 의미합니다. 확인해 보겠습니다.
that we have created on the db customers let me check
19:56:55
하나만 사용되고 있지만, 이제 당신은 인덱스를 사용했다고 말할 수 있습니다.
only one is used but now you might say you know what i've used the index
19:56:59
그런데 왜 여기서 그에 대한 숫자를 보지 못할까요? 그 이유는
but why i'm not seeing here any numbers about it well that's because
19:57:02
그 숫자들은 영원히 존재하지 않기 때문입니다.
those numbers will not live forever and
19:57:05
현재 우리는 로컬에서 익스프레스 에디션을 사용하고 있습니다.
we are using now the express edition locally at our
19:57:08
PC를 종료하고 클라이언트를 닫을 때마다
pc so each time you shut down your pc and you close the client that
19:57:12
데이터베이스도 종료되며, 이러한 통계는
database is going shutdown as well and those statistics can be
19:57:15
메모리에 있기 때문에 잃어버릴 수 있습니다. 실제 프로젝트에서는
lost because they are in the memory but in real projects the
19:57:18
숫자가 여기와 완전히 다를 것이며, 물론 현실적인 숫자를 얻을 수 있습니다.
number is going to be totally different than here and of course you're going to get realistic numbers
19:57:22
이제 사용되지 않는 것 중 하나를 목표로 해보겠습니다.
now let's try to target one of those not used
19:57:25
예를 들어, 이 인덱스를 사용해 보겠습니다. 이것은 제품에 대한 클러스터 인덱스가 아닙니다.
indexes so for example let's go with this index it is not clustered index on the product so let's go and query that currently it is completely
19:57:33
현재 완전히 사용되지 않고 있습니다. 그래서 제가 선택하면
not used so if i go and select it so
19:57:36
판매 제품에서 모든 항목을 선택합니다.
select star from sales products
19:57:40
제품이 대문자와 같을 때
where products equal
19:57:44
우리가 사용한 인덱스입니다. 다시 쿼리해 보겠습니다.
to caps so that's we have used the
19:57:47
우리 인덱스로 가서 그것이 잘 사용되고 있는지 확인해 보겠습니다.
index i think let's go back and query again
19:57:50
정확하며, 우리의 쿼리가 이 인덱스를 사용했음을 알 수 있습니다.
and let's go to our index and check whether it is used well it is correct so our query did use this index and we can see here
19:57:58
한 번 사용되었고, 이제 프로젝트에서 분석할 수 있습니다.
it is used once and now you can go and analyze in your project
19:58:02
테이블에 있는 모든 인덱스를 확인하고
all the indexes that you have on your tables and
19:58:05
쿼리와 함께 실제로 사용하고 있는지 확인할 수 있습니다.
you can see whether you are really using it with your queries or
19:58:08
쿼리를 사용하지 않는다면, 물론 그것에 대한 결정을 내려야 합니다.
not and if you are not using the query of course you have to make
19:58:11
결정을 내려야 할 수도 있습니다. 팀에서 질문해 보세요.
a decision about it maybe if you are working a team to ask
19:58:14
누가 그것을 만들었고 왜 만들었는지에 대해 질문해 보세요.
about it who did create it and why maybe there is like
19:58:17
데이터베이스에서 자주 사용되지 않는 작업이 있습니다. 아마도 한 달에 한 번 실행되는 작업일 수 있습니다.
one task in the database that is not frequently used maybe it's something that is run like once a month or something like that so So the index is needed, but not that frequently.
19:58:26
하지만 이제 우리는 이러한 인덱스에 대한 통찰력을 가지고 있습니다.
But still now we have like insights about what is going on with those indexes and whether we need them or not.
19:58:33
필요하지 않다면 삭제하세요. 알겠죠, 친구들?
And if you don't need them, go and drop them. All right, my friends.
19:58:36
여기 90%의 SQL 개발자들이 하지 않는 비밀이 있습니다.
So here is the secret that 90% of SQL developers don't do that's going to make you in one minute the hero of the projects.
19:58:44
프로젝트에 합류한 후, 모든 사람에게 인사하고 데이터베이스를 열었습니다.
So once I joined a project and after saying hello to everyone, I opened the database of the projects and do one query.
19:58:52
프로젝트의 인덱스 사용량을 확인합니다. 15년간 SQL을 다루며 90%의 인덱스가 사용되지 않았음을 알 수 있습니다.
I check the usage of the indexes of the projects. And I can tell you after working 15 years with SQL that 90% of indexes created in projects are totally untouched and unused.
19:59:04
모든 사용되지 않는 인덱스를 수집하고 팀과 논의합니다.
So I collect all unused indexes and discuss it with the team.
19:59:08
이 인덱스에 대한 실제 사용을 찾지 못하면 삭제합니다.
And if we don't find real usage for those indexes, we go and drop them.
19:59:13
모든 사용되지 않는 인덱스를 삭제한 후, 두 가지 큰 일을 한 것입니다.
So after dropping all those unused indexes, you have done two great things for the projects.
19:59:18
첫째, 데이터베이스에서 많은 저장 공간을 절약했습니다.
First, you have saved a lot of storage in the database.
19:59:22
둘째, 훨씬 더 중요한 것은 성능을 개선했습니다.
and second which is way more important you have improved
19:59:25
데이터베이스의 성능을 최적화했습니다.
and optimized the right performance on the database
19:59:28
첫날에 한 쿼리로 최적화했습니다.
so in your first day with one query you have
19:59:32
저장 공간을 절약하고 프로젝트에서 전문가처럼 빛날 수 있습니다.
optimized the performance of the database you have saved
19:59:35
저장 공간을 절약하고 전문가처럼 빛날 수 있습니다.
storage and you can shine like an expert in your projects
19:59:38
그렇지 않다면 지금 하세요.
so if you haven't done that do that now all
19:59:44
사용되지 않는 인덱스를 식별하는 것은 중요한 작업입니다.
right so now moving on to the next one as we learned identifying an unused index is
19:59:49
반면에, 누락된 인덱스를 식별하는 것도 매우 중요합니다.
an important task, but in the other hand, identifying a missing index is as well very important to improve the performance of your queries.
20:00:00
SQL Server에서는 누락된 인덱스에 대한 추천을 받을 수 있습니다.
In SQL Server you can get recommendations from the database itself about missing indexes for your query.
20:00:06
그럼 추천을 어디서 찾을 수 있는지 봅시다.
So let's see where we can find those recommendations. Alright, so now let's say that you are doing multiple queries and you are doing analysis and so on.
20:00:14
예를 들어, 여기 이 쿼리가 있습니다.
For example, I have this query over here. It is query on the
20:00:17
두 개의 테이블을 조인하고 색상과 날짜 키를 기준으로 데이터를 필터링합니다.
database AdventureWorks DW and I'm joining just
20:00:20
쿼리를 실행한 후 다음 정보를 얻었습니다.
two tables, the fact with the dimension and then filtering the data based on the colors and as well on the date key where I have like a range over here.
20:00:29
그래서 실행한 후 다음 정보를 얻었습니다. 연습하고 분석하는 동안 어떤 쿼리라도 될 수 있습니다.
So once I executed, I got the following informations. It could be any query that you are doing while practicing and analyzing and so on.
20:00:36
이제 느린 쿼리가 있다면 데이터베이스에서 누락된 인덱스에 대한 추천을 확인할 수 있습니다.
So now if you have like slow query and so on, you can go and check the recommendations from the database about missing indexes.
20:00:43
그렇게 하려면 데이터베이스 시스템의 메타데이터를 다시 확인하여 누락된 인덱스에 대한 추천을 볼 수 있습니다.
So in order to do that, we can go and check again the metadata from the database system to see the recommendations about the missing indexes.
20:00:51
그렇게 하러 갑시다. 이제 선택해야 하며 동적 관리
So let's go and do that. So we're going to go and select from and now we have to go and target the dynamic management
20:00:56
뷰는 이렇게 dm_underscore_db입니다.
views and it is like this dm underscore db
20:01:00
underscore missing index
underscore missing index
20:01:03
세부정보를 탐색해 봅시다.
details so let's go and explore
20:01:06
여기 있는 내용과 이 정보가
the content over here and don't forget that those information
20:01:10
서버의 캐시에 저장될 것입니다. 서버가 재시작되면 모든 정보를 잃게 됩니다.
is gonna be inside the cache of the server and
20:01:13
이제 제 쿼리에서 데이터베이스의 몇 가지 제안과 추천이 있습니다.
if there's like a restart or something in the server you will lose all those informations so now from my query there is a few suggestions and recommendations from the database
20:01:22
그것을 확인해 봅시다. 여기에는 네 가지 추천이 있습니다.
let's go and check it so we can see here there are four recommendations
20:01:25
데이터베이스의 누락된 인덱스에 대한
about missing indexes from the database so
20:01:28
이제 여기에서 첫 번째 추천을 확인해 봅시다. 테이블 이름을 확인할 수 있습니다.
now let's go and check the first recommendation over here you can
20:01:31
객체 ID에서 테이블 이름을 확인하거나
go and check the table name from the object id or you can find
20:01:34
여기에서 문장으로 찾을 수 있습니다. 데이터베이스가 제안하고 있습니다.
it here in the statements so here the database is suggesting an
20:01:37
테이블 차원 제품에 대한 인덱스를
index for the table dimension products and
20:01:41
컬럼 색상에 대한 인덱스를 만들 것을 추천합니다.
it is recommending us to make an index for the column color
20:01:44
우리 쿼리를 확인하면 여기에서 필터가 있습니다.
and that's because if you check our query we have like here a filter
20:01:47
우리가 색상이 검은색인 조건을 보고 있기 때문에
the word condition where we are seeing the color equal to black and
20:01:50
색상에 대한 인덱스가 없으므로 명확하게 제안하고 있습니다.
since we don't have an index on the color is clearly just suggesting
20:01:54
색상에 대한 인덱스를 사용하고 이 상황에서는
to use an index for the color and of course in this situation we can
20:01:57
비클러스터 인덱스를 사용하고 그 후에
go and use a non-clustered index now after that we have
20:02:00
같은 테이블 사실 인터넷에 대한 세 가지 추천이 있습니다.
three recommendations for the same table fact internet
20:02:03
판매에 대해 예를 들어 여기에서 주문 날짜 키에 대한 인덱스를 만들 것을 제안하고 있습니다.
sales so for example here it is suggesting to make an
20:02:07
여기에서 필터로 사용하고 제품 키에 대한 인덱스를 만들 것을 제안하고 있습니다.
index on the order date key because we are using it in the filter over here and as well suggesting to make an index for the product key since we are using it for the join so this is really nice report
20:02:19
데이터베이스의 누락된 인덱스에 대한
about missing indexes in the database and it could
20:02:22
당신이 생각하지 못했던 것들을 찾는 데 도움을 줄 수 있습니다
assist you to find out things that you didn't thought about
20:02:25
이 정보를 매우 신중하게 평가하세요
but here my recommendation is evaluate those informations
20:02:28
각 제안에 대해 인덱스를 생성하지 마세요
very carefully don't go and create like
20:02:31
정말 필요한지 생각해봐야 합니다
an index for each suggestions from the database you still have
20:02:34
이 쿼리를 자주 사용합니까? 그러니
to think about it is it really necessary do we really
20:02:37
각 추천에 대해 인덱스를 무작정 생성하지 마세요
use this query very frequently and so on so don't
20:02:41
SQL 데이터베이스에서 누락된 인덱스 추천을 찾는 방법입니다
go blindly creating indexes for each recommendations from the database so this is really nice tool and assistant for you in order to make a good strategy for your indexing.
20:02:50
이제 다음 단계로 넘어가서 인덱싱의 중복을 모니터링해야 합니다
So this is how you find the recommendations of missing indexes from SQL database.
20:03:00
여러 개발자와 팀으로 작업하는 경우
Okay, so now to the next step, we have to go and monitor the duplicates in indexing.
20:03:05
동일한 열에 대해 서로 다른 인덱스를 생성할 수 있습니다
If you are working in team with multiple developers and you are working parallely in order to optimize the performance of the queries, what might happen is that different developers
20:03:16
같은 테이블에서
creating different indexes for the same column
20:03:19
프로젝트에 깔끔하고 확고한 검토 프로세스가 있다면
in the same table but of course this must not happen if
20:03:22
프로젝트에 깔끔하고 탄탄한 리뷰 프로세스가 있습니다.
you have a clean and solid review process in the project
20:03:25
중복이 있는지 모니터링해야 합니다
but we are human and those things could happen so that's
20:03:28
열이 있는지 찾는 것이 미션입니다
why you have to monitor whether there are like duplicates
20:03:31
여러 인덱스에 관련된 열이 있는지
so the mission is to find whether there is a column
20:03:34
SQL에서 이를 모니터링하는 방법을 보겠습니다
that is involved in multiple indexes so let's
20:03:37
인덱스의 중복을 찾기 위해
see how we can monitor that in sql okay so now it's very simple
20:03:40
당신의 데이터베이스에서
in order to find the duplicates of indexes inside
20:03:44
이 테이블의 모든 인덱스 목록을 찾을 수 있습니다
your database so we have learned before that we can find a list
20:03:47
시스템의 인덱스
of all indexes in this table indexes in the system
20:03:50
테이블 이름을 얻기 위해 테이블과 조인합니다
schema and then we join it with the tables in order to get the
20:03:53
인덱스에 관련된 열을 찾기 위해
table name and then we have another table in order
20:03:56
그 정보를 인덱스 내에서 찾을 수 있습니다
to find the columns that are involved in the
20:03:59
인덱스 내에서 찾을 수 있는 정보를 인덱싱합니다.
index those informations we can find it inside the index
20:04:02
열의 전체 이름을 얻기 위해 열 테이블과 조인할 것입니다.
columns and now in order to get the full name of the columns
20:04:06
매우 간단하고 이해가 됩니다. 전체 쿼리를 실행해 보겠습니다.
we're going to go and join it with the columns table so it's
20:04:09
지금 보시다시피 테이블 이름으로 정렬되어 있습니다.
very simple and makes sense let's go and execute the whole query
20:04:12
열 이름과 함께 정렬되어 있습니다.
now as you can see it is sorted by the table name and
20:04:15
중복을 확인하기 위해 첫 번째 테이블을 확인해 보겠습니다.
the column name and that's because we can find them easier the
20:04:18
국가는 이 인덱스의 일부이며, 열이 있습니다.
duplicate so let's go and check the first table so the
20:04:22
비클러스터형 저장소이며, 다시 말해 국가는 관련이 있습니다.
country is part of this index where we have the column
20:04:25
고객의 국가가 있는 또 다른 인덱스에서 비클러스터형 저장소입니다.
store non-clustered and again the country is involved
20:04:28
이것은 물론 나쁜 것인데, 열 저장소로 할지 행 저장소로 할지 결정해야 합니다.
in another index where we have the customers country and this is a raw store non-clustered index so this is of course bad thing we have to go and decide now do we want it as a column store or a row store.
20:04:40
이 테이블을 확인하면 두 개의 다른 클러스터에서 이름을 찾을 수 있습니다.
And if we check as well this table, we can find the first name in two different clusters, the same story.
20:04:46
우리는 인덱스를 연습하고 만들고 있었기 때문입니다.
And that's because we were practicing and creating those indexes. And that's it.
20:04:50
이제 큰 스키마와 많은 인덱스가 있다면, 중복 여부를 이해하기 위해 플래그를 만들 것입니다.
But now if you have like large schema and a lot of indexes, I would go and make like a flag in order to understand whether we have a duplicate or not.
20:04:58
고유한 테이블 이름과 인덱스 이름의 행 수를 계산하여 확인합니다.
And that's by calculating the number of rows of
20:05:01
윈도우 함수를 사용하여 쉽게 할 수 있습니다.
unique table name and index name and we can do that very
20:05:04
행 수를 찾기 위해 count 함수를 사용할 것입니다.
easily using the window functions so let's have new row
20:05:07
테이블 이름과 열 이름을 기준으로 파티션을 나눌 것입니다.
and we're gonna go and use the function count since we want to find the number of rows over then we're gonna go and partition by we need the table name
20:05:19
이 열의 기대값은 하나여야 합니다.
and as well the column name our expectation
20:05:22
하나 이상이면 문제가 발생합니다.
of this column should be one if we have more than one
20:05:25
열이 두 개의 다른 인덱스에 포함되어 있다는 의미입니다.
then there is an issue and that means the column
20:05:28
열 이름으로 정렬하고 내림차순으로 실행해 보겠습니다.
is inside two different indexes and now let's go
20:05:31
특정 열에 대해 몇 개의 행이 있는지 확인할 수 있는 좋은 플래그입니다.
and sort it by the column name and descending so let's go and execute it and now we have here a nice flag where we can see how many rows we have for a specific column in a table
20:05:43
이런 열들은 괜찮습니다.
so if it's one like those columns they are fine
20:05:46
첫 네 행에는 문제가 있습니다.
those columns are involved only once in one index but
20:05:49
두 개의 인덱스가 같은 열에 대해 존재합니다.
for the first four rows we have here an issue because we
20:05:53
여기 첫 네 줄에 문제가 있습니다. 왜냐하면
count here two columns that means we have two indexes for the same column so as you can see the query is very simple and with that we have a nice report about that duplicates of indexes inside our database
20:06:08
인덱스를 유지하기 위해 한 가지 더 있습니다.
okay one more thing in order to maintain our indexes is by
20:06:11
통계 정보를 업데이트하는 것입니다. 데이터베이스 엔진은 보통
updating the statistics the database engines usually
20:06:15
어떤 인덱스를 사용할지 이해하기 위해 통계를 사용합니다.
use statistics in order to understand which
20:06:18
이 통계가 최신이 아니면 SQL이 잘못된 결정을 내릴 수 있습니다.
index should be used for our query and if these statistics
20:06:21
이 통계가 최신이 아니면 SQL이 잘못된 결정을 내릴 수 있습니다.
are not up to date sql gonna make wrong decisions
20:06:25
이제 이 의미를 이해해 봅시다. 테이블을 만들고 데이터를 삽입하기 시작한다고 가정해 보겠습니다.
so let's understand what this means now let's say that you have created a table and you start inserting data
20:06:31
이 새로운 테이블에 대해 데이터베이스 엔진이 가서
to this new table now the database engine gonna go and create your
20:06:34
새 테이블을 만들고 백그라운드에서 데이터를 삽입합니다.
new table and insert the data behind the scenes the
20:06:37
데이터베이스 엔진이 새 테이블에 대한 통계를 생성합니다.
database engine gonna go and create for your new table statistics
20:06:41
이는 데이터에 대한 메타데이터 정보와 같습니다.
it's like metadata information about your data
20:06:44
이는 데이터에 대한 보고서 또는 통찰력과 같습니다.
and that's like a report or insights about your
20:06:47
테이블에서 많은 정보를 찾을 수 있습니다. 예를 들어
table where you can find a lot of information like the
20:06:51
행의 수, 값의 분포를 찾을 수 있습니다.
number of rows the distribution of values in
20:06:54
열에서 고유한 값의 수와 히스토그램 및 패턴을 찾을 수 있습니다.
a column and as well we can find the number of distinct
20:06:57
값과 히스토그램 및 패턴.
values and histogram and patterns
20:07:00
테이블에 대한 많은 다른 정보가 있습니다.
and many other informations about your table
20:07:03
그렇다면 이제 질문은 왜 이러한 정보가 있는가입니다.
so now of course the question is why do we have those informations
20:07:07
데이터베이스에 있습니다. 이제 선택 쿼리를 실행한다고 가정해 보겠습니다.
in the database now imagine that you are doing select from where what can happen the database engine has to go and create an execution plan we're gonna learn about this later in details
20:07:18
이 쿼리를 실행하는 방법에 대한 로드맵입니다.
it is just a roadmap on how to execute this query
20:07:21
예를 들어 테이블에서 데이터를 로드하기 위해
so here for example in order to load the data from the table
20:07:25
다양한 방법이 있습니다. 테이블 스캔, 인덱스 스캔, 인덱스 탐색이 있습니다.
there are like different ways on how to do it so there is like
20:07:28
즉, 데이터베이스 엔진은 여기서 세 가지 방법이 있습니다.
a table scan index scan index seek so
20:07:31
이것을 수행하는 방법과 데이터베이스가
that means the database engine has here three different
20:07:34
어떤 방법을 사용할지 결정하기 위해.
ways on how to do it and now in order for the database
20:07:37
어떤 방법을 사용할지 결정하기 위해
to decide which way to use it
20:07:40
테이블의 통계를 읽고 정보를 수집할 것입니다. 몇 개의 행이 있는지 확인해보겠습니다.
gonna go and read the statistics of the table so it's gonna go and collect informations okay how many rows do we have are the informations
20:07:48
고유한 데이터 분포가 어떻게 되는지
are unique how is the distribution of the data and
20:07:51
통계와 숫자를 기반으로
so on and now based on those statistics and numbers the
20:07:54
데이터를 로드하기 위한 좋은 결정을 내릴 수 있습니다.
database can now make a good decision about
20:07:57
예를 들어 여기서 인덱스 스캔이 데이터를 로드하는 가장 좋은 방법입니다.
which methods to use in order to load the data so
20:08:01
우리 테이블을 로드하는 데 필요한 통계가 왜 중요한지
for example here the index scan is the best way to load
20:08:04
그래서 이제 여러분은 물어볼 수 있습니다. 이건 데이터베이스 내부의 문제인데, 왜 우리가 신경 써야 할까요? 문제가 있습니다.
our table so this is exactly why the database needs the statistics in order to make the correct decision and to use the correct index
20:08:13
예를 들어, 우리 테이블에는 50개의 행이 있습니다.
So now you might ask, okay, this is something internal for the database. Why do we have to care about it? Well, there is an issue.
20:08:20
다음 날 이 테이블에 약 100만 개의 행을 삽입했다고 가정해봅시다.
Now, for example, in our table, we have 50 rows.
20:08:22
문제가 발생할 수 있는 것은 이 테이블의 통계가 업데이트되지 않는 것입니다.
And let's say that in the next day you went and inserted to this table like around 1 million row.
20:08:28
통계는 여전히 50개의 행만 있다고 말할 수 있습니다.
Now, the issue that could happen is that the statistics will not get updated about this table.
20:08:33
즉, 이 테이블의 통계는 이제 구식입니다.
And the statistics can still say that we have only 50 rows.
20:08:37
즉, 이 테이블의 통계는 이제 구식이며
So that means the statistics of this table is now outdated.
20:08:42
쿼리할 때 SQL 엔진은 100만 개의 행에 대해 전혀 알지 못합니다.
and the big issue that once you query this table the
20:08:45
테이블에 삽입한 내용을 알지 못하게 됩니다.
sql engine don't know at all about the 1 million row
20:08:48
통계를 요청할 것이고, 50개만 있다고 대답할 것입니다.
that you have inserted in the table because it's going to go and
20:08:52
데이터베이스는 이것이 매우 작다고 판단할 수 있습니다.
ask the statistics and it's going to answer with only 50
20:08:55
테이블이므로 인덱스를 건너뛰거나 할 수 있습니다.
rows and the database can say okay this is very small
20:08:58
즉, 데이터베이스는 잘못된 결정을 내릴 수 있습니다.
table and let's maybe skip an index or something so
20:09:01
통계가 구식이기 때문입니다.
that means the database can make wrong decisions because
20:09:05
즉, 여러분의 작업은 이러한 통계를 모니터링하는 것입니다.
the statistics are outdated and now
20:09:08
계속 업데이트하는 것입니다. 그러면 어떻게 할 수 있는지 살펴보겠습니다.
your task is to monitor those statistics and
20:09:11
그래서 이제 우리가 해야 할 첫 번째 일은
to keep updating them so let's see how we can do that okay
20:09:15
우리의 통계가 최신인지 구식인지 확인하는 것입니다.
so now the first thing that we have to do is to find out whether our
20:09:18
통계가 최신인지 구식인지 확인해야 합니다
statistics are up to date or outdated in
20:09:21
그렇게 하려면 메타데이터에 접근해야 합니다
order to do that we have as well to access the metadata about
20:09:24
우리 데이터베이스에 대한 정보와
our database and for that as well we have tables and
20:09:27
그에 대한 동적 관리 기능이 있습니다
dynamic management functions in the system schema
20:09:30
여기서 통계에 대한 많은 세부 정보를 찾을 수 있습니다
where we can find a lot of details about the statistics and
20:09:34
통계를 모니터링하기 위해 쿼리를 준비했습니다
in order to monitor the statistics i have prepared a query
20:09:37
이와 같이 여기서는 stats라는 테이블을 사용하고 있습니다
like this so here i'm using a table called stats where
20:09:41
여기서 데이터베이스 내 모든 통계의 목록을 얻을 수 있습니다
here you're gonna get a list of all statistics inside our database
20:09:44
통계의 이름과 그에 따라 테이블 이름을 얻기 위해
and the name of the statistics and then i'm joining it
20:09:47
동적 관리 기능이 매우 중요합니다
with the tables in order to get the table name and what
20:09:50
여기서 마지막 업데이트와 행 수, 수정 수와 같은 중요한 정보를 얻을 수 있습니다
is very important is the dynamic management function
20:09:53
그럼 쿼리를 실행해 보겠습니다
so here we're gonna get very important information like the last update and the number of rows and the number of modifications
20:10:01
여기서 테이블 이름과 통계 이름을 볼 수 있습니다
so let's go and query it so here we
20:10:04
그리고 통계가 마지막으로 업데이트된 시간이 매우 중요합니다
can see information like the table name the statistics name
20:10:07
그럼 이제 테이블을 확인해 보겠습니다
and now it's very important when the last time the statistics
20:10:11
고객 데이터베이스에서 통계 이름을 볼 수 있습니다
get updated so now let's go and check our table
20:10:14
그리고 마지막 업데이트가 매우 중요합니다
db customers we can see here the statistics name
20:10:17
이것은 통계가 얼마나 오래되었는지를 알려줍니다
and what is very important is the last update so
20:10:20
제 경우에는 약 4일 정도입니다
this tells us how old is the statistics so
20:10:23
그리고 이 테이블의 총 행 수를 찾을 수 있습니다
for me it is like four days and then we can find the total number
20:10:26
이제 매우 중요한 것은 수정 수입니다
of rows in this table and now what is very important is
20:10:30
테이블에서 수행된 수정 수입니다
the number of modifications that have been done on
20:10:33
19일에 통계를 업데이트한 후
the table so after updating the statistics on the 19th
20:10:36
10월에 약 15개의 행이 수정되었습니다
of october there were around 15 rows that
20:10:39
이것은 삽입, 업데이트 또는 삭제일 수 있습니다
got modified this could be an insert update
20:10:43
삭제하여 테이블에서 수행되는 모든 작업이
delete so any operation on the table considered to be
20:10:46
수정으로 간주되므로, 이를 통해 많은 수정이 있음을 알 수 있습니다.
a modification so with that you can see you there were a lot of modifications
20:10:49
이 통계는 업데이트되어야 하며, 이제
so this statistics should be updated so now for
20:10:52
고객 테이블에서 통계를 확인할 수 있습니다.
the table customers you can see that the statistics
20:10:55
최신 상태이므로 수정 사항은 0입니다.
are up to date so we have here zero as a modifications and
20:10:59
따라서 통계를 업데이트할 필요가 없으며, 데이터베이스 내에서 통계 정보를 확인하여 업데이트 여부를 결정할 수 있습니다.
there will be no need to update the statistics so this is how you can go and check the statistics informations inside your database in order to make a decision should i update the statistics or not
20:11:10
이제 고객 테이블의 통계를 업데이트하고 싶다고 가정해 보겠습니다. 여기 여러 통계가 있습니다.
So now let's say that I would like to go and update the statistics of our table DB customers. Now as you can see, we have here multiple statistics.
20:11:17
이 테이블에서 통계를 확인할 수 있으며, 인덱스에 대한 통계도 있습니다.
So over here, we have this statistics on this table and as well we have the statistics on the index.
20:11:24
하나의 테이블에 여러 통계가 있으며, 테이블 자체와 이 테이블의 각 인덱스에 대한 통계가 있습니다.
So as you can see, we have here multiple statistics in one table, one for the table itself, and one for each index that we have in this table.
20:11:32
하나만 업데이트하고 싶다고 가정해 보겠습니다.
So now let's say that I would like to go and update the statistics only for one.
20:11:36
이 테이블의 모든 것을 업데이트하고 싶지 않습니다.
i don't want to update everything in this table only for one
20:11:39
통계를 업데이트합시다. 매우 간단할 것입니다.
statistics let's go and do that so it's going to be
20:11:42
통계를 업데이트하는 것이며,
very simple updates statistics and
20:11:45
이름을 지정해야 하므로 sales db customers가 될 것입니다.
then we have to go and mention the name so it's going to be sales db customers
20:11:49
그 이름을 지정해야 하며,
and then we have to specify the name of that
20:11:52
통계를 가져와서 실행합시다. 매우
statistics so let's go and get this over here and let's
20:11:55
빠르게 실행하고 쿼리를 다시 실행하여 확인합시다.
go and execute it so it was very
20:11:58
데이터를 확인합시다. 이제 찾아보겠습니다.
fast let's go and re-execute our query and check
20:12:01
정확히 이 것이었으며, 보시다시피 업데이트되었습니다.
the data so now let's go and find it it
20:12:05
행 수는 5이며,
was exactly this one and as you can see it just got
20:12:08
수정 사항은 0입니다.
updated and the number of rows is five and the number
20:12:11
따라서 이 테이블에 대한 최신 통계가 있습니다.
of modifications is zero so we have now an
20:12:14
나머지를 업데이트하고 싶지만 하나씩 하기를 원하지 않습니다.
up-to-date statistics for this table but let's
20:12:17
여기서 동일한 작업을 수행하되, 아무 것도 지정하지 않습니다.
say that i would like to go and update the rest but i don't want to do it one by one so what we can do we can just copy the
20:12:24
통계의 이름을 지정하지 않으므로, 통계를 업데이트하라고 말하고 있습니다.
same thing over here but we don't specify any
20:12:27
통계의 이름을 업데이트한다고 말하고 있습니다.
name of the statistic so we are saying update statistics
20:12:31
그리고 테이블 이름만으로 실행해 보겠습니다.
and then only the table name so let's go and execute it
20:12:34
이제 우리가 모든 통계를 업데이트할 것입니다.
so now what can happen is we're going to go and update all the statistics
20:12:37
이 테이블에 속하는 것을 확인해 보겠습니다.
that belongs to this table so let's go and check
20:12:40
우리의 쿼리를 다시 실행해 보니 모든 것이 사라졌습니다.
our query again now you can see everything disappeared
20:12:44
DB 고객은 수정 문제 없이 완전히 최신 상태입니다.
and the db customer is completely up to date with no modifications problem so this is how you can go and update your table and you can do then
20:12:54
나머지 부분도 마찬가지지만 이제 한 가지 더 있습니다.
for the rest as well but now there is like one more thing where
20:12:57
전체 통계를 업데이트할 수 있습니다.
you can go and update the statistics of the whole
20:13:00
하지만 주의하세요, 시간이 오래 걸릴 수 있습니다.
database but beware this might take
20:13:03
정말 오랜 시간이 걸릴 것이며, 이를 실행하여
really long time and we're gonna do that by executing a
20:13:06
특별 저장 프로시저를 실행합니다.
special stored procedure so execute sp update
20:13:10
이 통계를 업데이트해 보겠습니다.
stats this one over here let's
20:13:13
이제 완료되었고, 꽤 긴 로그가 있습니다.
go and do that and now it is done and
20:13:17
우리는 큰 데이터베이스가 아니기 때문에 빠르게 실행됩니다.
we have here a pretty long log it runs fast because we
20:13:20
실제 데이터베이스와 비교할 수 없습니다.
don't have a big database it is very small database so
20:13:23
이제 SQL이 모든 것을 처리하고 있습니다.
it's not compared to any real databases so
20:13:26
데이터베이스에 있는 모든 것을 업데이트하려고 합니다.
now we can see over here that sql is going through everything
20:13:30
데이터베이스에 있는 것과 통계를 업데이트하려고 하는 것
that you have in the database and trying to update the statistics so
20:13:33
업데이트할 것이 없고 수정 사항이 없었습니다.
in many situations it's going to be not necessary because there
20:13:36
그래서 데이터베이스는 필요 없다고 말할 만큼 똑똑합니다.
is nothing to update there were no modifications and so on
20:13:39
그리고 건너뛰게 됩니다. 이제 제가 보통 하는 방식은
that's why the database is smart enough to say no it is not required
20:13:43
주말에 작업이 있는 프로젝트에서입니다.
and it go and skip it so now how i usually do it in
20:13:46
전체 데이터베이스 통계를 업데이트합니다.
my project that I have like a job on the weekend
20:13:49
모든 테이블과 인덱스가
where it's gonna go and update the whole database statistics
20:13:53
최신 통계를 갖도록 합니다.
so that I make sure all my tables and indexes
20:13:56
최신 통계가 필요합니다.
having up-to-date statistics of
20:14:00
작은 데이터베이스가 있다면 매일 실행할 수 있지만, 시간이 오래 걸린다면 주말에 예약할 수 있습니다. 프로젝트에서 하루에 많은 새로운 데이터가 들어올 것이라는 것을 알고 있다면
course if you have small database you can run this like every day but if this takes a long time then you can schedule it in the weekend and as well if I know in the project that there will be in one day
20:14:10
많은 새로운 데이터가 들어오고 있으므로 데이터 마이그레이션을 하고 있습니다.
a lot of new incoming data so we are doing some kind
20:14:14
데이터 마이그레이션이 완료된 후 통계를 업데이트합니다.
of data migrations so i go and update the statistics after
20:14:17
데이터 마이그레이션이 완료된 후 최신 통계를 유지하기 위해
the data migration is done just to make sure we have up-to-date statistics
20:14:21
이렇게 해서 데이터베이스의 통계를 모니터링하고 업데이트합니다.
so this is how we monitor and update the statistics of
20:14:24
데이터베이스 괜찮아
the database okay
20:14:29
이제 마지막 작업으로 넘어가겠습니다. 일반적으로 인덱스를 모니터링하고 관리하기 위해 인덱스를 모니터링하는 것입니다.
so now moving on to the final task that i usually do in order to monitor and manage the indexes is to monitor the index
20:14:36
시간이 지남에 따라 데이터가 테이블에 삽입, 업데이트, 삭제됨에 따라 조각화됩니다.
fragmentations over the time as your data is inserted updated deleted into your tables
20:14:43
인덱스는 조각화될 수 있습니다. 그래서 조각화란 무엇인가요?
indexes can become fragmented so what is
20:14:46
조각화란 사용되지 않는 공간이 있다는 것을 의미합니다.
fragmentation it means like there is unused spaces
20:14:49
데이터 페이지에 데이터베이스가 이를 채우지 않거나
in your data pages and the database is not filling
20:14:52
데이터가 더 이상 인덱스에서 올바르게 정렬되지 않는 경우입니다. 이는 물론 저장소의 비효율적인 사용으로 이어지고 쿼리 속도를 늦출 것입니다.
them or your data is not anymore sorted correctly in the index and this of course leads to inefficient use of the storage and as well gonna slow down your queries
20:15:08
SQL에서는 모든 것을 다시 정리하기 위해
and in sql in order to get everything organized again
20:15:11
두 가지 방법이 있습니다. 첫 번째 방법은 재구성입니다. 이는 인덱스의 리프 레벨을 조정하여
we have two methods the first method is reorganize so it's gonna go and defragment the leaf level of the index in order to get it
20:15:20
논리적 순서로 다시 정리하고 정렬합니다.
organized and sorted again with the logical
20:15:23
이 작업은 매우 가벼운 작업이며
order so it is very light operation and it
20:15:26
사용자가 테이블을 사용하는 것을 차단하지 않습니다.
will not block the user from using your table and
20:15:29
두 번째 방법은 재빌드라고 불리는 무거운 작업입니다.
the second method called rebuild this is heavyweight
20:15:32
전체 인덱스를 삭제하고
operation it's gonna go and drop the whole index
20:15:35
처음부터 다시 생성할 것입니다.
and recreate it from the scratch and
20:15:38
이는 물론 데이터가 다시 정렬될 뿐만 아니라
this means of course not only the data gonna get sorted again but
20:15:42
데이터 페이지 내부의 조각화도
as well the fragmentations inside your data pages and
20:15:45
제거될 것입니다. 그러면 SQL에서 이를 수행하는 방법을 살펴보겠습니다.
the index gonna be eliminated so let's see how we
20:15:48
좋아요, 이제 데이터베이스로 돌아갑니다.
can do that in sql okay so now back to our database and
20:15:51
우리가 해결해야 할 첫 번째 질문은
the first question that you have to ask do we have an issue with
20:15:54
인덱스의 단편화 문제입니다. 그래서 우리는
the fragmentations in our indexes so we have to check the
20:15:57
데이터베이스의 인덱스 건강 상태를 확인해야 합니다.
health of our indexes in the database and in
20:16:00
이를 위해 시스템 메타데이터로 다시 가야 합니다.
order to do that we have again to go to the system metadata
20:16:04
우리가 가지고 있는 것과 그들의 동적 관리
that we have and we're gonna check their dynamic management
20:16:07
함수를 확인할 것입니다. 그래서 특별한 함수가 있습니다.
functions so there is like special functions in order to
20:16:10
SQL 서버에서 답을 얻기 위해 그렇게 하겠습니다.
get an answer in the sql server let's go and do that so
20:16:14
함수에서 스타를 선택하겠습니다.
we're gonna go and select star from the function
20:16:17
그래서 sys입니다. sys로 갈 것입니다.
so it is sys dot so it's gonna be sys
20:16:20
dot dm db index
dot dm db index
20:16:23
물리적 상태입니다. 이것은
physical states this one and this is a
20:16:26
우리가 몇 가지 매개변수를 전달해야 하는 함수입니다.
function that we have to pass few parameters we will not go in details just
20:16:29
이와 함께 db id를 제공해야 하고
following with this so we have to give it the db id and
20:16:34
null, 또 다른 null, 세 번째 null, 마지막 하나는 제한될 것입니다.
a null another null and a third null and the last one gonna be limited so we have to do it like
20:16:40
그래서 우리는 이렇게 해야 합니다.
is so let's go and query it now what do we find we have
20:16:43
이제 쿼리를 실행해 보겠습니다. 무엇을 찾았는지
the object id we have the index id and few other
20:16:47
객체 ID, 인덱스 ID 및 몇 가지 다른 정보가 있습니다.
formations but the most important one is the
20:16:50
가장 중요한 것은 평균 단편화 비율입니다.
average fragmentation in percent so this column gives
20:16:53
이 열은 인덱스의 단편화 정도를 제공합니다.
us the degree of the fragmentations in our index if
20:16:56
0이면 완벽하며, 단편화가 없습니다.
it is zero then it is perfect we have no
20:16:59
인덱스가 매우 건강하지만 100이면 완전히 엉망입니다.
fragmentation in the index and our index is very healthy but if it is like 100 then that means is completely out of order and we have to do something about it.
20:17:10
이제 당신은 어떤 객체인지, 어떤 인덱스인지 모를 수도 있습니다.
And now you might say, you know what, I don't know which object is that and which index.
20:17:14
sys.tables와 sys.index와 같은 몇 가지 테이블을 조인해야 합니다.
Well, you have to go and join a few tables like the sys.tables and sys.index in order to get those informations.
20:17:20
그래서 우리는 첫 번째 쿼리에서 했던 것처럼 그렇게 해야 합니다.
So we have to go and do that like we have done in the first query. So offline I have done that.
20:17:26
테이블과 인덱스를 조인하고 평균 단편화 및 비율로 데이터를 정렬하고 있습니다.
So I joined with the tables and the indexes and I'm sorting the data by the average fragmentations and percentage
20:17:32
내림차순으로 문제를 시작 부분에 가져오기 위해
descending in order to get the problems at the start because we
20:17:36
우리가 높은 비율에 관심이 있으므로 가서
are interested where we have high percentage so let's go and
20:17:39
이것을 실행하고 이제 데이터베이스를 연습하고 있으므로
execute this and now since it is practicing database i didn't
20:17:42
데이터를 삽입하지 않았습니다. 그러나 실제 프로젝트에서는
insert any data and so on but in real projects you
20:17:45
여기에서 다른 숫자를 얻을 수 있으며 여기에
will get here different numbers and here is
20:17:48
조각화 비율에 대한 내 권장 사항이 있습니다. 비율이
my recommendations about the percentage if the fragmentation is
20:17:51
0과 10 사이이면 모든 것이 괜찮고 아무것도 할 필요가 없습니다. 그러나 비율이
between like 0 and 10 that means everything is like okay and you don't have to do anything about it but if the percentage is
20:17:58
10과 30 사이이면 여기에서
between like 10 and 30 then here
20:18:01
무언가를 해야 하므로 여기에서 재구성 방법을 사용하라고 권장합니다.
we have to do something about it so here i recommend to use the reorganize
20:18:05
데이터를 다시 올바르게 정렬하기 위해
methods in order to sort the data again correctly
20:18:08
30%가 넘으면 여기에서
but if you have more than 30 percent then here
20:18:11
내 권장 사항은 전체 인덱스를 재구성하라는 것입니다.
my recommendation is to go and rebuild the whole index
20:18:14
데이터가 잘못된 순서일 뿐만 아니라 인덱스에 새로운 공간이 있으므로
because not only the data is in wrong order but as well there is a new spaces in your database in the index so you have to do something about it so now let's go and imagine one of those indexes for example this one over here
20:18:26
조각화가 15%입니다. 이제 우리가 해야 할 일은 이 인덱스를 재구성하는 것입니다.
has fragmentation of 15%. So now what we have to do is to go and reorganize this index. Let's see how we can do that.
20:18:33
여기에서 다음과 같이 말해 보겠습니다. ALTER INDEX. 그런 다음 인덱스 이름이 필요합니다.
So let's go over here and say the following. Alter, index. And then we need the index name.
20:18:39
여기에서 가져오고 인덱스가 존재하는 테이블 이름을 언급해야 합니다.
So let's go and get it from here. And then you have to mention the table name where the index exists. So we have it from the customers.
20:18:46
판매, 고객에서 가져옵니다. 이제 인덱스를 편집하고 SQL에 무엇을 할지 알려야 합니다.
So from sales, customers. So now we are editing the index and we have to tell SQL what to do now.
20:18:53
인덱스를 재구성하려고 합니다. 따라서 재구성 키워드를 사용합니다.
So we just want to reorganize the index. So you go and use the keyword reorganize. So reorganize.
20:18:59
그게 전부입니다. 매우 간단합니다. 그래서 가서 그렇게 해봅시다.
And that's it. This is very simple. So let's go and do that. And as you can see, it is completed.
20:19:05
그리고 매우 빨랐습니다. 데이터베이스가 작기 때문입니다.
And it was very fast because we have small database. But sometimes it takes a little more time if you have a big index and big table.
20:19:11
재구성 후에 다시 테이블을 확인하고 결과를 확인할 수 있습니다.
So after reorganizing, you can go and again, check the table over here and see the results. And it should be like here, zero.
20:19:18
이제 조각화가 약 50%인 다른 인덱스를 살펴보겠습니다.
Now let's see that we have another index where the fragmentation around like 50%.
20:19:23
가서 복사하고 이번에는
so let's go and copy it and this time instead of
20:19:26
재구성 대신 재구성을 할 것입니다.
reorganize we're gonna do rebuild so i'm
20:19:29
전체를 가져가고 이번에는 이 인덱스를 재구성하겠습니다.
gonna take the whole thing and this time we're
20:19:32
이 인덱스를 여기서 다시 구축할 것입니다.
gonna go and rebuild this index over here on the
20:19:35
같은 테이블에서 재구성하는 대신 다시 구축하겠습니다.
same table and instead of reorganize we're gonna say rebuild
20:19:39
그래서 이제 그것을 실행해 보겠습니다. SQL은 전체 인덱스를 삭제하고 처음부터 생성합니다.
so let's go and execute that and with that sql did drop the whole index and create it from the scratch and this is usually takes more time than and reorganize of course.
20:19:50
다음 단계는 조각화를 다시 확인하는 것입니다.
And the next step of course is to go and check again the fragmentations and so on.
20:19:54
인덱스를 건강하게 유지하고 조각화를 제거하는 방법에 대한 모든 것입니다.
So that's all about how to make your index healthy and remove the fragmentation
20:20:00
인덱스에서. 알겠죠, 친구들?
from your index. Alright my friends
20:20:03
보시다시피 쿼리 성능을 개선하는 것은
so as you can see improving the performance of your queries doesn't
20:20:06
생성하는 것으로 끝나지 않습니다. 항상 능동적으로 대처하는 것이 중요합니다.
end by creating them it's all about staying proactive
20:20:10
그래서 인덱스 사용을 모니터링하고 확인하세요.
so monitor the usage of the indexes check
20:20:13
누락된 인덱스가 있는지 확인하고 항상
whether there are any missing indexes and always make
20:20:16
데이터베이스 통계가 최신인지 확인하고 조각화를 주의 깊게 살펴보며 건강한 인덱스를 유지하세요. 그래서 이렇게 인덱스를 생성한 후 관리하고 모니터링하는 방법을 배웠습니다.
sure the statistics of the database are up to date and keep your eyes on the fragmentation and make sure you have healthy indexes so with that you have learned how I manage and monitor the indexes once I create them
20:20:28
그리고 이 단계들을 따르기를 정말 추천합니다. 알겠죠, 친구들.
and I really recommend you to follow those steps. All right, friends.
20:20:36
이제 복잡한 분석 SQL 쿼리가 있고 많은 조인과 집계가 포함되어 있지만 느리다고 가정해 봅시다.
So now let's say that you have a large, complex, analytical SQL query and it involves a lot of joins and aggregations and so on, but it is slow.
20:20:46
물론 인덱스를 사용하여 쿼리 성능을 최적화하고 싶습니다.
And of course, you want to go and optimize the performance of your query by maybe using indexes.
20:20:51
그렇다면 큰 질문은, 이 인덱스를 어디에 구축할 것인가? 어떤 테이블에? 어떤 열에?
And now the big question is, where exactly I'm going to go build this index? On which table? On which columns?
20:20:57
즉, 문제의 정확한 위치를 이해해야 합니다. 테이블을 조인하는 것인가, 데이터를 정렬하는 것인가, 아니면 집계 때문인가요?
So that means you have to understand where exactly the problem is. Is it by joining tables or sorting data or by the aggregations?
20:21:05
이 모든 질문에 답하기 위해 실행 계획이라는 것이 있습니다. 그게 뭐죠?
Now, in order to answer all those questions, we have something called execution plan. So what is that?
20:21:12
실행 계획은 데이터베이스가 쿼리를 단계별로 처리하는 방법을 보여줍니다.
The execution plan is going to show you how the database exactly process your query step by step.
20:21:19
이것이 우리가 필요한 것입니다. 성능 문제가 있는 정확한 위치를 보여줄 것입니다.
And this is what we need. It's going to show us where exactly we have a performance issue.
20:21:24
다시 말해, 실행 계획은 SQL 데이터베이스가 어떻게 생각하는지를 보여주는 창과 같습니다.
So, in other words, the execution plan is like your window on how the SQL database thinks.
20:21:30
그것을 이해하면 인덱스를 구축하는 올바른 결정을 내릴 수 있습니다. 그러니 이것이 정확히 무엇을 의미하는지 이해해 봅시다.
And once you understand that, then you're going to make the right decision on building an index. So let's understand exactly what this means.
20:21:37
좋아요, 이제 테이블에서 선택하고 다른 테이블과 데이터를 조인하는 쿼리를 실행한다고 가정해 봅시다.
Okay, so now let's imagine that you are doing a query like selecting from table and then joining the data with another table.
20:21:44
이 쿼리를 실행하면 데이터베이스 엔진이 즉시 디스크에서 데이터를 가져오지 않습니다.
So now once you execute this query, the database engine will not go immediately and start fetching data from the disk.
20:21:51
그 대신, 먼저 SQL은 계획을 세워야 합니다.
But instead of that, first, the SQL has to make a plan.
20:21:54
그래서 목적지에 도달하기 위해 최적의 경로를 찾기 위해 구글 지도를 확인하는 여행 계획을 세우는 것과 같습니다.
So it's like you are planning a trip where you check the Google map in order to find the best route in order to reach the destination.
20:22:02
실행 계획은 정확히 같은 것입니다. 데이터베이스는 먼저 쿼리를 실행하는 방법을 계획해야 합니다.
And the execution plan is exactly the same thing. The database has first to plan how to execute your query.
20:22:09
그리고 쿼리와 통계에 따라 이 계획을 단계별로 구축할 것입니다.
And it's going to build this plan step by step based on your query and as well the statistics.
20:22:14
예를 들어, 첫 번째 단계는 테이블에서 데이터를 가져오는 방법입니다.
So the first step, for example, how to get the data from the tables.
20:22:19
여기에는 인덱스 스캔이나 전체 테이블 스캔과 같은 여러 방법이 있습니다.
And there are like multiple ways like scan index or full table scan.
20:22:22
그 후에는 어떤 종류의 조인을 할 수 있을지 결정해야 합니다. 해시 조인인가요, 루프 조인인가요?
And then after that, it needs to decide which type of joins can be done. Like is it a hash join or a loop join?
20:22:29
이 계획의 마지막에는 선택 문이 있을 것입니다.
And then at the end of this plan, it's going to be the select statements.
20:22:32
실행 계획이 준비되면 데이터베이스 엔진이 단계를 구현하기 시작합니다.
So once the execution plan is ready, the database engine going to start implementing the steps.
20:22:37
예를 들어, 디스크에서 테이블을 읽기 시작할 것입니다.
So it's going to go and start reading your tables, for example, from the disk.
20:22:41
그 후에는 테이블을 조인하고 열을 선택한 다음 최종 사용자에게 결과를 보냅니다.
And then after that, it's going to join the tables and then select the columns and send at the end the results to the end user.
20:22:48
모든 작업이 완료되면 데이터베이스 엔진이 이 실행 계획을 가져와 캐시에 저장할 수 있습니다.
And now once everything is done, the database engine can do one more thing where it's going to go and take this execution plan and store it at the cache.
20:22:56
데이터베이스 엔진은 유사한 쿼리가 있을 경우 이 계획을 재사용할 수 있습니다.
And that's because the database engine can go and reuse this plan if we have a similar query.
20:23:03
예를 들어, 동일한 쿼리를 다시 실행하면 데이터베이스 엔진이 이를 동일한 쿼리로 인식할 수 있습니다.
So for example, if you go and execute the same query again, the database engine here can understand how this is the same query.
20:23:10
우리는 이미 그에 대한 실행 계획을 구축했습니다.
We have already built an execution plan for that.
20:23:13
그래서 캐시를 확인할 수 있고 즉시 캐시에서 가져오는 것이 훨씬 빠릅니다.
So it can go and check the cache and it is way faster to get it immediately from the cache instead of building it.
20:23:19
이 시나리오에서는 데이터베이스 엔진이 어떤 결정을 내릴 필요가 없습니다.
So in this scenario, the database engine doesn't have to make any decisions or something like that.
20:23:24
캐시에서 계획을 가져와 즉시 실행을 시작할 것입니다.
It's going to go and get the plan from the cache and start immediately by executing the plan.
20:23:29
물론 데이터베이스 엔진은 사용자에게 실행 계획을 숨기지 않을 것입니다.
And of course, the database engine will not hide the execution plan from the users.
20:23:33
데이터베이스가 데이터를 어떻게 로드했는지, 어떻게 조인되었는지 확인할 수 있습니다.
You can go and check it because you can go and check how the database loaded the data, how they are joined and so on.
20:23:40
그럼 올바른 결정을 내려 쿼리를 최적화할 수 있습니다. 아마도 인덱스를 추가하여.
And then you can make a correct decision on how to optimize your query, maybe by adding indexes.
20:23:46
그럼 SQL로 돌아가서 어떻게 하는지 봅시다.
So let's go back to SQL and see how we do that okay
20:23:53
이제 데이터베이스 adventureworks dw에서 작업할 것입니다.
so now we're gonna work with the database adventureworks dw
20:23:56
2022년 이제 테이블로 가겠습니다.
2022 and now we're gonna go to our tables and
20:23:59
사실 사실 리셀러 판매에 집중할 것입니다.
we're gonna focus on the fact fact reseller sales
20:24:02
이 테이블의 유형을 확인해 보겠습니다.
now let's go and check the type of this table so if you go
20:24:06
인덱스에 가면 기본 키에 인덱스가 있음을 알 수 있습니다.
inside it and go to the indexes you can see that
20:24:09
우리는 기본 키에 인덱스가 있어서 클러스터형 행 저장소 인덱스가 있습니다. 즉, 데이터가 구조화되어 있습니다.
we have an index on the primary key so we have a clustered row store index so that means the data is structured
20:24:16
이 p3에서 이제 우리가 할 것은 미러를 생성하는 것입니다.
in this p3 so now what we're gonna do we're gonna go and create a mirror
20:24:19
이 테이블의 미러를 생성하지만 인덱스는 없습니다. 그래서
of this table but without any indexes so it's
20:24:22
매우 간단한 선택입니다. 우리의 사실에서 모든 것을 선택합니다.
gonna be very simple select star from our fact
20:24:26
리셀러 판매를 삽입할 수 있습니다.
reseller sales and we can insert it
20:24:30
새 테이블에 삽입할 것입니다. 그래서 사실
in a new table so into fact
20:24:33
리셀러 판매를 삽입할 것입니다. 저는
reseller sales and i'm
20:24:36
힙을 위해 hp라고 부를 것입니다. 그래서 실행해 보겠습니다. 이제 새 테이블에 약 60,000개의 행이 삽입되었습니다. 이제 테이블을 새로 고쳐서 새 테이블을 찾을 수 있습니다.
gonna call it hp for heap so let's go and execute it and now you can see we have inserted in the new table around 60 000 rows so now we can go and refresh our tables in order to find our new table.
20:24:47
여기 공장 판매자가 있습니다. 인덱스를 확인하면 찾을 수 없습니다.
So it is over here factory seller sales. And if you check the indexes, you will not find any.
20:24:53
즉, 힙 테이블입니다. 이제
So that means it is a heap table. Now let's
20:24:56
우리의 새 테이블에서 매우 간단한 쿼리를 실행해 보겠습니다.
go and do a very simple query on top of our new
20:24:59
테이블에서 공장에 대해 모든 것을 선택합니다.
table so select star from the factory
20:25:03
판매자 hp처럼 이렇게 실행해 보겠습니다.
seller hp like this so let's go and execute it and
20:25:06
결과를 얻었습니다. 이제 질문은
we got the results so now the question is i would like to see
20:25:09
이 쿼리의 실행 계획을 보고 싶습니다. 실행 계획을 보려면
the execution plan of this query now in order to see
20:25:12
여기 툴바로 가서 세 가지가 있습니다. 첫 번째는 표시합니다.
the execution plan we're gonna go to the toolbar over here and we have three things the first one is says display
20:25:20
예상 실행 계획이 있으며 또 하나는
estimated execution plan and we have another
20:25:23
실제 실행 계획을 포함하라고 합니다.
one says include actual execution plan
20:25:26
세 번째는 실시간 쿼리를 포함하라고 합니다.
and a third one says include live query
20:25:29
통계입니다. 이제 질문은
statistics so now the question is what are the differences between
20:25:33
그들 사이의 차이점은 무엇인가요? 첫 번째로 표시된 예상
them let's start with the first one displayed estimated
20:25:36
실행 계획을 시작하겠습니다. 여기서 SQL이
execution plan so here what can happen sql gonna go
20:25:39
실행 계획을 추측할 수 있습니다. 쿼리를 실행하지 않고
and guess the execution plan without executing
20:25:42
이것은 단지 추정입니다. 두 번째는
the query so it's just an estimation so this
20:25:45
실제 실행 계획입니다. 이것은 실행 계획을 보여줄 것입니다.
is only a guess and estimation the second one is
20:25:48
실행 계획을 보여줄 것입니다.
the actual one so this is going to show you the execution plan
20:25:52
당신의 쿼리를 처리하는 데 사용되는 계획입니다.
that is used in order to process your
20:25:55
쿼리를 실행한 후 어떤 계획이 사용되는지 보여줄 것입니다.
query so after executing your query SQL going to show for you which plan is used so that means the estimated plan it is something before
20:26:03
쿼리를 실행한 후 실제 계획은 쿼리 실행 후의 것입니다.
executing your query and the actual plan is something after executing your query and the
20:26:10
쿼리를 실행하는 동안입니다.
third one is while executing the query so
20:26:13
쿼리의 실시간 실행을 보게 될 것입니다.
you're gonna get a real-time execution of your query and you
20:26:17
실행 계획이 어떻게 작동하는지 볼 수 있습니다.
can see how your execution plan is working so
20:26:20
추정 실행 계획을 활성화해 보겠습니다.
now we can go and try that let's go and activate the estimated
20:26:23
여기에서 새로운 출력을 볼 수 있습니다.
execution plan now we can see over here we have a new
20:26:26
실행하지 않고 추정된 실행 계획입니다.
output where you can see like few boxes so this
20:26:29
여기에서 실제 실행 계획으로 전환해 보세요.
is an estimated execution plan without executing your
20:26:32
아무 일도 일어나지 않을 것입니다.
query but now if you go over here and switch it to
20:26:35
쿼리를 실행해야 합니다.
the actual execution plan nothing gonna happen because
20:26:39
쿼리를 실행한 후 결과를 얻었습니다.
first you have to execute a query so let's go and do that
20:26:42
여기에서 실행이라는 새로운 탭이 있습니다.
so once we have executed we got the result the
20:26:45
실행 계획을 찾을 수 있습니다.
messages and here we have a new tab called execution
20:26:48
쿼리를 처리하는 데 사용되는 실제 실행 계획입니다.
plan so if you go over here you will find the
20:26:51
세 번째를 시도해 보겠습니다.
real execution plan that is used to process your query
20:26:54
쿼리가 매우 빠르기 때문에 실행이 빨랐습니다.
and let's go and try the third one and let's go and
20:26:58
이것이 실시간 실행 계획입니다.
execute it was pretty fast because the query is very fast but here we can see how the data and that plan is working during the execution.
20:27:07
현재 실행 계획이 있습니다.
So this is the life execution plan. And of course, we have the last one, which is the current execution plan.
20:27:14
이러한 것들 간의 차이점입니다.
So those are the differences between those stuff. Now you might ask, why do we have this estimated and actual execution plans?
20:27:22
데이터베이스가 건강한지 이해하는 데 유용한 도구입니다.
Well, it is really nice tool to understand whether everything like
20:27:26
추정과 실제 계획이 다르면 통계나 인덱스에 문제가 있다는 신호입니다.
is healthy at your database, because if the guessing is something else as the actual execution plan, that means this is an indicator that something is wrong at the statistics or the index at your database.
20:27:38
추정과 실제가 일치하면 모든 것이 좋아 보입니다.
So if they are matching the estimated and the actual, then everything looks good.
20:27:43
하지만 이제 우리는 그 실행 계획 중 하나의 유형에만 집중할 것입니다. 실제 실행 계획에 집중하겠습니다.
But now we're going to focus only on one type of those execution plans. We're going to stick with the actual execution plan.
20:27:50
이제 우리는 두 개의 쿼리를 나란히 열어볼 것입니다. 하나는 클러스터 인덱스에서 가져올 것입니다.
So now what we can do, we're going to go and open two queries side by side. And one going to be from the clustered index.
20:27:56
그리고 다른 하나는 힙 구조에서 가져올 것입니다. 그래서 일대일로 진행될 것입니다. 두 쿼리를 모두 실행해 보겠습니다.
And another one is from the heap structure. So it's going to be like one to one. Let's go and query both of them.
20:28:03
이제 실행 계획을 읽어보려고 합니다. 하지만 실제 실행 계획을 활성화하고 있는지 확인하세요.
And now let's go and try to read the execution plan, but make sure that you are activating the actual execution plan.
20:28:09
여기 두 개의 계획이 있습니다. 이제 우리는 힙 테이블에 있으며 인덱스가 없습니다.
So we have here now two plans. So now we are at the heap table and we don't have any indexes.
20:28:16
이제 이 실행 계획을 어떻게 읽을 것인지가 문제입니다. 계획은 매우 간단합니다. 매우 간단한 쿼리가 있기 때문입니다. 하지만 오른쪽에서 왼쪽으로 읽습니다.
So now the question is how to read this execution plan? Well, now the plan is very simple because we have a very simple query, but we read it from the right to the left.
20:28:25
첫 번째 작업은 테이블 스캔입니다.
So the first operation is the table scan.
20:28:29
그리고 다음 작업으로 가는 아주 작은 화살표가 있습니다. 그래서 오른쪽에서 왼쪽으로 진행됩니다.
And then we have here a very small arrow to the next one where we have the select. So from right to left.
20:28:34
따라서 이제 첫 번째 연산자는 테이블 내에서 데이터를 읽는 방법입니다. 여기에는 다양한 유형의 스캔이 있습니다.
So now, of course, the first operator is how to read your data inside the table. And here we have different types of scans.
20:28:40
그 중 하나가 테이블 스캔입니다. 테이블 스캔은 실제로 전체 테이블을 스캔합니다.
And one of them is the table scan. So table scan actually is scanning the entire table.
20:28:46
그래서 이 쿼리를 실행하기 위해 테이블 내의 모든 행을 스캔하게 됩니다.
So it's going to go and scan all the rows inside your tables in order to execute this query.
20:28:51
이 테이블 스캔에 마우스를 올리면 데이터 로딩 또는 테이블 스캔 중에 발생하는 많은 세부 정보를 찾을 수 있습니다.
Now, if you go and mouse hover on the table scan, you will find a lot of details about what is happening during loading the data or scanning the table.
20:29:01
하지만 약간 귀찮습니다. 그보다 더 나은 방법은 오른쪽 클릭하여 속성으로 가면 오른쪽에서 동일한 세부 정보를 얻을 수 있지만 읽기 더 쉽습니다.
But it is a little bit annoying. Better than that, if you go right to click on it and then go to properties, you will get in the right side the same details, but it is easier to read.
20:29:11
우리가 읽어야 할 세 번째 사항은 읽은 행의 수입니다.
So the third thing that we have to read is the number of rows that has been read.
20:29:15
그래서 우리는 테이블 내의 모든 행을 읽었다는 것을 알 수 있습니다. 이는 그리 좋지 않습니다.
So we can see that we have read all the rows inside the table, which is not really good.
20:29:20
그리고 자원과 비용에 대한 또 다른 중요한 정보가 있습니다.
and we have another important information about the resources and the cost
20:29:23
그래서 CPU 비용과 입력 출력 비용이 있습니다.
so we have the cpu cost and the input output costs
20:29:26
흥미로운 점은 논리적 연산자입니다.
and what is interesting is the logical operator
20:29:30
테이블 스캔이며, 우리는 몇 가지 유용한 정보를 볼 수 있습니다.
the table scan and we can see some nice information about
20:29:33
저장소에 대한 정보가 있으며, 원시 저장소라고 합니다. 이제 진행해 보겠습니다.
the storage it says it is raw store now let's go
20:29:36
다른 테이블의 실행 계획을 확인해 보겠습니다.
and check the execution plan of this other table where
20:29:39
클러스터 인덱스가 있으므로 실행 계획으로 가겠습니다. 이제 오른쪽에 다른 것이 보입니다. 테이블 스캔이 아니라 클러스터 인덱스 스캔이라는 것이 있습니다.
we have a clustered index so let's go to the execution plan and now you can see that we have on the right side something else we don't have table scan we have something called clustered index scan.
20:29:50
전체 테이블을 다시 스캔하거나 인덱스의 일부 또는 범위만 스캔하고 있습니다.
It is either scanning the entire table again or only a range or a part of the index.
20:29:57
물론 세부 정보에서 모든 정보를 읽었는지 확인할 수 있습니다.
And of course, in the details, we can see whether it read all
20:30:00
모든 정보를 읽었는지 확인해 보겠습니다.
the informations or not now if you go and check the number
20:30:03
행의 전체 인덱스가 순서대로 읽힙니다
of rows again the whole index is read in order
20:30:07
그래서 여기 총 행 수가 있습니다
to get this results so again we have here the total number of rows
20:30:10
우리 테이블 내부에서 논리적
inside our table and as well you can see over here the logical
20:30:13
작업은 클러스터 인덱스 스캔입니다
operation it is clustered index scan so it is not table scan now of course we have to go and check the cpu and the input output costs whether we are consuming
20:30:22
그래서 같은 노력을 소비하는지
the same efforts or not so we can go and compare stuff
20:30:25
여기 0.07이 있습니다
so here we have like 0.07 and
20:30:28
여기서 우리는 큰 이득을 보지 못했습니다
if going over here you can see we didn't gain like
20:30:31
이 테이블에 인덱스가 있어도
a lot of information having an index on this table and that's
20:30:35
물론 논리적입니다
of course logical because this query is not using any
20:30:38
전체 테이블에서 모든 것을 선택하고 있습니다
indexes it is just like selecting everything from the whole
20:30:41
이제 데이터를 기본 키 판매 주문 번호로 정렬하겠습니다
table so now let's go and extend that we're gonna sort the data by the
20:30:48
이것을 가져오고
primary key sales order number
20:30:52
힙 구조를 위해
so let's go and get this one and as well
20:30:55
실행 계획을 확인하고
for the heap structure so let's go and
20:30:58
클러스터 테이블에 대한 동일한 작업
execute it and check the execution plan and the same
20:31:02
힙 구조를 먼저 확인해 보겠습니다
thing for our cluster table
20:31:05
여기 두 단계가 있습니다
now let's check first the heap structure as you
20:31:08
전체 테이블을 스캔하고
can see here we have like two steps first it's
20:31:11
출력에 표시하기 위해
gonna go and scan the whole table and then we have sort operator in order to go and sort all the data in
20:31:18
여기 두 개의 연산자가 있습니다
order to present it in the output and at the end we have the select
20:31:21
이제 클러스터 인덱스로 가면
which is not really important so here we have like two operators
20:31:25
여기 두 단계만 있습니다
but now if you go to our clustered index you
20:31:28
정렬 단계가 없습니다
can see that we have only like two steps there is no sort
20:31:31
클러스터 인덱스는
step right and that's because the clustered index
20:31:34
정렬만 되어 있고 SQL은 없다
is only sorted and sql don't have
20:31:37
데이터를 다시 판매할 필요가 없도록 정렬되어 있습니다.
to go and sell the data again so it doesn't have to go and
20:31:41
데이터는 이미 정렬되어 있으므로 인덱스가 있으면 첫 번째 이점이 있습니다.
sort anything the data is already sorted so this is the first win that you have if you have an index so everything
20:31:48
이 열에 정렬 기준이 있으면 SQL이 쿼리 중에 이를 수행할 필요가 없습니다.
is already sorted and if you have an order by on this column then SQL don't have to do it during the query.
20:31:54
이제 비용을 비교하고 싶다면 CPU와 입출력 비용이 동일하다는 것을 알 수 있습니다.
So now if you want to go and compare the cost you can see here we still have the same cost for the CPU and the input output.
20:32:00
인덱스가 없는 힙 구조에서는 두 배의 비용이 발생합니다.
In the heap structure without any index we have here like double cost. The first cost is for the table scan.
20:32:07
클러스터와 동일한 CPU와 입출력 비용이지만, 데이터 정렬에 대한 높은 비용이 추가됩니다.
It is the exact same amount of CPU and input output like the clustered but as well on top of it we have high cost for sorting the data.
20:32:16
따라서 더 많은 CPU와 입출력을 소비하고 있습니다.
So we are consuming more CPU and input outputs.
20:32:20
비용을 요약하면, 이 쿼리는 클러스터 인덱스에 비해 느리고 좋지 않을 것입니다.
And if you summarize those costs, of course, this query going to be slower and bad compared to the clustered index.
20:32:27
실행 계획에서 인덱스의 이점을 정확히 이해할 수 있습니다.
So with that in the execution plan, you can understand exactly the benefit of your index.
20:32:33
이 계획에 대해 한 가지 더, 여기로 가면.
And one more thing about this plan, if you go over here.
20:32:36
객체로 가면 쿼리에 사용된 인덱스의 이름을 볼 수 있습니다.
So if you go to the objects, and let me just extend it like this, you can see the name of the index that has been used for your query.
20:32:45
인덱스는 기본 키에 대한 p 키입니다.
So it says the index is p key for primary key. And then we have the whole thing.
20:32:50
왼쪽의 테이블로 가서 인덱스를 확인하면 이 인덱스와 정확히 일치할 것입니다.
So now if you go to our table on the left side, check the indexes, it's going to be exactly this index.
20:32:56
실행 계획에서 쿼리에 사용된 인덱스를 찾을 수 있습니다.
So in the execution plan, you can find as well, which index has been used in your query.
20:33:02
새 인덱스를 생성한 후 쿼리를 실행하고 데이터베이스가 새 인덱스를 사용하는지 확인하는 것이 중요합니다.
And this is very important to check. If you create a new index, then run your query and check whether the database is using your new created index.
20:33:11
그렇지 않다면 인덱스에 대한 잘못된 결정을 내리고 있는 것입니다.
and if not then you are making the wrong decisions about your index so each time you create a new index make sure to check whether in the execution plan the database is using your new index
20:33:25
이제 기본 키 대신 계속 진행하겠습니다.
okay so now let's keep going now instead of using the primary key
20:33:29
이 중 하나를 기준으로 데이터를 필터링하겠습니다.
i'm gonna go and filter the data based on one of those
20:33:32
예를 들어 운송 추적 번호를 확인해 보겠습니다.
columns that we have in this table so let me check the results and
20:33:35
운송 추적 번호와
let's take for example the carrier tracking number
20:33:38
여기서 첫 번째 값을 선택해 보겠습니다.
so carrier tracking number and
20:33:42
힙 테이블에 대해서도 같은 작업을 수행하겠습니다.
let's go and pick a value the first one here like this
20:33:45
그리고 실행해 보겠습니다.
and let's do the same thing for the heap table
20:33:48
실행 계획에서 여전히 테이블 스캔이 있습니다.
and execute it and now in the execution
20:33:51
이 테이블에서 클러스터 인덱스의 실행 계획을 확인해 보겠습니다.
plan you see we still have a table scan and
20:33:54
이 테이블에서 인덱스 클러스터와 함께 실행 계획을 살펴보겠습니다. 이제 비클러스터 인덱스를 생성하고 싶다고 가정해 보겠습니다.
on this table let's see the execution plan with the cluster of the index now let's say that i would like to go and create a non-clustered index
20:34:02
이 열에 대해 비클러스터 인덱스를 생성해 보겠습니다.
for this column so let's go and do it so create
20:34:05
비클러스터 인덱스를 생성할 것이며
non-clustered index and
20:34:09
인덱스 이름을 'index fact reseller'라고 하겠습니다.
i'm gonna call it index fact reseller and
20:34:12
그 다음 열 이름을 설정하겠습니다.
then the column name so on
20:34:15
우리 테이블 'facts reseller'에서
our table facts reseller and
20:34:19
열은 'carrier tracking number'가 될 것이며, 여기서 가져오겠습니다.
the column gonna be carrier tracking number so i'm gonna take
20:34:22
여기서 가져와서 생성해 보겠습니다.
it from here and let's go and create
20:34:25
이제 우리의 쿼리가 이 인덱스를 사용할지 확인해 보겠습니다. 실행해 보겠습니다.
it now let's see whether our query gonna use this index so let's go and execute it and let's go to the execution
20:34:32
계획이 이제 이전과 완전히 다르게 보입니다.
plan now things looks completely different than before
20:34:35
무슨 일이 일어나고 있는지 보겠습니다. 이제
so what is going on we can see that we have now
20:34:38
클러스터 인덱스가 없고
something new we don't have a clustered index we have
20:34:41
인덱스 탐색이라는 것이 있습니다. 인덱스 탐색은
something called index seek index seek is an
20:34:45
실행 계획에서 놀라운 신호입니다. 왜냐하면
amazing sign in your execution plan because
20:34:48
SQL 서버가 인덱스를 사용하여 필요한 정확한 데이터를 찾을 수 있는 방법을 찾았기 때문입니다. 그래서 이제 세 가지 유형의 스캔이 있습니다.
it tells us the sql server did find a way to use the index in order to find the exact data that we need without scanning a lot of stuff so that means now we have like three types of scans.
20:34:59
SQL이 전체 테이블을 스캔하는 테이블 스캔이 있습니다.
we have the table scan where the sql gonna go and
20:35:02
두 번째는 인덱스 스캔입니다.
scan the whole table and this can happen in the heap structure
20:35:06
여기서는 전체 인덱스를 스캔하는지 알 수 없습니다.
and the second one we have the index scan and
20:35:09
여기서는 전체 인덱스를 스캔하는지
here we don't know whether it is scanning the whole index
20:35:12
인덱스의 일부를 스캔하는지 알 수 없습니다. 마지막으로 데이터베이스가 많은 것을 스캔하지 않고 직접 데이터를 찾을 수 있는 인덱스 시크가 있습니다. 최악의 유형은 테이블 스캔입니다.
or a part of the index and the last one we have the index seek where the database is able to find directly the data without scanning a lot of stuff so the worst type is the table scan
20:35:25
그 다음으로 인덱스 스캔이 있고 가장 좋은 것은
then we have the index scan and the best one is
20:35:28
인덱스 시크입니다. 여기에서 세부 정보를 확인하면
the index seek so if you check here the details you
20:35:31
읽힌 행의 수가
can see the number of rows that has been read is
20:35:34
단 12개입니다. 놀랍습니다. 가서 힙을 확인해 봅시다.
only 12 this is amazing let's go and check the hip
20:35:38
여기에서 스캔하여 실행 계획을 확인합니다.
scan over here so to the execution plan
20:35:41
여기서 실행 계획을 살펴보면
and if you go over here you can see that we are reading around 60 000 rows in order to get 12 but with the index we are reading only 12 in order to get 12
20:35:53
이것은 놀랍고 매우 빠릅니다. 물론 비용도 매우 작습니다.
And this is amazing and very fast, of course. And of course, the cost of this is very, very small.
20:35:59
CPU와 입출력을 확인하면 그 숫자는 아무것도 아닙니다.
So if you check the CPU and the input output, you can see those numbers are nothing.
20:36:04
여기서 객체로 가면 어떤 인덱스가 사용되었는지 볼 수 있습니다.
And of course, if you go to the object over here, you can see which index has been used. And this is exactly the index that we have just created.
20:36:12
이 인덱스를 생성한 것은 정말 좋은 결정이었습니다.
So that means it was a really good decision to create this index.
20:36:16
SQL은 이에 대해 매우 기뻐하며 데이터를 빠르게 찾기 위해 사용했습니다.
And the SQL was very happy about it and used it in order to fast find our data. So now let's go and check the rest of the plan.
20:36:23
여기서 키 조회가 있습니다. 키 조회는 나머지 열을 가져오기 위해 필요한 작업입니다.
And now you can see over here we have key lookup. The key lookup is an operation that we need in order to get the rest of the columns.
20:36:31
이 인덱스에서는 하나의 열, 즉 운송 추적 번호만 가져옵니다.
Because from this index, we are getting the data of only one column, the carrier tracking number.
20:36:37
쿼리에서 select star를 사용하므로 많은 열이 있습니다.
But since in our query, we are saying select star, that means we have a lot of columns. And those columns are not part of the index.
20:36:44
이 인덱스에서는 나머지에 대해 아무것도 알지 못합니다.
So in this index, SQL don't know anything about the rest.
20:36:48
그래서 이스키엘은 나머지 열을 찾으러 가야 합니다.
that's why isquiel has to go and search for the
20:36:51
다른 열을 찾으러 가야 하며, 이는 조회라고 불립니다.
other columns and of course it is called a lookup not
20:36:54
스캔 같은 것이 아니며, 그래서 여기서도
a scan or something like that and that's why we have here
20:36:57
여기서도 12개 행만 있지만 이 단계에서
as well only 12 rows but from this step
20:37:01
나머지 열을 가져올 것입니다.
we will get the rest of the columns so and
20:37:04
이제 다음 단계는 이스키엘이 그것들을 조인하는 것입니다.
now the next step is that isquiel gonna go and join those
20:37:07
첫 번째에서 가져온 두 가지 정보입니다.
two informations so we have from the first one
20:37:10
운송 추적 번호와 나머지 정보를 합쳐야 합니다.
the carrier tracking number and the second one we have the rest of course isquiel has to go and merge all those stuff in one in order to
20:37:17
결과적으로 이 작업은
habit as a result and now this operation called a
20:37:20
내부 조인과 같은 다양한 유형의 중첩 루프입니다.
nested loops behind the scenes there are different types
20:37:24
우리가 아는 조인과는 다릅니다.
of joins not the one that we know the inner left and so
20:37:27
중첩 루프, 병합 조인 및 해시 조인이 있습니다.
on but there is another types of joins we have the
20:37:30
중첩 루프는 작은 데이터에 매우 좋습니다.
nested loop we have the merge join and the hash
20:37:33
대형 테이블이 있다면 병합 및 해시 조인이 더 좋습니다.
join the nested loop is very good for small stuff if you have large tables then the merge and the hash joins are way better than the nested loop.
20:37:43
많은 데이터를 가져오고 중첩 루프를 사용하고 있다면 좋지 않습니다.
So that means if you are getting here a lot of data from the index and the lookups and you see a skill is using a nested loop, this is not good.
20:37:52
하지만 지금은 괜찮습니다. 12개의 행만 가져오고 있고 작업이 충분히 빠를 것입니다.
But for now, it is okay because we are getting only 12 rows and the operation is going to be fast enough.
20:37:57
이제 실행 계획에서 볼 수 있는 또 다른 것은 비용의 비율입니다.
And now one more thing that we can see inside our execution plan is the cost in percentage.
20:38:02
이 계획을 확인하면 선택 비용이 거의 없다는 것을 알 수 있습니다.
So from checking this plan, you can see the select is almost costing nothing.
20:38:06
중첩 루프의 비용은 0%와 같습니다. 그리고 인덱스 탐색은 약 6%입니다.
The cost of the nested loop is as well like 0%. And then we have like a 6% of the index seek.
20:38:14
그것은 꽤 빠르기 때문입니다. 쿼리에서 가장 비싼 작업은 키 조회입니다.
That's because it is pretty fast. And the most expensive operation that done in our query is the key lookups.
20:38:21
물론 모든 열을 가져오기 때문입니다.
Of course, because it's going to go and get all the columns.
20:38:25
이제 힙 구조와 비교해보면, 힙 구조의 실행 계획이 매우 작아 보이더라도 인덱스보다 빠르다는 의미는 아닙니다.
And now if you go and compare it to the heap structure, even though the execution plan of the heap structure looks very small, doesn't mean that is faster than the indexes that we have.
20:38:35
여전히 모든 숫자를 합산하면 힙 구조보다 훨씬 빠릅니다.
Still, if you go and add up all those numbers, it is way, way faster than the heap structure.
20:38:42
이제 하나 더 보여드리겠습니다. 이 키 조회를 없애고 쿼리에서 운송 추적 번호만 선택하고 싶다면.
Now, I would like to show you one more thing. If you want to get rid of this key lookup and in your query, you have only selecting the carrier tracking number.
20:38:51
실행해보고 실행 계획으로 가보겠습니다. 보시다시피, 조회가 필요 없습니다. 열이 하나뿐입니다.
Let's go and execute it and go to the execution plan. As you can see, there is no need for the lookup because we have only one column.
20:38:58
이 데이터는 인덱스에서 완전히 가져올 수 있습니다.
And this data, we can get it completely from our index.
20:39:02
따라서 SQL이 테이블과 인덱스에서 어떻게 작동하는지 이해하는 것이 흥미롭습니다. 이것이 인덱스에 대한 올바른 결정을 내리고 있는지 검증하는 방법입니다.
so as you can see it is interesting to understand how sql is working with your table and with your index and this is how to validate whether you are making correct decisions about your indexes
20:39:17
이제 집계 조인을 수행하는 더 많은 내용을 추가해 보겠습니다. 쿼리를 확장하겠습니다. 다른 차원과 조인할 것입니다.
okay so now let's go and add more stuff where we are doing aggregation joins and so on let's extend our query so i'm gonna go and join it with another dimension like for example
20:39:28
제품 키에서 조인이 이루어질 것입니다.
the dim products and the join
20:39:31
제품 키와 같아야 합니다.
going to be on the product key so products key
20:39:34
그 후 몇 가지를 집계할 것입니다.
and equal to as well product key now
20:39:38
제품 이름으로 집계할 것입니다.
after that we're going to go and aggregate few stuff so we're going to aggregate
20:39:41
영어 제품 이름이 될 수 있으며, 이를 제품 이름이라고 부르겠습니다.
by the product name so i'm going to take the product
20:39:44
판매를 집계할 것입니다. 사실 테이블에서 가져올 것입니다. 판매 금액입니다.
name so it can be the english product name and let's go and call it product name and let's go and aggregate the sales so some
20:39:55
총 판매로 가져올 것입니다.
and we're gonna get it from the fact table. It's gonna be sales amount.
20:40:00
총 판매량으로서
as total sales
20:40:03
물론 우리는 그룹화를 해야 합니다
and of course we have to go and do group by
20:40:06
프랑스어 이름이 아니라 영어 이름이 될 것입니다
and not french name it's gonna be the english name
20:40:09
그러니 올라갑시다
so let's go up
20:40:12
제품 이름으로 그리고 그게 전부입니다
by the product name and that's it let's go and
20:40:15
지금 실행해 보겠습니다. 우리는 멋진 제품 목록과 총
execute it now we have a nice list of products and total
20:40:18
판매량이 있지만 실행 계획을 확인해 보겠습니다. 오 마이 갓, 우리는 많은 것이 있습니다. 오른쪽에서 시작하겠습니다. 빨리 진행합시다.
sales but let's go and check the execution plan and oh my god we have a lot of stuff so let's start from the right side so let's do it quickly
20:40:27
오른쪽에서 왼쪽으로, 첫 번째는 데이터를 가져오는 것입니다.
from the right to the left so the first thing is that it's gonna go and get
20:40:30
사실에서 데이터를 가져오고 있습니다. 클러스터 인덱스를 사용하고 있습니다.
the data from the fact so it is using the
20:40:33
클러스터 인덱스를 사용한 후, 해시 매치를 수행할 것입니다.
clustered index and then after that it's gonna go and
20:40:37
집계를 위한 해시 매치를 수행한 후, 데이터를 정렬할 것입니다.
do a hash match for the aggregation and
20:40:40
데이터를 정렬한 후, 병합 조인을 수행할 것입니다. 모든 단계가 준비되고 있습니다.
after that it's gonna go and sort the data because it is doing later
20:40:43
사실 테이블을 준비하고 있으며, 또 다른 클러스터가 있습니다.
emerge join so all those steps are preparing
20:40:47
차원 스캔을 수행할 것이며, 차원에서 정보를 선택할 것입니다.
the fact table and then we have another cluster
20:40:50
행이 많지 않아서 매우 작은 테이블입니다. 600행입니다.
scan for the dimension so it's gonna go and as well select the informations from the dimension and we have here like
20:40:56
행이 많지 않아서 매우 작은 테이블입니다. 600행입니다.
not a lot of rows so it is very small table 600 rows
20:40:59
이제 클러스터 스캔의 결과가 있습니다.
and now of course the result of the cluster scan
20:41:02
결과가 정렬되어 있으며, 우리가 배운 대로
is as well sorted right and of course as we learned the
20:41:05
클러스터 인덱스가 데이터를 정렬할 수 있습니다.
cluster the index can go and sort the data so we have here
20:41:09
정렬된 출력과 또 다른 정렬된 출력이 있습니다.
a sorted output together with another sorted
20:41:12
정렬된 두 데이터 세트가 있으며,
output so we have like two data sets that are sorted and
20:41:15
SQL은 여기서 단순 조인을 선택했습니다.
sql here decided to go with the mere join which
20:41:18
정렬된 두 데이터 세트를 조인하기에 좋은 방법입니다.
is a good join in order to join two sorted data sets
20:41:21
중첩 루프를 사용하여 조인하는 것보다 훨씬 빠릅니다.
it is way faster than joining using the nested
20:41:25
모든 것이 잘 진행되고 있으며, 정렬될 것입니다.
loop so everything is fine and then that is going to be sorted
20:41:28
출력으로 표시되고 있으며, 이 계획을 확인하면
and presented as output and now if you are checking this plan
20:41:31
가장 비싼 일이 발생한 것을 볼 수 있습니다.
you can see the most expensive thing happened
20:41:34
사실 테이블에서 71의
at the fact table so 71 of
20:41:37
총 비용이 이 단계에서 발생했습니다. 이제 쿼리가 느리다고 가정해 보겠습니다.
the total cost happened in this step now let's say
20:41:40
쿼리가 느리며 최적화하고 싶습니다.
that the query is slow and i would like to go and optimize it
20:41:43
우리는 큰 테이블에서 집계를 수행할 경우 열 저장소가 좋은 아이디어라는 것을 배웠습니다.
we have learned that if you are doing aggregations on big tables then the column store
20:41:50
그것이 사실인지 확인하기 위해 다른 테이블로 가겠습니다.
index is a good idea so let's go and find whether
20:41:53
우리의 판매 테이블은 힙 구조로 되어 있었습니다.
that is true so i'm gonna go to our other
20:41:56
이제 이 힙 구조를 열 저장소로 변환하자고 하셨습니다.
table so our sales table was with the heap
20:42:00
클러스터형 열 저장소 인덱스를 생성하겠습니다.
structure and now you say you know what let's go and convert this heap structure to a column store so let's go and do that so we're gonna say create clustered
20:42:10
우리는 어떤 열도 지정할 필요가 없습니다.
column store index and we're gonna call it index and then the whole name factory seller sales hp
20:42:19
우리의 테이블이 될 것이고, 그게 전부입니다.
and we don't have to specify any columns so it's
20:42:22
이제 실행해 보겠습니다.
going to be our table on and that's it let's
20:42:26
이제 우리의 테이블은 더 이상 힙 구조가 아닙니다.
go and execute it so now our table is not
20:42:29
이제 열 저장소여야 합니다.
anymore heap structure it should be a column
20:42:32
정보를 확인하면 클러스터형 열 저장소 인덱스가 있습니다.
store so if you go and check the informations we
20:42:35
이제 같은 쿼리를 실행하고 성능을 확인해 보겠습니다.
can see we have like clustered column stored index on
20:42:38
더 나은 성능이 있는지 확인해 보겠습니다.
it so now let's go and do the same query and check whether we
20:42:41
이제 확인해 보겠습니다.
have a better performance let's go and execute it and of course you have to go and activate the execution plan so i'm gonna
20:42:48
다시 오른쪽으로 가보겠습니다.
and now let's go and check from the
20:42:51
이미 6%만 비용이 든다는 것을 알 수 있습니다.
right again so this is our fact table and
20:42:54
흥미롭습니다. 우리의 사실 테이블에서 무슨 일이 있었는지 비교해 보겠습니다.
as you can see already it is costing only six percent
20:42:58
먼저 물리적 작업이 무엇인지 알 수 있습니다.
interesting so let's go and compare what happened to our fact table
20:43:01
열 저장소 인덱스 스캔입니다.
first of all you can see that the physical operation is
20:43:04
여기서 SQL이 사용되었다는 것을 알 수 있습니다.
a column store index scan and if you go to the objects
20:43:07
여기서 SQL이 열 저장소를 사용했다는 것을 알 수 있습니다.
over here you can see that the sql did use the
20:43:10
물론 전체 데이터가 인덱스에만 저장되기 때문에 그렇게 될 것입니다.
column store and that is of course going to happen because the whole data is stored only in the index so there is no way around it so
20:43:17
인덱스를 사용할 수 있지만 이제 흥미로운 점은
it can go and of course and use the index but now what is interesting
20:43:20
CPU 비용을 비교해야 할 것 같습니다.
maybe we have to go and compare the cpu costs so
20:43:24
여기서 확인하면 0.0067과 같습니다.
if we check over here it is like 0 comma 0067
20:43:27
입출력에 대해 거의 같은 것
almost the same thing for the input output let's
20:43:31
이전 계획으로 가면 열 저장소가 없습니다
go to the previous plan where we don't have a column store
20:43:34
사실을 확인해 보겠습니다. 여기서 볼 수 있듯이 사실 테이블을 읽는 것이 열 저장소보다 훨씬 비쌉니다
and check our facts so as you can see here it is way more expensive reading the fact table than the column store and
20:43:42
입출력 비용을 줄였습니다
well we have reduced the input output costs so as
20:43:45
전체의 71%에서
you can see we went from 71 percent of total
20:43:48
사실 테이블의 비용이 단 6%로 줄었습니다
cost for the fact table to only six
20:43:51
쿼리를 실행하는 데 사용되는 리소스는
percent and the resource that is used to execute the
20:43:54
쿼리는 그것이 훨씬 적습니다.
query it is way less than a
20:43:58
정상 클러스터 드로우 저장소이며 이것이 정확히 그 힘입니다.
normal cluster draw store and this is exactly the power
20:44:01
이 인덱스의 열 저장소 인덱스를 사용할 수 있습니다.
of this index the column store index you can use
20:44:04
사실 테이블과 같은 큰 테이블에서 사용할 수 있습니다.
it in big tables like the fact tables like
20:44:07
이 쿼리에서 우리가 하고 있는 것처럼 놀라운 성능을 얻을 수 있습니다.
we are doing here in this query you will be getting amazing
20:44:10
이 시나리오에 대해 물론 이동하고 비교할 수 있습니다.
performance for this scenario so of course you can go and
20:44:13
실행 계획을 왼쪽과 오른쪽으로 이동하여 비교할 수 있습니다.
compare the execution plan by moving left and
20:44:16
여기 클릭하고 다른 탭으로 전환하면 숫자를 빠르게 비교할 수 있습니다.
right so as you can see if i click over here and i just
20:44:20
하지만 실행 계획을 비교하는 또 다른 방법이 있습니다.
switch to the other tab i can like quickly compare the
20:44:23
그것은 실행 계획으로 가서 오른쪽 클릭한 다음 실행 계획으로 저장을 선택하는 것입니다.
numbers but there is another way on how to compare execution plans
20:44:26
그런 다음 이름을 지정해야 합니다. 예를 들어 쿼리 프로 저장소로 저장합시다.
and that is if you go to the execution plan i right
20:44:29
그런 다음 두 번째 쿼리로 가서 원시 저장소에서 실행 계획을 오른쪽 클릭하고 비교를 선택합니다.
click on it then go to save execution plan as and then you have to go and give it a name for example query pro store so let's Let's go and save it.
20:44:39
그것을 클릭하면 비교할 항목을 선택해야 합니다.
And then you can go to the second query where we have the raw store and then right click on the execution plan and say compare show plan.
20:44:48
열고 나면 상단에 쿼리가 있고 하단에 저장한 실행 계획이 있습니다.
So once you click on that, then you have to go and select the one that you want to compare with.
20:44:53
여기에서 두 실행 계획을 비교하는 많은 정보가 있습니다.
So open and now on top, you have your query and at the bottom, you have the execution plan that you have saved.
20:45:00
그렇게 하면 어떤 계획이 더 나은지 이해하기 위해 더 자세히 들어갈 수 있습니다. 알겠죠, 친구들.
And then you have here a lot of informations where they compare both of the execution plan.
20:45:07
실행 계획을 갖는 것은 놀랍습니다. SQL이 뒤에서 어떻게 작동하는지 볼 수 있습니다.
And with that, you can go in more details in order to understand which plan is better. All right, friends.
20:45:11
SQL이 뒷면에서 어떻게 작동하는지 볼 수 있습니다
So as you can see, having the execution plan is amazing. We can see how the SQL is working behind the scenes.
20:45:17
그리고 SQL이 내 쿼리를 단계별로 처리하는 방식을 이해할 수 있으며, 얼마나 많은 자원을 소모하는지, 내 인덱스가 유용한지 또는 쓸모없는지를 알 수 있습니다.
And we can understand how SQL is processing my query step by step, how much resources it is consuming, whether my indexes are useful or useless.
20:45:27
그리고 우리는 여러 실행 계획을 비교할 수 있습니다. 올바른 테이블과 올바른 열에 대한 올바른 인덱스를 찾을 때까지 비교할 수 있습니다.
And I can go and experiment stuff. I can go and add like an index, then test and check whether I gained like few performance or not.
20:45:35
실행 계획은 우리의 인덱싱 전략이 올바른지 이해하는 데 도움을 주기 때문에 놀랍습니다.
And we can go and compare like multiple execution plans before and after until you get the right index for the right table and the right column.
20:45:44
자, 친구들, 지금까지 우리는 SQL 서버가 쿼리를 실행하는 방법에 대해 스스로 결정을 내린다는 것을 배웠습니다.
So the execution plan are amazing in order to help us understanding whether our indexing strategy is correct or not.
20:45:56
그리고 SQL은 통계를 기반으로 이러한 계획을 세웁니다.
Alright friends, so far we have learned that the SQL server is going to make its own decisions on how to execute your queries.
20:46:03
하지만 때때로 데이터베이스에서 얻는 계획이 쿼리에 최적이 아닐 수 있습니다.
And the SQL makes those plans based on the statistics.
20:46:07
그리고 이러한 일이 발생할 수 있는 이유는 여러 가지가 있을 수 있습니다.
But sometimes the plan that you are getting from the database might be not the best one for your query.
20:46:13
아마도 통계가 최신이 아니거나 인덱스가 너무 많아 데이터베이스 엔진이 혼란스러워할 수 있습니다.
And there could be many reasons why this could happen.
20:46:16
그리고 여기서 우리는 SQL 힌트가 필요합니다.
Maybe the statistics are not up to date or you have a lot of indexes and the database engine get confused.
20:46:23
따라서 SQL 힌트를 사용하여 SQL 데이터베이스가 쿼리를 어떻게 실행해야 하는지 강제할 수 있습니다.
And here exactly where we need the SQL hints.
20:46:27
그래서 우리는 개입하여 실행 계획의 단계를 변경할 수 있습니다. 자, 어떻게 할 수 있는지 봅시다.
So you can use the SQL hints in order to command to force the SQL database on how exactly your SQL query should be executed.
20:46:36
자, 이제 아주 간단한 쿼리를 해보겠습니다. 우리는 주문 테이블과 고객 테이블을 조인하고 몇 개의 열을 보여주고 있습니다.
So you can intervene and change the steps in the execution plan. So let's see how we can do that. All right.
20:46:43
이제 실행하고 실행 계획을 확인하면, 이 계획에서 클러스터형 인덱스를 사용하여 주문과 고객의 데이터를 읽고 있음을 알 수 있습니다.
So now let's have a very simple query. We are just joining the table orders with the customers and we are showing like few columns.
20:46:50
그리고 그 다음에 조인을 수행하기 위해 중첩 루프를 사용하고 있습니다.
Now, if you go and execute it and we go and check the execution plan, we can see in this plan that it is using the clustered index in order to read the data from the orders and the customers.
20:47:00
이제 우리의 테이블이 정말 크다고 가정해 보겠습니다. 그럼에도 불구하고 SQL은 중첩 루프를 사용하고 있습니다.
And then it is using the nested loop in order to do the joins.
20:47:04
물론, 이는 큰 테이블에 좋지 않습니다. 아마도 SQL이 인덱스와 통계로 혼란스러워했을 것입니다.
Now let's say that our tables are really big, but still the SQL is using the nested loops.
20:47:09
그리고 초기 루프를 사용하기로 결정했습니다. 자, 이제
And of course, this is not good for large tables. And maybe the SQL was confused with the indexes and statistics and so on.
20:47:16
그리고 초기 루프를 사용하기로 결정했습니다. 그래서 이제
And it decided to use the initial loops. So now in
20:47:19
SQL이 다른 유형의 조인을 사용하도록 강제하기 위해, 쿼리에서 SQL이 조인에 대해 다른 유형을 사용하도록 힌트를 줄 수 있습니다.
order to force the SQL to use another type of join, we can go and give a hint in our query for the SQL to use different types for the join.
20:47:29
그럼 이제 그렇게 해봅시다. 쿼리의 끝에 가서 옵션을 추가하고 그 안에 해시 조인을 사용하라고 이렇게 말할 것입니다.
So let's go and do that. We're going to go at the end of our query and we're going to say option and inside it we're going to say use the hash join like this.
20:47:40
그래서 그게 전부입니다. 이것이 우리의 쿼리이며, 마지막에 데이터베이스에 실행 계획에 대한 힌트를 주고 있습니다.
So that's it. This is our query and at the end we are giving the database a hint for the execution plan.
20:47:46
그럼 이제 그것을 시도해 봅시다. 실행 계획을 확인해 봅시다.
So let's go and try that out. So let's check the execution plan.
20:47:50
이제 보시다시피, SQL이 다른 유형의 조인을 사용하고 있습니다.
And now as you can see, SQL is using different type of join.
20:47:54
그래서 이를 통해 우리는 실행 계획에 개입하고 선택을 하고 있습니다.
So with that, we are intervening in the execution plan and we are making choices.
20:47:59
그래서 이를 통해 SQL이 두 테이블을 조인하는 방식의 기술적인 부분을 변경했습니다. 알겠습니다.
So with that, we have changed the technicality on how the SQL is joining those two tables. All right.
20:48:05
이제 다른 것을 변경해 보겠습니다. 예를 들어 인덱스 스캔 대신 인덱스 시크를 사용하고 싶습니다.
So now let's go and change something else. Like for example, instead of having index scan, I would like to have an index seek.
20:48:13
테이블에 올바른 인덱스가 있다면 SQL에 데이터 읽는 방법을 알려줄 수 있습니다.
So if you have the right index in your table, you can go and tell SQL how to read your data in the table.
20:48:20
그럼 이제 그렇게 해보겠습니다. 현재 고객 테이블에서 인덱스 스캔이 있습니다.
So let's go and do that. Currently, here we have an index scan on the table customers.
20:48:26
테이블 근처로 가서 'with'라고 말한 다음, SQL 강제 시크를 사용하겠다고 말할 것입니다.
So we can go over here near the table and we're going to say with and inside it, we're going to say for SQL force seek.
20:48:34
우리는 SQL이 시크 인덱스를 사용하도록 강제하고 있습니다.
So we are forcing SQL to use the seek index.
20:48:37
테이블 근처에서 이러한 키워드를 사용하여 SQL에 데이터를 로드하는 방법을 지정할 수 있습니다.
So we can use those keywords near the table in order to specify for SQL how to load the data.
20:48:44
주문과 같이 아무것도 지정하지 않으면 힌트가 없습니다.
If you are not specifying anything like here with the orders, we don't have any hints.
20:48:48
즉, SQL에서 재생성된 실행 계획에 의존하고 있다는 뜻입니다.
That means we are counting on the execution plan that is regenerated from the SQL.
20:48:53
추천을 원하지 않으면 어떤 것을 사용할지 지정할 수 있습니다.
But if you don't want the recommendations, you can go and specify which one should be used.
20:48:59
이제 실행해 보겠습니다. SQL이 우리가 요청하는 내용을 처리할 수 없기 때문에 오류가 발생했습니다.
Now let's go and execute it. Now we got an error because the SQL is not able to process what we are asking for.
20:49:07
아마도 우리는 강제 시크와 해시 조인을 사용하고 있는 것 같습니다. 이 주석을 해제하고 다시 시도해 보겠습니다.
And I think maybe we are using the force can and as well the hash join. Let me just uncomment this and let's go and give it another try.
20:49:15
이제 작동하고 있습니다. 실행 계획으로 가보겠습니다. 다시 중첩 루프가 보입니다.
And now it is working. So let's go to the execution plan. So you can see we got again the nested loop.
20:49:20
고객 테이블로 가면 이제 인덱스 시크를 사용하고 있는 것을 볼 수 있습니다.
And now if you go to the customers table, you can see now it is using the index seek.
20:49:25
더 이상 인덱스 스캔을 사용하지 않습니다.
So it is not using anymore the index scan.
20:49:28
다시 말하지만 SQL을 강제하고 있습니다.
so as you can see again we are intervening and forcing sql to
20:49:32
우리 쿼리에 더 나은 방법을 사용할 수 있습니다.
use the method that might be better for our query
20:49:35
하나의 테이블에 많은 인덱스를 생성하는 경우입니다.
now if you are creating a lot of indexes in one table
20:49:38
SQL이 여전히 올바른 인덱스를 타겟팅하지 않고 있습니다.
and the sql is still not targeting the right
20:49:41
이렇게 할 수 있습니다. 여기로 가서 'for seek'를 제거하고 'use index'라고 말합니다.
index so if we check the object you can see it is targeting specific index but if you have a better index than that you can give a hint for the sql to use a specific index
20:49:53
그런 다음 인덱스 이름을 지정해야 합니다. 그러니 다시 기본 키를 가져옵니다.
And we can do that like this. If you go over here and remove the for seek and you say use index.
20:49:59
이제 SQL에 이 인덱스를 사용하여 고객 테이블을 스캔하라고 말하고 있습니다.
And then we have to go and specify the index name. So let's go and get again the primary key over here.
20:50:06
이제 이 인덱스를 사용하여 고객 테이블을 스캔하라고 SQL에 말하고 있습니다.
Now I'm telling SQL you have to go and use this index in order to scan the table customers.
20:50:11
이제 이것을 시도해 보겠습니다. 실행 계획으로 가면 이 인덱스를 타겟팅하고 있는 것을 볼 수 있습니다.
So let's go and try this out. And if you go to the execution plan, you can see it is as well targeting this index.
20:50:19
특정 유형의 로딩이나 조인에 대해 SQL을 강제할 수 있을 뿐만 아니라, 생성한 특정 인덱스를 사용하도록 SQL을 강제할 수 있습니다.
So not only can force SQL for specific type of loading or joining, you can force SQL to use a specific index that you created.
20:50:28
좋습니다, 친구들. SQL 힌트는 매우 강력하지만, 프로젝트에서 사용하면서 나쁜 경험을 했기 때문에 매우 조심해야 합니다.
All right, friends. So as you can see, SQL hints are very powerful, but we have to be very careful with them because I really had a bad experience using them in my projects.
20:50:38
그래서 여기 제 추천 사항과 발생하는 일입니다. 개발 데이터베이스에서 성능을 최적화하고 힌트를 사용하기 시작했을 때 속도가 정말 좋았습니다.
So here are my recommendations and what happens. So what could happen is that you are optimizing the performance in the development database and you start using the hints and the speed was really good.
20:50:49
프로덕션 데이터베이스로 배포하면 이 힌트가 제대로 작동하지 않을 것입니다.
And once you roll that out to another database, the production database, this hint will not be working correctly.
20:50:57
사용하는 동일한 힌트가 성능을 개선하지 않을 수 있습니다.
The same hint that you are using might not improve the performance.
20:51:01
그 이유 중 하나는 프로덕션 데이터베이스가 개발 데이터베이스에 비해 큰 데이터를 가질 수 있기 때문입니다.
And one reason is that sometimes the productive database has like large data compared to the development database.
20:51:09
각 데이터베이스에서 힌트를 테스트해야 합니다.
So you have really to test the hint in each database that you have.
20:51:13
하나의 환경에서 힌트가 작동한다고 해서 다른 환경에서도 작동하는 것은 아닙니다. 항상 테스트해야 합니다.
So if your hint is working in one environment, that doesn't mean it's going to work in the other one. So always make sure to test.
20:51:20
프로젝트에서 작업하고 있고 쿼리가 매우 느리다면 힌트를 영구적인 수정으로 사용하지 마십시오.
And the second recommendation is that don't use the hint as a permanent fix for your queries.
20:51:25
이것은 실행 계획이 왜 그렇게 나쁜지 명확하지 않다면 힌트를 사용하여 쿼리를 다시 빠르게 할 수 있다는 것을 의미합니다.
So what this means, let's say that you are working in the project and one of your queries are very slow.
20:51:30
여전히 원인을 분석하는 데 시간을 투자하고 소비해야 합니다.
Now, if it's not clear why the execution plan is really bad, you can go and use the hints as a workaround in order to speed up your query again but it still has a workaround temporary.
20:51:42
아마도 오래된 통계이거나 잘못된 인덱싱이 있을 수 있습니다.
You still have to invest and spend time in order to analyze what was the root cause.
20:51:48
힌트는 쿼리를 빠르게 하기 위한 임시 방편으로만 사용하고 영구적인 수정으로 사용하지 마십시오.
So maybe it is an old statistics or you have wrong indexing and so on.
20:51:52
SQL 힌트는 실행 계획을 제어하는 데 정말 놀랍지만, 매우 조심스럽게 사용해야 하며 긴급 상황에서만 사용해야 합니다.
So use hints only to work around and speed up your queries but don't use it as a permanent fix.
20:51:58
자, 친구들, 이제 각 SQL 데이터 프로젝트에 대해,
So friends SQL hints are really amazing in order to control the execution plan but use it very carefully and only if there is like an emergency.
20:52:11
명확한 지침을 만들어야 합니다.
Alright friends, so now for each SQL data project,
20:52:15
우리는 명확한 지침을 만들어야 합니다.
we have to make sure that we create a clear guidance
20:52:18
인덱스 전략에 대해 팀의 모든 구성원이 헌신하고 전략을 따르도록 해야 각 인덱스가 프로젝트에서 목적을 달성할 수 있습니다.
about the index strategy and everyone in the team has to commit and follow the strategy in order to make sure that each index that is created in the project to fulfill a purpose.
20:52:29
명확한 전략이 없으면,
And that's because without a clear strategy about the
20:52:32
인덱싱에 대해 약속할 수 있습니다. 많은 중복, 사용되지 않는 인덱스, 저장소 낭비가 발생하고, 프로젝트의 전체 시스템이 느리고 나빠질 것입니다.
indexing, I'm gonna promise you there will be a lot of redundancy, unused indexes, waste of storage, and the whole system of your project is going to be slow and bad.
20:52:42
이제 우리가 할 일은, 제가 보통 제 프로젝트에서 따르는 인덱싱 전략을 보여주는 것입니다.
So now what we're going to do, I'm going to show you my indexing strategy that I usually follow in my projects.
20:52:47
하지만 지금부터 말씀드리자면, 모든 프로젝트와 모든 시나리오에 맞는 단일 전략은 없습니다.
But I'm going to tell you from now, there is like not one strategy that can fit any project and any scenario.
20:52:53
그래서 각 프로젝트 팀은 자신의 전략을 만들기 위해 브레인스토밍을 해야 합니다.
That's why the team of each project should brainstorm in order to make their own strategy.
20:52:59
이제 제 인덱싱 전략을 살펴보겠습니다. 그리고
So now let's have a look to my indexing strategy. And
20:53:05
이 인덱싱 튜토리얼에서 제가 여러분에게 드릴 수 있는 단 하나의 추천을 뽑아야 한다면, 이 조언을 드리겠습니다.
now if I have to pick only one recommendation from me to you in this indexing tutorial, I'm gonna have this advice for you.
20:53:13
과도한 인덱싱을 피하세요. 과도한 인덱싱은
Avoid over indexing. Over indexing
20:53:16
많은 개발자들이 저지르는 가장 큰 실수이자 함정입니다. 그들은 더 많은 인덱스를 추가하면 속도가 빨라지고 쿼리가 빨라질 것이라고 생각합니다.
is the biggest mistake and trap that a lot of developers do where they think adding more indexes, that sounds like we are speeding up things and our queries can be fast.
20:53:27
하지만 이것이 정반대의 결과를 초래한다는 것을 말씀드려야 합니다. 그 이유는 다음과 같습니다.
But I have to tell you this exactly lead to the opposite. And here's why.
20:53:32
우리가 배운 바와 같이, 테이블에 새로운 데이터를 추가할 때마다 인덱스는 업데이트되고 정렬되며 재배치되어야 합니다.
As we learned, each time you add a new data to your table, your index has to get updated, sorted, rearranged.
20:53:39
즉, 인덱스가 너무 많으면 어떤 일이 발생할까요? 삽입, 업데이트, 삭제 작업이 느려질 수 있습니다.
That means having too many indexes, what can happen? Your insert, update, delete operations can be slow.
20:53:46
그리고 이것은 데이터베이스가 더 느려진다는 것을 의미합니다.
And this means your database is slower and not faster.
20:53:49
과도한 인덱싱이 나쁜 또 다른 중요한 이유는 실행 계획을 생성할 때 데이터베이스가 혼란스러워진다는 것입니다.
And one more very important reason why over-indexing is bad is you make the database confused while creating the execution plan.
20:53:58
우리가 배운 대로 SQL 데이터베이스는 쿼리에 대한 최상의 실행 계획을 생성해야 합니다.
As we learned the SQL database has to create the best execution plan for your query.
20:54:04
그리고 데이터베이스에 인덱스가 많으면 실행 계획을 생성하는 과정이 복잡해져서 데이터베이스가 최상의 경로와 인덱스를 선택하기 어려워집니다.
And if you have a lot of indexes in your database, it's going to make the process of creating an execution plan complicated for the database, which makes it of course for database harder to choose the best path and index.
20:54:17
또한 나쁜 실행 계획의 가능성을 열어줍니다.
And as well, you open the door for bad execution plans.
20:54:21
이것은 쿼리를 느리게 만든다는 것을 의미합니다. 왜냐하면 데이터베이스가
And this means it's going to slow the query because first the database has
20:54:24
쿼리를 실행하기 전에 실행 계획을 생성해야 하므로
to create the execution plan before executing your query so
20:54:27
다시 말해 성능에 나쁜 영향을 미치게 됩니다.
again it has a bad effect for the performance and
20:54:30
또한 데이터베이스가 최상의 실행 계획을 결정하기 어렵게 만듭니다.
as well there is another bad thing it can make it harder for
20:54:33
쿼리에 대한 최상의 실행 계획을 결정하는 것이며, 인덱스가 너무 많으면
the database to decide what is the best execution
20:54:36
SQL 데이터베이스가 정말 나쁜 선택을 하게 만들 수 있습니다.
plan for a query and having too many indexes might
20:54:40
쿼리에 대한 실행 계획을 세우는 것이며, 인덱스가 너무 많으면
make the sql database choosing a really bad
20:54:43
SQL 데이터베이스가 정말 나쁜 실행 계획을 선택하게 만듭니다. 과도한 인덱싱은 실행 계획을 혼란스럽게 하고 쿼리를 느리게 만듭니다. 그래서 저는 이것을 황금 규칙이라고 부르며, 반드시 지켜야 합니다.
execution plan so over indexing confuse the execution plan and as well makes the query slower so that's why i call this a golden rule and you you have to commit to it.
20:54:53
과도한 인덱싱을 피하세요. 그것은 두 개의 날카로운 칼날과 같습니다.
Just avoid over indexing because it is double H swords.
20:54:57
정확히 여기서 적은 것이 더 많다는 사고방식을 가져야 합니다.
And here exactly you have to have the mindset of less
20:55:01
효과적인 인덱스 몇 개를 갖는 것이 인덱스가 많은 것보다 훨씬 낫습니다.
is more so having a few effective indexes
20:55:04
많은 인덱스를 가지는 것보다 훨씬 낫습니다.
is way better than having a lot of indexes so
20:55:07
이 점을 염두에 두고 팀의 개발 지침에 큰 문구로 작성하세요. 과도한 인덱싱을 피하세요. 이것이 인덱싱 전략의 첫 번째 문구입니다. 이제 나머지를 확인해 봅시다.
keep it in mind and write it in your development guideline for the team with big statement avoid over indexing so this is the first statement in your indexing strategy so now let's check the rest
20:55:23
좋습니다. 이제 인덱싱 전략을 네 단계로 나눌 수 있습니다.
all right so now we can split the indexing strategy into four phases
20:55:26
각 단계에는 여러 단계가 있습니다. 이제
and each phase has multiple steps so now the
20:55:29
첫 번째 단계는 초기 인덱스를 생성하는 것입니다.
first step is we're gonna go and create an initial indexing
20:55:32
이제 새로운 SQL 프로젝트를 시작하면 프로젝트의 목표를 매우 명확하게 정의해야 합니다. 즉, 우리가 집중하고자 하는 것과 달성하고자 하는 것을 명확히 해야 합니다.
strategy so now once you start a new SQL project you have to define the objectives of the projects very clearly so that means we have to make it clear what we are focusing on what we want to achieve
20:55:43
인덱싱 전략의 목표를 정의하기 위해서는 시스템을 이해해야 합니다.
And in order to define the goal of your indexing strategy, you have to understand your system.
20:55:49
주로 두 가지 유형의 데이터베이스가 있습니다. 한편으로는 OLAP 데이터베이스가 있습니다.
We have mainly two types of databases. In one hand, we have OLAP databases.
20:55:55
OLAP는 온라인 분석 처리(Online Analytical Processing)를 의미합니다. 이 데이터베이스의 목적은 데이터 분석을 위한 것입니다.
It stands for Online Analytical Processing. The purpose of this database is for data analytics.
20:56:00
그 예로 데이터 웨어하우스가 있습니다. 데이터 웨어하우징에서는 여러 출처에서 데이터를 추출합니다.
And an example for that is the data warehouse. So in data warehousing, we go and extract the data from multiple sources.
20:56:07
그런 다음 데이터를 준비하고 변환하여 하나의 큰 저장소에 넣습니다.
And then we prepare it and transform it and put it in one big storage.
20:56:12
이 과정을 ETL 프로세스라고 부르며, 그 후
and we call this process an ETL process and then the front
20:56:15
우리는 보고서와 대시보드를 통해
end we have like reports and dashboards where the
20:56:18
최종 사용자에게 데이터를 요약하고 집계하여 제공합니다.
data is summarized and aggregated and presented for the
20:56:21
이 보고서는 사용자가 데이터를 분석하고 통찰력을 얻는 데 사용될 수 있습니다.
end user and these reports could be used from users in
20:56:24
이 보고서를 생성하기 위해서는
order to analyze and have insights about the data and now
20:56:27
보고서를 생성하기 위해서는
in order to generate those reports there will be
20:56:30
데이터 웨어하우스 데이터베이스에서 많은 읽기가 필요하므로, 이는 데이터베이스에 접근하여 데이터를 집계하고 시각화를 위해 준비하는 거대한 쿼리가 발생할 것임을 의미합니다.
like heavy reading on the data warehouse database so that means there will be huge queries that's gonna access the database in order to aggregate and prepare the data for the visualization.
20:56:42
하지만 이제 다른 한편으로, 우리는 OLTP 시스템, 온라인 트랜잭셔널 프로세싱이 있습니다.
But now in the other hand, we have the OLTP systems, online transactional processing.
20:56:46
이것은 전자상거래, 금융, 은행과 같으며, 백엔드에는 데이터가 저장되는 데이터베이스가 있습니다.
It is like an e-commerce, finance, banking, where you have at the backend, a database where the data is stored.
20:56:53
그리고 프론트 엔드에는 최종 사용자를 위한 애플리케이션이 있습니다.
And on the front end, we have like an applications for the end users.
20:56:57
따라서 사용자가 앱과 상호작용함에 따라, 이는 데이터베이스에 대한 쓰기 작업을 유발할 수 있습니다.
So now as the users are interacting with the app, this can cause a write operations on the database.
20:57:02
즉, 새로운 데이터를 삽입하거나 데이터를 변경하는 것입니다. 또한 앱에서 데이터를 표시하기 위해 데이터베이스에 대한 읽기 작업도 발생합니다.
So inserting new data or changing data. And as well there will be read operations on the database in order to show the data in the app.
20:57:10
따라서 우리는 쓰기와 읽기 모두를 가지고 있습니다. 이제 물론 우리는 목표가 무엇인지, 우리가 무엇을 달성하고 싶은지 스스로에게 물어봐야 합니다.
So we have both write and read. So now of course we have to ask ourselves what is the goal? What do we want to achieve?
20:57:17
여기에는 주로 두 가지 전략이 있습니다. 읽기 성능을 개선하고 싶거나 쓰기 성능을 개선하고 싶습니다.
And here mainly there is like two strategy. Either you want to improve the read performance or the write performance.
20:57:23
이제 전체 시스템을 살펴보면, 프로젝트를 이해해야 합니다. 어디에서 어려움이 있는지.
Now if you are looking to the all up system here is really you have to understand the project. Where is the struggle?
20:57:29
때때로 ETL 프로세스 자체가 느릴 수 있습니다.
Sometimes it could be like the ETL process itself is slow.
20:57:33
주로 ETL은 데이터 웨어하우스의 소스에서 데이터를 쓰는 것입니다. 아마도 매일 10시간이 걸리는 시나리오가 있을 수 있습니다.
And mainly the ETL is writing data from the sources in the data warehouse. And maybe you have a scenario where it takes like every day 10 hours.
20:57:41
그리고 10시간은 물론 문제입니다. 매일 새로운 데이터, 신선한 데이터를 보고서에 받기 위해 그렇게 오랫동안 기다릴 수는 없습니다.
And 10 hours is of course a problem because you cannot wait so long in order to get a new data, fresh data to the report every day.
20:57:48
따라서 프로젝트의 목표는 쓰기 성능을 최적화하는 것입니다. ETL을 가속화하고 싶습니다.
So you can make the goal of the project is to optimize the right performance. You want to speed up the ETL.
20:57:54
하지만 실제로 이러한 프로젝트의 대부분은 또 다른 문제를 가지고 있습니다. 바로 데이터베이스에 대한 읽기 작업입니다.
But actually most of those projects having another issue. Well, it is the read operation on the database.
20:58:01
데이터 웨어하우스는 일반적으로 매우 큰 데이터 세트를 가지고 있으며, 프론트 엔드에서 보고서는 데이터베이스에 대해 복잡한 쿼리를 생성합니다.
Because data warehouses normally have really big data sets and at the front end the reports generate large complex queries on the database.
20:58:10
즉, 읽기 프로세스가 각 OLAP 시스템의 문제점이 될 수 있습니다.
So that means the read process can be the pain point in each OLAP system.
20:58:16
따라서 일반적으로 각 OLAP 시스템의 큰 목표는 읽기 성능을 최적화하는 것입니다.
So normally the big goal in each OLAP system is going to be how to optimize the read performance.
20:58:22
하지만 이제 OLTP와 함께 오른쪽에는 데이터베이스와 시나리오의 다른 성격이 있습니다.
But now in the right hand with the OLTP we have different nature of database and scenario.
20:58:27
무슨 일이 일어날 수 있냐면 큰 쿼리가 없을 것입니다.
what can happen you will not have like big queries from the
20:58:30
앱에서는 미니 쿼리와 많은 트랜잭션이 발생할 수 있습니다.
apps you can have like mini query many transactions
20:58:34
응용 프로그램과 데이터베이스 간에 발생하고 있습니다.
happening between the application and the database
20:58:37
그래서 대량의 읽기 및
so you're gonna have like massive amount of read and
20:58:40
쓰기 트랜잭션이 발생할 것입니다. 그래서 우리는 계속해서
write transactions so the whole time we
20:58:43
읽고 쓰고 읽고 쓰고 있습니다. 하지만 모든 앱과 함께
are reading writing reading writing and so on but with the all app
20:58:46
우리는 더 크고 느린 것을 가지고 있습니다. 왜냐하면
we have like something bigger and slower because
20:58:49
ATL에서는 일반적으로 한 번만 실행되므로 데이터베이스에 새 데이터를 한 번만 씁니다.
in the atl we usually run it only once that means we are writing only once a new data to the database and this happens
20:58:56
이것은 보통 밤에 발생하지만 트랜잭션 시스템에서는
usually at the night but on the transactional systems you
20:58:59
항상 많은 읽기와 쓰기가 발생합니다. 다시 프로젝트에 따라
have a lot of read writes all time again depend on
20:59:02
항상 많은 읽기와 쓰기가 발생합니다. 일반적으로 OLTP의 주요 문제는
the project but usually the main pain point in
20:59:06
쓰기 작업입니다. 그래서
the OLTP is the write operation so it
20:59:09
OLTP 시스템을 구축하는 경우 주요 목표는
could be like this if you are building an OLTP system the main
20:59:12
올바른 성능을 최적화하는 것입니다. 이제
goal is to optimize the right performance now
20:59:15
물론 질문은 어떻게 해야 하는지, 어떻게 최적화할 것인지입니다. 다시 말해, 데이터베이스의 성격을 이해해야 합니다.
of course the question is how to do that how we're going to optimize that well again we have to understand the nature of the database what do we have in the OLAP systems is usually like
20:59:25
OLAP 시스템에서는 매우 큰 사실이 있는 데이터 모델을 가지고 있습니다.
a data model where you have very big fact
20:59:28
사실 주위에는 여러 차원이 연결되어 있습니다.
tables and around the fact we have like multiple dimensions that
20:59:31
이 사실 테이블은 데이터베이스에서 정말 큰 테이블이며 매번
are connected to the facts so those fact tables are really
20:59:35
보고서를 작성하기 위해 사용됩니다. 그리고
big tables in the database and each time
20:59:38
보고서는 항상 이러한 사실을 사용하여
they are used in order to build a report and the
20:59:41
시각화를 위한 데이터를 준비하고 많은 집계 쿼리를 사실에 대해 수행할 수 있습니다.
report is going to be using all time those facts in order to
20:59:44
시각화를 위한 데이터를 준비하고 많은 집계 쿼리를 사실에 대해 수행할 수 있습니다. 이제 어떤 유형의 인덱스를 사용해야 할지 질문에 답해야 합니다.
prepare the data for the visualizations and a lot of aggregations query can be done on the facts and now of course you have to answer now the question which type of index should we use in this scenario?
20:59:54
완벽한 인덱스가 있습니다. 그것은 열 저장소 인덱스입니다.
Well, we have a perfect one called a column store index.
21:00:00
여기서의 실천은 전체 프로젝트에 대한 전략으로 모든 사실 테이블을 열 저장소 인덱스로 만드는 것입니다. 이것이 우리가 모든 앱에서 하고 있는 일입니다.
Practice here is and you can make it as a strategy for the whole project that we make all fact tables as a column store index because this is what we are doing in the all app.
21:00:10
우리는 대규모 데이터 세트를 집계하고 있습니다. 하지만 이제 데이터 모델과 시나리오는 오른쪽에서 완전히 다릅니다.
We are aggregating large data sets. But now the data model and the scenario is completely different at the right side.
21:00:17
여기에는 많은 테이블이 있으며 크기가 다릅니다.
Here we can have like a lot of tables and they have like different sizes and so on.
21:00:21
모든 테이블 간에 많은 관계가 있습니다. 그래서 완전히 연결되어 있습니다.
And there are like a lot of relationship between all those tables. So it is completely connected.
21:00:27
따라서 많은 기본 키와 외래 키 관계가 있습니다.
So you have a lot of like primary keys and foreign keys relationships between them.
21:00:32
그리고 일반적으로 이러한 테이블은 완전히 정규화된 테이블입니다. 그래서 작은 조각들입니다.
And normally those tables are completely normalized table. So they are like small pieces.
21:00:37
하지만 왼쪽에는 사실로서 비정규화된 테이블이 있습니다.
But on the left side, we have denormalized tables as a fact.
21:00:41
여기서 AOTB의 인덱싱에 대한 하나의 전략이 있습니다.
So here is like one strategy that we can follow in the indexing of the AOTB.
21:00:45
각 테이블의 기본 키에 대해 클러스터 인덱스를 생성하는 것입니다.
It's that we create clustered index for each primary key of our tables.
21:00:50
물론 이것은 검색, 정렬 및 테이블 결합과 같은 많은 것들을 개선할 수 있습니다.
This, of course, can improve a lot of stuff like searching, sorting, and as well joining tables together.
21:00:56
하지만 OLTP의 올바른 성능 최적화에 집중하고 있으므로 OLAP에 비해 새로운 인덱스를 추가할 때 더 민감해야 합니다.
But of course, since we are focusing on optimizing the right performance on the OLTP, you have to be more sensitive by adding new indexes compared to the OLAP.
21:01:05
추가하는 각 인덱스가 데이터가 매우 느리게 기록되는 이유가 될 수 있습니다.
Because each index you add, it could be a reason why the data is written very slowly.
21:01:11
따라서 OLTP에서는 인덱스를 추가할 때 훨씬 더 조심해야 합니다.
So in the OLTP, you have to be way more careful adding indexes.
21:01:16
이제 프로젝트의 본질을 이해해야 합니다. 주요 문제가 무엇인지 이해해야 합니다.
So now, as you can see, you have to understand the nature of your projects. You have to understand what is the main issue.
21:01:22
프로젝트를 이해하면 시스템 최적화를 위한 목표를 정의할 수 있습니다.
Once you understand your project, you can go and define like a goal for optimizing the system.
21:01:28
읽기 또는 쓰기 또는 둘 다일 수 있습니다. 그렇게 하면 시스템 인덱싱의 초기 전략을 수립하게 됩니다.
So either read or write or maybe both of them. And with that, you are making like the initial strategy of indexing your system.
21:01:40
좋습니다. 그렇게 해서 우리는 인덱싱에 대한 초기 전략과 대략적인 계획을 갖게 되었습니다.
All right. So with that, we have an initial strategy for our indexing and we have a rough plan.
21:01:46
이제 다음 단계에서는 사용 패턴 인덱싱이 있습니다. 이제 프로젝트를 깊이 파고들 것입니다.
Now in the next phase, we have usage patterns indexing. So now we're going to do a deep dive into our project.
21:01:52
우리가 해야 할 첫 번째 일은 자주 사용되는 테이블과 열을 식별하는 것입니다.
And the first thing that we have to do is that we have to identify the frequently used tables and columns.
21:01:58
즉, 프로젝트에서 사용된 쿼리를 확인하여 어떤 테이블이 많은 쿼리에서 가장 중요한지 이해해야 합니다.
So that means you have to go and check the queries used in your projects in order to understand, okay, what is the most important table that is used in many queries?
21:02:07
예를 들어, 여기에는 사실 인터넷 판매가 있습니다. 이는 우리의 스크립트에서 많은 쿼리에서 사용됩니다.
Like for example, here we have the fact internet sales. It is used like in many, many queries in our scripts.
21:02:14
여기서 가장 중요한 자주 사용되는 테이블에 대한 감각을 개발하고 있습니다.
So here you are like developing a feeling about what are the most important frequently used tables.
21:02:20
뿐만 아니라 이러한 쿼리에서 데이터를 필터링하는 방법을 확인할 수 있습니다.
And not only that, you can go and check how we are filtering the data on those queries.
21:02:24
예를 들어, 여기서 우리는 주문 날짜 키로 필터링하고 있습니다. 이러한 종류의 필터링은 여러 쿼리에서 사용됩니다.
So for example, we have over here, we are filtering by the order date key. Is this kind of filtering is used like in multiple queries.
21:02:32
그래서 보시다시피, 우리는 항상 같은 작업을 수행하는 몇 가지 쿼리가 있습니다. 날짜로 데이터를 필터링하고 있습니다.
So as you can see, we have like a couple of queries where we are doing always the same, where we are filtering the data by the dates.
21:02:39
이를 통해 우리는 이 열이 주로 필터링과 집계에 사용되는 패턴이 있음을 이해합니다.
So with that, we understand there is like a pattern inside our projects where this column is used mainly on filtering and as well for aggregating.
21:02:47
즉, 스크립트 내에서 가장 덜 사용되는 테이블과 열이 무엇인지 이해하기 위해 깊이 분석해야 합니다.
So that means you do a deep dive in order to understand what are the most infrequently used tables and columns inside your scripts.
21:02:54
그리고 이제, 제가 보통 하는 일은 AI와 HIGPT의 도움을 받아 제 코드를 제공하고 질문하는 것입니다.
And now, of course, what I usually do, I go and use the help of the AI and HIGPT where I give it my code and then ask questions about it.
21:03:01
예를 들어, 이 프롬프트는 다음 SQL 쿼리를 분석하고 테이블 및 열 사용 통계에 대한 보고서를 생성하라고 합니다.
For example, this prompt, it says analyze the following SQL queries and generate a report on table and column usage statistics.
21:03:08
각 테이블에 대해 모든 쿼리에서 테이블이 사용된 총 횟수를 제공합니다.
And for each table, provide the total number of times the table is used across all queries.
21:03:14
각 열에 대한 세부 사항을 제공하여 각 열이 나타나는 횟수를 보여줍니다.
A breakdown for each column in the table showing the number of times each column appears.
21:03:19
그리고 각 열의 주요 사용 용도, 필터링, 조인, 그룹화 등을 보고 싶습니다.
And I would like to see as well the primary usage of each column, filtering, joining, grouping, and so on.
21:03:24
출력에서 보시다시피, 제 스크립트에 대한 멋진 통계를 얻었습니다.
And in the output, as you can see, we got like nice statistics about my scripts.
21:03:28
보시다시피, 가장 많이 사용된 사실 테이블은 인터넷 판매 사실입니다. 프로젝트에서 13번 사용되었습니다.
So as you can see, the most used fact table is fact Internet sales. It is like 13 times used in the projects.
21:03:35
그리고 그러면 이 사실들 안에 있는 각 열에 대한 통계를 볼 수 있습니다. 대부분의 경우 판매는 집계에 사용됩니다.
And then we can see like statistics about each column that is inside these facts. So most of the time is the sales is used for aggregating.
21:03:43
그리고 우리가 보았듯이, 주문 날짜 키는 필터링에 5번 사용됩니다.
And as we saw, the order date key is used like five times for filtering.
21:03:48
그리고 다른 키는 테이블을 조인하는 데 사용됩니다. 보시다시피, 놀랍죠?
And the other keys is used for joining tables. So as you can see, it's amazing, right?
21:03:53
이제 우리는 어떤 테이블이 중요한지, 어떤 열이 중요한지 식별할 수 있습니다.
Now we can identify which tables are important, which columns as well are important.
21:03:58
그리고 우리는 이러한 정보를 바탕으로 데이터베이스의 인덱스를 유도할 수 있습니다.
And we can like based on those informations, maybe derive our indexing for our database.
21:04:04
이제 우리는 자주 사용되는 테이블과 열을 식별했습니다.
So with that, we have identified our frequently used tables and columns.
21:04:08
그리고 이제 그 다음 단계로, 적절한 인덱스 유형을 선택해야 합니다.
And now the next step of that, we have to go and choose the right index type.
21:04:12
그리고 우리가 이전에 배운 것처럼, 여러 종류의 인덱스가 있습니다. 이는 사용 용도와 시나리오에 따라 다릅니다.
And as we learned before, we have multiple types of indexes. And that's really depend on the usage and the scenario.
21:04:18
예를 들어, 열이 기본 키인 경우 인덱스의 클래스를 선택하세요.
So for example, if your columns are primary keys, then go with a class of the index.
21:04:23
그리고 기본 키가 아닌 열을 사용하는 경우 조인 필터링을 수행할 때 비클러스터형을 고려하세요.
and if you are using columns that are not primary key where you are
21:04:26
조인 필터링을 수행할 때 비클러스터형 인덱스를 고려하세요.
doing joining filtering then think about the non-clustered
21:04:29
그리고 테이블이 매우 크면 열 저장 인덱스를 사용할 수 있습니다.
index and of course if the table is very big as we said you can
21:04:32
데이터의 하위 집합, 즉 1년 정보만 타겟팅하는 경우
go and use the column store index and if you are targeting always
21:04:35
필터링된 인덱스를 고려할 수 있습니다.
like a subset of data only like one year informations
21:04:38
필터링된 인덱스와 마지막에 대해 생각할 수 있습니다.
then you can think about the filtered index and the last
21:04:42
고유한 열이 있고 중복이 없다면 고유 인덱스를 적용할 수 있습니다.
one if you have like a unique column where you don't have any duplicates then you can go and apply a unique index so it depends
21:04:48
시나리오와 사용에 따라 올바른 인덱스를 선택해야 합니다.
of the scenario and the usages you have to choose the right index
21:04:51
이 단계의 마지막 단계는 인덱스를 테스트해야 한다는 것입니다.
and of course the last step in this phase is that you have to
21:04:54
모든 것이 잘 작동하는지 인덱스를 테스트해야 합니다.
go and test your index whether everything is working fine so that's all for the phase two.
21:05:03
이제 세 번째 단계인 시나리오 기반 인덱싱으로 넘어갑니다.
Then we go to phase three, scenario-based indexing.
21:05:07
여기서 특정 문제와 고통 지점에 집중해야 합니다.
So here we have to tackle and focus on specific issues to specific pain points.
21:05:13
먼저 느린 쿼리를 식별해야 합니다.
So that means we have first to identify the slow queries.
21:05:17
사용자에게 보고되거나 팀이 로그를 분석하고 있습니다.
So it could be reported from users or the team is doing like analyzing on the logs and
21:05:22
어떤 쿼리가 성능 문제를 일으키는지 이해해야 합니다.
understand which queries are causing like
21:05:25
느린 쿼리 목록을 얻으면 하나씩 분석해야 합니다.
performance issues and now once you get a list of slow
21:05:28
느린 쿼리 목록을 얻으면 하나씩 분석해야 합니다.
queries then you have to analyze them one by one
21:05:31
실행 계획을 파고들어야 할 시간입니다.
and it is time to dig into the execution
21:05:34
SQL이 우리의 쿼리를 어떻게 구현하는지 확인할 수 있습니다.
plans so as we learn we can check how SQL is implementing
21:05:38
SQL이 테이블을 전체 스캔하는 영역을 찾아야 합니다.
our queries and start looking for areas for example
21:05:41
비용이 많이 드는 작업을 사용하는지 확인해야 합니다.
where the SQL is doing a full scan of the tables
21:05:44
중첩 루프 조인과 같은 작업을 이해해야 합니다.
or maybe using expensive operations like
21:05:47
정확한 문제 지점을 이해했다면 다음 단계는
nested loop joins and so on so once you understood
21:05:50
올바른 인덱스를 선택해야 합니다.
where is exactly the pain point the next step is
21:05:53
어떤 종류의 인덱스를 사용할지 결정해야 합니다.
that you have to go and choose the right index so which
21:05:56
쿼리를 최적화하기 위해 사용할 인덱스 유형입니다.
type of indexes we're going to use in order to optimize the
21:05:59
인덱스를 생성한 후에는 테스트해야 합니다.
query and once you go and create the index the
21:06:02
실행 계획을 다시 실행해야 합니다.
last step is that you have to go and test it so you're going
21:06:05
쿼리가 방금 생성한 인덱스를 사용하고 있는지 확인해야 합니다.
to run again the execution plan in order to make sure that
21:06:09
실행 계획을 비교해야 합니다.
your query is using the index that you have just created
21:06:12
즉, 실행 계획을 비교해야 한다는 뜻입니다.
so that means you have to go and compare the execution plans before and after and if you see that there is no benefit then something
21:06:20
문제가 있다는 뜻입니다.
is wrong that means you have to go and investigate more and
21:06:23
더 조사해야 한다는 뜻입니다.
analyze the execution query and maybe choose a better
21:06:26
각 느린 쿼리에 대해 이 과정을 진행해야 합니다.
index way and you have to do this process for each
21:06:29
모든 쿼리를 빠르게 가져올 때까지.
slow query until you get all your queries fast
21:06:33
물론 인덱싱이 유일한 방법이 아니라는 것을 잊지 마세요.
but of course don't forget indexing is not the only method on
21:06:36
쿼리 속도를 최적화하는 방법에 대해.
how to optimize the speed of queries so
21:06:39
이 세 가지 단계에서 우리는 일반적인 방법에서 구체적이고 시나리오 기반의 방법으로 나아갔습니다.
as you can see through these three phases we went from
21:06:42
자, 이제 마지막 단계로 넘어가겠습니다. 인덱스의 모니터링과 유지 관리입니다.
a very generic methods on how to index our system to something very specific and scenario based so as So as you can see, as we're moving in the phases, we are doing more deep dive into our projects.
21:06:59
우리가 배운 바와 같이, 작업은 인덱스를 생성하고 구현하는 것으로 끝나지 않습니다.
All right, so now moving to the last phase, we have the monitoring and maintenance of our indexes.
21:07:04
우리는 인덱스의 건강을 지켜야 할 책임이 있습니다.
As we learned, the job doesn't stop by just creating and implementing indexes.
21:07:09
여기서 데이터베이스는 이 단계에서 사용할 수 있는 많은 통계와 메타데이터를 제공합니다.
We have to be responsible by keeping eye on the health of our indexes.
21:07:13
첫 번째 단계는 인덱스 사용을 모니터링하는 것입니다.
And here the databases offers a lot of statistics and metadata about your data that you could use in this phase.
21:07:21
우리는 시스템 스키마에서 찾을 수 있는 동적 관리 뷰나 함수를 사용할 수 있습니다.
So the first step is to monitor the usage of the indexes.
21:07:25
각 인덱스의 사용 횟수와 마지막으로 쿼리가 인덱스를 사용한 시간을 확인할 수 있습니다.
And as we learned, we can use the dynamic management views or functions that we can find in the system schema.
21:07:32
우리가 만든 인덱스 중 사용되지 않은 인덱스를 찾아낼 수 있습니다.
Where we can see the number of usage of each index and when the last time our queries did use the indexes.
21:07:39
다음 단계는 누락된 인덱스를 모니터링하는 것입니다.
So with that, we can go and find out all those indexes that we have created and never been used in our projects.
21:07:46
여기서 데이터베이스가 실행 계획에서 누락된 인덱스를 보고하는 추천 사항을 확인할 수 있습니다.
And now the next step is that we can go and monitor the missing indexes.
21:07:49
다시 말해, 더 많은 세부 정보를 보기 위해 동적 관리 뷰나 함수를 사용할 수 있습니다.
So here we can go and check what are the recommendations from the database where the database is reporting missing indexes from the execution plan.
21:07:58
또한 인덱스에 중복이 있는지 모니터링할 수 있습니다.
And again, we can go and use those dynamic management views or functions in order to see more details.
21:08:03
팀에 많은 개발자가 있을 경우 자주 발생합니다.
And as well, we can go and monitor whether we have duplicates in the indexing.
21:08:09
그들이 병렬로 최적화 작업을 하고 있을 수 있습니다.
it happens a lot if you have like a lot of developers in your team so
21:08:12
느린 쿼리의 성능을 최적화하기 위해 여러 개의 인덱스를 생성할 수 있습니다.
it could be that they are working parallely to optimize the
21:08:15
동일한 열에 대해 여러 개의 인덱스를 생성하는 것입니다.
performance of slow queries and then go and create multiple
21:08:19
인덱스에서 중복이 있는지 확인할 수 있습니다.
indexes for the same column so this is something that
21:08:22
우리는 인덱스에 중복이 있는지 확인할 수 있습니다.
we can go and check whether we have duplicates in our indexes and
21:08:25
중복이 있다면 어떻게 처리할 수 있는지 찾아야 합니다.
if you have duplicates then you have to go and find how you can go
21:08:28
그것들을 통합한 다음, 다음 단계는 통계를 업데이트하는 것입니다.
and consolidate them then the next step we have to go and
21:08:31
통계는 실행 계획에 매우 중요합니다.
update the statistics so as we learn statistics are
21:08:34
데이터베이스 엔진은 이러한 정보를 사용하여
very important for the execution plan because the
21:08:38
쿼리에 대한 최적의 실행 계획을 결정합니다.
database engine use those informations to decide
21:08:41
통계가 오래되면 데이터베이스가 잘못된
the best execution plan for your query and if
21:08:44
쿼리를 실행하는 방법에 대해 잘못된 결정을 내릴 수 있습니다.
the statistics are old then the database can make wrong
21:08:47
이로 인해 성능이 저하될 수 있습니다.
decisions about how to execute your query which might
21:08:50
통계를 모니터링하기 위해 특별한 기능이 있습니다.
lead to bad performance so here again we have like special
21:08:53
매주 작업을 설정하여
functions in order to monitor the statistics but here
21:08:56
데이터베이스의 모든 통계를 생성하는 것이 좋습니다.
my recommendation is that each week ends have a job that's
21:08:59
마지막 단계는 단편화를 모니터링하는 것을 잊지 않는 것입니다.
go and create all the statistics of your database and
21:09:02
테이블을 수정하는 동안 시간이 지나면서 배운 것입니다.
the last step we don't have to forget about monitoring the fragmentations as
21:09:06
데이터베이스의 순서가 잘못될 수 있습니다.
we learned over the time as you are doing modifications on the tables
21:09:09
또는 데이터베이스에 사용되지 않는 여유 공간이 있을 수 있습니다.
what could happen the order of the databases could get wrong
21:09:13
그래서 단편화가 발생합니다.
or there are like free spaces on the database that are
21:09:16
인덱스에서도 마찬가지로 단편화를 모니터링해야 합니다.
not used so we have like fragmentations in the
21:09:19
각 테이블의 단편화를 모니터링해야 합니다.
index and the same thing we have to monitor the fragmentations
21:09:23
0과 10 사이의 비율이면 문제가 없습니다.
of each tables and here if the percentage is between 0
21:09:26
단편화가 10에서 30 사이이면 재구성해야 합니다.
and 10 then there is no issue but if the fragmentation is
21:09:29
인덱스를 재구성해야 하며, 30을 초과하면
between 10 and 30 then we have to go and reorganize
21:09:32
전체 인덱스를 재구성해야 한다는 경고입니다.
the index and if it's more than 30 then this
21:09:35
모니터링을 위해 자동화된 대시보드를 구축합니다.
is alerting you have to go and rebuild the whole index
21:09:38
Power BI 또는 Tableau에서 대시보드를 구축합니다.
and usually for the monitoring i go and build like
21:09:42
자동화된 대시보드를 파워 BI 또는 태블로에서 만들고
automated dashboards in power bi or tableau where i
21:09:45
모든 메타데이터를 추출하여 데이터베이스의 상태를 모니터링하기 위한 멋진 대시보드를 생성합니다. 또는 이러한 작업을 수행하기 위해 고급 도구를 구매할 수 있습니다.
go and extract all those metadata and create a nice dashboards in order to monitor the health of the database or you can go and buy some other tools that are advanced in order to do those stuff
21:10:00
좋습니다. 이것이 제가 프로젝트에서 일반적으로 따르는 인덱싱 전략입니다.
All right, so this is my indexing strategy that I usually follow in my project.
21:10:04
각 단계가 이전 단계에 기반하여 구축되는 것을 볼 수 있습니다.
And as you can see, each phase builds upon the previous one,
21:10:07
일반 전략에서 보다 목표 지향적이고 정제된 구체적인 전략으로 이동하며, 프로젝트의 인덱싱 전략의 목표를 먼저 정의합니다.
moving from a general strategy to more targeted, refined, specific strategy, where we define first the goal of the indexing strategy of the project.
21:10:17
단계가 진행됨에 따라 더 구체적인 시나리오를 목표로 삼게 됩니다.
And as we move with the phases, we're going to be targeting more specific scenarios.
21:10:22
이 사이클은 반복되며 한 번만 일어나는 것이 아닙니다. 목표가 여전히 프로젝트에 적합한지 계속 논의해야 합니다.
And this cycle keep repeating it's not only one time. So you have to keep discussing is the goal still suitable for the project.
21:10:29
자주 사용되는 테이블과 열을 계속 분석해야 합니다. 그리고 느린 쿼리를 계속 검색하고 찾아야 합니다.
You have to keep analyzing the frequently used tables and columns. And keep searching and finding those slow queries.
21:10:36
인덱스를 모니터링하면서 항상 주의를 기울여야 합니다.
And always keep an eye by monitoring the indexes.
21:10:40
물론 과도한 인덱싱을 피하라는 말을 계속 반복할 수 있습니다. 자, 친구들, 인덱스에 대한 모든 것입니다.
And of course I can only keep repeating this avoid over indexing. Alright my friends so that's all about the indexes.
21:10:47
많은 정보와 기술이었습니다. 이제 SQL에서 인덱싱에 대해 모든 것을 알게 되었습니다.
That was a lot of information and a lot of technique. So now you know everything about indexing in SQL.
21:10:53
다음에는 성능을 최적화하는 방법에 대한 또 다른 중요한 기술이 있습니다. 그래서 파티션에 대해 이야기할 것입니다.
Now in the next one, there is another important techniques on how to optimize the performance. So we're going to talk about the partitions.
21:10:59
데이터를 최적화하기 위해 어떻게 나눌 것인지에 대해 이야기하겠습니다. 자, 시작합시다.
So how to divide our data in order to optimize the performance. So let's go.
21:11:08
좋습니다. SQL 파티셔닝이란 무엇인가요? 큰 테이블을 작은 조각으로 나누기 위한 기술입니다.
All right, so what is SQL partitioning? It's a technique in order to divide a large table into small pieces.
21:11:15
각 조각을 파티션이라고 부릅니다. 큰 테이블을 더 작은 테이블로 나누는 것처럼 들리지만, 그렇지 않습니다.
And each piece, we call it a partition. Well, this sounds like we are dividing one big table into smaller tables, but it's not like that.
21:11:22
우리는 단지 하나의 테이블을 더 작은 파티션으로 나누고 있습니다.
We are just dividing one table into smaller partitions.
21:11:26
데이터베이스에서 여전히 하나의 단일 테이블로 보이지만, 내부적으로는 여러 파티션으로 나뉘어 있습니다.
So we're going to see it in the database still as one solid table, but behind the scenes, it is split it into multiple partitions.
21:11:33
이제 이것이 무엇을 의미하는지 이해해 봅시다. 자, 데이터베이스에 테이블이 있고 시간이 지남에 따라 이 테이블이 점점 커지고 있다고 가정해 봅시다.
So now let's go and understand what this means. Okay. So now let's say that you have a table at your database and over the time, this table is getting bigger and bigger where you have like hundreds of millions of rows.
21:11:45
이렇게 큰 테이블이 있으면 모든 것이 느려질 수 있습니다.
Now once you have such a big table what can happen everything gonna be slow.
21:11:48
예를 들어 테이블을 읽고 실행 계획이 테이블의 전체 스캔을 수행하면 모든 행이 가져올 때까지 SQL이 오랜 시간이 걸릴 수 있습니다.
So for example if we are reading the table and the execution plan is doing full scan of the table this can take SQL long time until all the rows are fetched.
21:11:58
이 테이블에 인덱스를 만들기로 결정하면 SQL이 매우 큰 B3 인덱스를 구축하게 되며, 많은 분기와 파일이 포함됩니다.
And if you decide to make like an index for this table what can happen is SQL gonna go and build a very big B3 index where there are a lot of branches and files and so on.
21:12:09
큰 인덱스를 갖는 것이 항상 좋은 것은 아닙니다. 삭제, 업데이트 또는 행 삽입과 같은 작업을 수행하면
And having a big index is not always a good thing because if you do operations like delete delete rows, update rows or inserting rows.
21:12:18
이 작업은 처리하는 데 오랜 시간이 걸릴 것입니다.
This operation is going to need a long time to process.
21:12:21
따라서 큰 인덱스가 있다고 해서 큰 테이블에 대한 좋은 성능을 보장하는 것은 아닙니다.
So having a big index doesn't mean that you can have a good performance for your big table.
21:12:26
따라서 큰 테이블을 갖는 것은 문제가 됩니다. 모든 것이 느려질 것입니다.
So that means having a big table is problematic because everything will be slow.
21:12:31
그렇다면 이 큰 테이블의 성능을 최적화하기 위해 우리는 무엇을 할 수 있을까요? 음, SQL 파티셔닝을 사용할 수 있습니다.
So now what we can do in order to optimize the performance of this big table? Well, we can use SQL partitioning.
21:12:38
이를 위해서는 우리 테이블에서 발생하는 동작과 트랜잭션을 이해해야 하며, 일반적으로 테이블은 시간이 지남에 따라 커집니다.
And in order to do that, we have to understand the behavior and the transactions that are happening on our table and what usually happen is that the table grows over the time.
21:12:49
따라서 2023년에 해당하는 데이터의 하위 집합과 2024년에 생성 및 업데이트된 데이터가 있을 수 있으며, 2025년에는 더 최신의 데이터가 있을 수 있습니다.
So you can have like subset of data that belongs to 2023 and another one that is created and updated in 2024 and then you have something like more current in 2025.
21:13:00
즉, 우리 테이블에는 오래된 데이터와 새로운 데이터가 있으며, 우리는 일반적으로 오래된 데이터보다 새로운 데이터와 더 자주 상호작용합니다.
So that means we have like in our table old data and as well new data and we usually interact with the new data more often than the old data.
21:13:09
예를 들어, 2023년에는 읽기 트랜잭션이 하나만 있을 수 있습니다.
So maybe for example, for 2023, there is like only one read transaction.
21:13:14
2024년 데이터의 경우, 우리는 두 번 읽고 한 번 쓰기를 했습니다. 그래서 2023년보다 조금 더 많습니다.
And for the data in 2024, we have done like two reads and one writes. So it is a little bit more than 2023.
21:13:21
하지만 현재 연도의 새로운 데이터는 많은 트랜잭션이 있을 것입니다. 그래서 우리는 많은 읽기와 많은 쓰기를 할 수 있습니다.
But for the new data for the current year, there will be heavy transactions. So we can have a lot of reads, a lot of writes.
21:13:28
우리는 업데이트하고, 삽입하고, 읽고 있습니다. 그래서 새로운 데이터에 대해 많은 일이 진행되고 있습니다.
We are updating, inserting, reading. So a lot of things are going on for the new data.
21:13:34
즉, 우리는 새로운 데이터와 상호작용하기 위해 Bigtable에 자주 접근하고 있습니다.
So that means we are accessing frequently the Bigtable only to interact with the new data.
21:13:39
그리고 우리는 오래된 데이터는 거의 필요하지 않습니다. 그래서 우리가 할 수 있는 것은 이 큰 테이블을 나누는 것입니다. 우리는 일반적으로 날짜로 나눕니다.
and we rarely need the old data. So what you can do, we can go and divide this big table and we usually divide it by like a date.
21:13:48
즉, 우리는 이 테이블을 연도별로 나눌 수 있으며, 각 연도를 하나의 파티션에 넣습니다.
So that means we can go and split this table by the year and we put each year in one partition.
21:13:53
결국, 우리는 세 개의 파티션을 가질 수 있습니다. 그리고 이제 이것들이 세 개의 파티션이라는 것을 이해하는 것이 정말 중요합니다.
So at the end, we can have like three partitions. And now it's really important to understand that those are three partitions.
21:13:59
그들은 세 개의 테이블이 아닙니다. 즉, 클라이언트 측에서는 사용자들이 단 하나의 테이블만 볼 수 있습니다.
They are not three tables. So that means at the client side, the users can see only one table,
21:14:05
하지만 이면에서는 세 개의 파티션이 있습니다. 이제 2025년의 데이터를 읽기 위한 쿼리가 있다고 가정해 보겠습니다.
but behind the scenes, we have like three partitions. Now, let's say that you have a query in order to read the data from 2025.
21:14:12
이제 SQL은 테이블의 모든 데이터를 스캔하지 않고, 오직 하나의 파티션인 2025년만 타겟팅할 것입니다.
And now what can happen is SQL will not go and scan all the data from the table. It's going to go and only target one partition, the 2025.
21:14:20
즉, SQL은 관련 정보, 즉 관련 파티션만 스캔하고 전체 테이블은 스캔하지 않습니다.
So that means SQL is only scanning the relevant information, the relevant partition and not the entire table.
21:14:27
이제 우리는 파티션을 갖는 또 다른 이점을 갖게 되었습니다. 현대 데이터베이스를 사용하고 있다고 가정해 보겠습니다. 일반적으로 이들은 병렬 처리를 지원합니다.
And now we have another benefit of having partitions. Let's say that you are using a modern database and normally they support parallel processing.
21:14:35
따라서 이를 위한 인프라가 있다면, 데이터베이스 엔진은 각 파티션을 독립적이고 병렬로 처리할 수 있습니다.
So if you have the infrastructure for that, what can happen, the database engine can process each partition independently and parallelly.
21:14:43
따라서 데이터를 읽거나 쓰는 경우, SQL은 쿼리를 병렬로 처리할 수 있으며, 이는 전체 실행 시간을 줄일 수 있습니다.
So whether you are reading or writing data, so what's going to happen, SQL can process your queries parallelly, which of course can reduce the overall execution time.
21:14:53
즉, 현대 인프라가 있다면, 예를 들어
So that means if you have a modern infrastructure, like maybe
21:14:56
Azure Synapse와 같은 것을 사용하여
for example, the Azure Synapse and so on, go with
21:14:59
파티션을 사용하세요. 파티션은 서로 다른
the partitions because the partition then could be stored in different
21:15:02
서버에 저장될 수 있으며, 이는 SQL 엔진이
servers and this helps of course the sql engine to
21:15:06
모든 리소스를 동시에 사용할 수 있도록 도와줍니다. 즉,
use all the resources at once so this means
21:15:09
파티션은 확장성을 허용하고 병렬 처리도 가능하게 합니다.
partitions allow scalability and as well parallel
21:15:12
파티션을 처리하면 인덱싱이 더 효율적이 되어 전체 테이블에 대해 매우 큰 인덱스를 가지는 대신 파티션 테이블에 인덱스를 추가하면 어떤 일이 발생할 수 있습니다.
processing partitions gonna make the indexing more efficient so instead of having one very big index for the whole table if you put an index on a partition table what can happen
21:15:24
각 파티션은 자체 인덱스를 가지게 되며 이는
each partition gonna get its own index which means
21:15:27
인덱스의 크기가 더 작아질 수 있고
the size of the indexes can be smaller and
21:15:30
물론 이는 데이터 검색에 많은 도움이 되며
of course this helps a lot with searching for data or
21:15:34
인덱스 자체를 확장하는 데도 도움이 됩니다. 예를 들어
as well extending the index itself so for example if
21:15:37
2025 파티션에 데이터를 삽입하면
you are inserting data to the partition 2025 the
21:15:40
SQL은 다른 인덱스에서 아무것도 변경하지 않고
sql will not go and change anything on the other indexes it's
21:15:44
2025 파티션의 인덱스만 변경할 것입니다.
gonna go and only change the index of the partition 2025
21:15:47
이를 통해 파티셔닝의 힘을 볼 수 있습니다.
so that you can see the power of the partitioning
21:15:50
테이블의 성능이 크게 향상됩니다.
it improves significantly the performance of your table
21:15:53
데이터를 읽거나 쓸 때 이
whether you are reading or writing data to this
21:15:56
큰 테이블에 대해 파티셔닝이 필요하다는 의미입니다.
big table so this is what we mean with partitioning and
21:15:59
왜 우리가 그것을 모두 필요로 하는지
why we need it all
21:16:04
좋은 친구들, 이제 파티션 생성 프로세스로 넘어가겠습니다.
right friends so now we're gonna go to the process of creating partitions
21:16:08
SQL에서 시작할 때는 다소 복잡하게 들릴 수 있습니다.
in sql at the start it might sound a little bit complicated
21:16:11
하지만 단계별로 진행할 것이며, 이를 위한 스케치가 있습니다.
but we're gonna do it step by step and i have a sketch for
21:16:14
데이터베이스에 여러 레이어가 있기 때문에 네 단계가 있습니다.
that so we have like four steps because we have in the database like
21:16:18
그럼 어떻게 할 수 있는지 봅시다.
multiple layers so let's see how we can do that let's
21:16:21
첫 번째 단계는 파티션을 정의하는 것입니다.
go so the first step in that we're gonna go and define the partition
21:16:24
함수에서 우리가 정의할 것은
function so what is that we're gonna go and define here in
21:16:27
테이블을 파티션으로 나누는 방법에 대한 논리입니다.
the function the logic on how to divide the
21:16:30
이것은 파티션 키를 기반으로 하며, 이는
table into partitions and this can be based on
21:16:34
논리를 정의하기 위해 열이 필요함을 의미합니다.
the partition key so this means we need a column in
21:16:37
주로 주문 날짜와 같은 날짜 열을 사용합니다.
order to define the logic and we usually use columns with the
21:16:40
다른 시나리오에서는 지역이나 국가를 사용할 수 있지만 가장 유명한 것은 날짜입니다.
dates like for example the order dates or in
21:16:43
다른 시나리오에서는 지역이나 국가 등을 사용할 수 있지만 가장 유명한 것은 날짜입니다. 그 이유는 우리의 테이블이 시간이 지남에 따라 커지기 때문입니다.
other scenarios we can use the region or country and so on but the most famous one is the date and that's because our tables like get bigger over the
21:16:52
시간이 지나면서 여러 종류의 함수가 있습니다.
time and there are like multiple types of functions we're going
21:16:55
우리는 범위 함수에 집중할 것이며, 그것이 어떻게 작동하는지 알아보겠습니다.
to focus on the range function so how it's going to work we're
21:16:58
우리는 날짜의 범위를 가질 것이고, 경계를 정의해야 합니다.
going to have like a range of dates and then we have to define like boundary
21:17:02
각 연도를 위한 파티션을 만들고 싶다고 가정해 보겠습니다.
values and let's say that i would like to make a partition
21:17:05
그렇게 하기 위해서는 파티션 경계를 정의해야 합니다.
for each year and in order to do that we have to define
21:17:09
연도의 경계는 이렇게 될 수 있습니다. 연도의 첫날이나 마지막 날입니다.
the partition boundary so it is like a value
21:17:12
여기 예제에서는 경계로 연도의 마지막 날을 사용할 것입니다.
the boundary of the years could be like this first day of the year or the last day of the year so here in this example we're going to
21:17:18
2023년, 2024년, 2025년의 마지막 날입니다.
take for the boundary the last day of the year so
21:17:21
그래서 우리는 그 값을 경계라고 부릅니다.
the last day of 2023 2024 and 2025
21:17:25
우리 함수의 경계 사이에는
so we call those values the boundary
21:17:28
파티션이 있을 것입니다. 예를 들어 모든 행이
of our function now between the boundaries we're
21:17:31
2025년 및 이전 연도의 경우입니다.
gonna have our partitions so for examples all the rows
21:17:34
2025년 및 이전 연도의 경우, 파티션 1이 될 것입니다.
for 2025 and earlier years it's
21:17:38
경계와 그 이전의 모든 것이 하나의 파티션이 되고, 그 후 두 경계 사이에는
gonna be the partition one so between the boundary and everything before is one partition and after that between the two
21:17:44
파티션 2가 있습니다. 이 파티션은
boundaries we have partition two so this partition is going to be for
21:17:47
2024년의 모든 행을 위한 것입니다.
all rows of 2024 and then we have
21:17:50
2024년의 모든 행 후에
another section the partition three where we have all
21:17:53
2025년의 모든 행과 마지막 경계 사이에 있습니다.
rows of 2025 and then between the last boundary
21:17:57
그리고 그 이후의 모든 것은 파티션 4가 될 것입니다.
and everything onwards it's going to be partition four
21:18:00
여기에서는 2026년 이후의 모든 행을 가질 것입니다.
and here we're going to have all the rows from 2026 onwards
21:18:03
그래서 우리는 이제 SQL에 어떤 논리를 전달하고 있습니다.
so with that we have now a logic we are telling sql
21:18:06
데이터를 여러 파티션으로 나누는 방법입니다.
how to divide our data into multiple
21:18:09
여기에는 두 가지 방법이 있습니다. 왼쪽
partitions and here there is like two methods the left
21:18:12
그리고 오른쪽입니다. 그 두 가지 방법은 무엇인가요?
and the right so what are those two methods so
21:18:16
다시 우리는 경계를 가지고 있고 이제 큰 질문은
again we have our boundary and now the big question to
21:18:19
이 경계가 어떤 파티션에 속하는가입니다
which partition does this boundary belongs to is
21:18:22
그것은 파티션 1인가 파티션 2인가, 그래서 우리는
it partition one or partition two and that's why we have those
21:18:25
두 가지 방법이 있습니다. 왼쪽이라고 말하면 경계는
two methods if you say it is left that's meaning the boundary
21:18:28
파티션 1에 속하지만 다른 한편으로는
belongs to the partition number one but in the other hand
21:18:31
오른쪽이라고 말하면 경계는 파트가 되고 파티션 2에 속합니다. 그래서 경계가 왼쪽 파티션에 속하는지 오른쪽 파티션에 속하는지 결정해야 합니다.
if you say it is right then the boundary gonna be part and belongs to the partition number two so you have to decide whether the boundaries belongs to the left partition or to the right partition.
21:18:42
그것에 따라 파티션 1에서는 2023년의 모든 행을 가질 수 있습니다. 2023년의 마지막 날도 포함됩니다. 파티션 2에서는 2024년에만 집중합니다.
And with that in the partition one, we can have all the rows of 2023, including the last day of 2023, because in the partition two, we only focus on 2024.
21:18:53
그래서 경계는 왼쪽 파티션에 속합니다. 매우 간단합니다. 이제 SQL에서 구현해 보겠습니다.
So it's just the boundary belongs to the left partition. It's very simple. Now let's go and implement that in SQL.
21:18:59
그럼 시작해 봅시다. 구문은 매우 간단합니다. 파티션을 생성하겠다고 말할 것입니다.
So let's do it. The syntax is very simple. We're going to say create partition
21:19:05
함수 그리고 이름을 지정해야 하므로 파티션이 될 것입니다.
function and then we have to give it a name so it's going to be partition
21:19:09
연도별로 나누기 때문에
by year since we are dividing
21:19:12
연도별로 데이터를 나누고 나서
the data by the year and after that we have to define the
21:19:16
데이터 유형을 정의해야 하므로 데이터를
data type so we are splitting the data by a
21:19:19
날짜로 나누게 됩니다. 그래서 날짜가 될 것이고, 그 후에 파티션 함수 유형을 정의해야 합니다. 예제에서는 범위를 사용하고 있으며, 이제 왼쪽인지 오른쪽인지 정의해야 합니다.
date so it's going to be date and after that we have to define the partition function type so in our example we are using the range and now we have to define whether it is left or right
21:19:30
우리는 왼쪽으로 고정할 것입니다. 이제 매우 중요한 단계가 있습니다. 경계를 정의해야 합니다.
we're going to stick with the lift. And now comes the very important step. We have to define the boundaries.
21:19:36
그래서 우리는 값에 대해 말할 것이고 여기서 세 개의 경계를 입력할 것입니다.
So we're going to say for values and we're going to enter here three boundaries.
21:19:41
예제처럼 각 연도에 대해 날짜를 정의할 것입니다.
Like in our example, for each year, we're going to define a date.
21:19:45
그래서 2023년과 연말입니다.
So 2023 and the last day of the year.
21:19:49
2024년과 마지막으로 2025년도 마찬가지입니다.
Same goes for 2024 and for the last one 2025.
21:19:57
그래서 이를 통해 우리는 논리를 정의했습니다.
So with that, we have defined the logic.
21:20:00
정의한 범위와 경계를 설정했습니다.
the range we have defined the boundaries and
21:20:03
경계가 날짜라고 사각형에 알려주므로 가겠습니다.
we tell the square the boundaries are a date so let's go
21:20:06
그리고 우리의 함수를 실행합시다. 좋아요, 그래서
and execute our function okay so
21:20:09
그게 전부입니다. 보시다시피 매우 간단합니다. 우리는 단지 함수를 만들었습니다.
that's it as you can see it's very simple we just created a function
21:20:12
날짜를 기준으로 데이터를 나누는
that split the data by the date using
21:20:15
범위가 남아 있고 물론 이 함수는 아직 연결되지 않았습니다.
the range left and of course this function is not yet attached
21:20:19
어떤 테이블이나 다른 것에 연결되지 않았습니다. 단지 논리일 뿐입니다.
to any tables or anything it is just a logic that
21:20:22
데이터베이스에 저장되어 있습니다. 이제 우리의 파티션
is stored in the database all right so now since our partition
21:20:25
함수가 데이터베이스 안에 저장되어 있으므로 메타데이터를 갖게 됩니다.
function is stored inside the database we will have metadata
21:20:28
시스템 스키마에 저장된 함수에 대한 메타데이터입니다.
about those functions stored in the system schema
21:20:32
그래서 우리는 파티션 함수라고 불리는 전용 테이블이 있습니다.
so we have there a dedicated table called partition functions
21:20:35
그리고 거기서 모든 함수에 대한 정보를 찾을 것입니다.
and there we're going to find informations about all functions
21:20:38
우리 데이터베이스 안에 있는 함수들입니다. 이제 실행해 봅시다.
that we have inside our database so let's go and execute it
21:20:41
그리고 보시다시피 이제 새로 생성된 파티션 함수를 찾았습니다.
and as you can see we find now our new created partition function
21:20:45
그래서 연도로 파티션을 나누면 범위가 있고 ID가 있으며, 새로운 파티션 함수를 만들기 전에 확인하는 것을 권장합니다.
so partition by year it is a range and it has an id and so on and i really recommend you to check it before creating any new partition function maybe you have already one in the projects
21:21:00
좋습니다. 이제 우리의 프로세스에서 다음 단계를 확인해 봅시다. 파일 그룹을 만들 것입니다. 파일 그룹이란 무엇인가요?
Okay, so now let's check the next step in our process. We're going to go and build now the file groups. So what is a file group?
21:21:07
하나 이상의 데이터 파일의 논리적 컨테이너와 같습니다. 매우 간단합니다. 폴더와 같습니다.
It is like a logical container of one or more data files. So it's very simple. It's like folders.
21:21:14
이제 여러 개의 폴더를 만들 것입니다. 나중에 그 안에 파일을 삽입할 수 있습니다.
We're going to go and create now like multiple folders. So later we can insert inside them files.
21:21:20
이것은 정말 좋습니다. 데이터 파일이 각 파티션에 어떻게 조직되는지를 결정할 수 있는 자유와 유연성을 제공합니다.
And this is really nice because it gives us like freedom and flexibility where we can go and decide how the data files are organized for each partition.
21:21:29
우리가 일반적으로 하는 것은 각 파티션에 대해 파일 그룹을 만드는 것입니다.
So what we usually do, we go and create for each partition, a file group.
21:21:33
그래서 2023, 2024 등을 위해 네 개의 폴더 또는 네 개의 파일 그룹을 가질 것입니다.
So we're going to have like four folders or four five groups for 2023 2024 and so on.
21:21:39
좋습니다. 이제 SQL로 돌아가서 그렇게 하겠습니다. 좋습니다. 이제 그 다섯 개의 그룹을 만들겠습니다. 구문은 매우 간단합니다.
So now let's go back to SQL in order to do that. All right, so now let's go and create those five groups. The syntax is very simple.
21:21:45
그래서 데이터베이스를 변경하라고 할 것입니다. 그리고 이제
So it's going to say alter database. And now
21:21:48
이 다섯 개의 그룹이 어디에 저장되어야 하는지 데이터베이스에 알려야 합니다.
we have to tell the database where these five groups should be stores
21:21:52
어떤 데이터베이스에 저장할 것인지, 그래서 저는 판매 데이터베이스에 머물 것입니다.
in which database so i'm going to stay with the sales db
21:21:55
그리고 나서 우리는 괜찮은 파일 그룹을 말해야 합니다.
and then we have to tell okay ads file
21:21:58
그 후 파일 그룹의 이름을 정의해야 합니다.
group and after that we have to define the name of
21:22:01
첫 번째는 2023년용이 될 것이므로 구문은 매우 간단합니다. 다른 연도에 대해서도 진행하겠습니다.
the file group so the first one going to be for 2023 so the syntax is very simple let's go and do it for the other years so we need 2024
21:22:12
2024, 2025, 2026이 필요합니다. 좋습니다. 그게 전부입니다.
five and six okay so that's all we can just
21:22:15
모든 것을 선택하고 실행합니다. 보시다시피 매우 간단합니다.
select everything and execute so as you can see it's
21:22:18
매우 간단합니다. 우리는 방금 네 개의 파일 그룹을 만들었습니다.
very simple we have just created four file groups and
21:22:21
그들은 비어 있으므로 그 컨테이너 안에 아무것도 없습니다.
they are empty so we don't have anything inside those containers now
21:22:25
이름 지정에서 실수를 했다고 가정해 보겠습니다.
let's say that you have made mistake with the namings and so on and you
21:22:28
그 중 하나를 삭제하고 싶다면 구문은
would like to drop one of them so the syntax is
21:22:31
또한 매우 쉽습니다. 변경된 데이터베이스 판매가 유지됩니다.
as well very easy so it's going to stay altered database sales
21:22:34
db이고 ads 대신 remove라고 말할 수 있습니다.
db and instead of ads you can say remove so
21:22:38
이 명령을 실행하면 이 파일 그룹이 삭제됩니다.
once you execute this this file group will be dropped
21:22:41
하지만 우리는 필요하므로 다시 생성해 보겠습니다.
but we need it so let's go and recreate
21:22:44
이제 일반적으로 항목을 생성한 후 확인해 보겠습니다.
it now as usual after creating stuff let's check whether
21:22:47
모든 것이 올바르게 생성되었는지 확인하고
everything is created correctly and whether we have
21:22:51
중복이 있거나 잘못된 것이 있는지 확인합니다.
any duplicate or anything wrong so with that we have
21:22:54
그렇게 해서 우리는 시스템 내에 파일 그룹 테이블을 가지고 있습니다.
as well a file group table inside the system
21:22:57
스키마를 실행해 보겠습니다. 저는 단순히
schema and let's go and execute it so i'm just
21:23:00
파일 그룹에 대해 fg 유형으로 필터링하고 있습니다.
filtering with the type fg for file group so
21:23:03
이제 실행해 보겠습니다. 이제 데이터베이스에서 네 개의 파일 그룹이 있습니다.
let's execute it and now we can see in our database we have four file groups now four of those five groups we just created it right so we have that 2023, 24 and so on.
21:23:14
하지만 우리는 기본 파일 그룹이라는 것이 있습니다. 이는 각 데이터베이스에 대해 생성되는 기본 파일 그룹입니다.
But we have something called primary file group. This is the default file group that is created for each database.
21:23:21
따라서 이는 데이터베이스의 모든 데이터 파일을 위한 컨테이너입니다.
So it is a container for all data files in your database. And as you can see, we have here flags saying it is a default.
21:23:28
기본값이므로 하나가 있으며 나머지는 기본값이 아닙니다.
So it's default and we have it one and for the rest, they are not the defaults.
21:23:32
모든 파일 그룹을 확인하여 중복이 없는지 확인하는 것이 정말 좋습니다.
So this is really nice to see all the file groups inside your database to check that you don't have duplicate and so on.
21:23:42
이제 물리적으로 더 많은 단계로 넘어가겠습니다.
okay now moving on to the third step where things can get more physically
21:23:45
지금까지 우리는 파일 그룹과 같은 기능을 가지고 있습니다.
so so far we have like a function the file group and all those
21:23:48
이것들은 논리적 개념이며 아직 데이터가 없습니다.
stuff are logical stuff we don't have data yet in order
21:23:51
데이터를 가지려면 데이터 파일을 생성해야 합니다.
to have data we have to go and create data files
21:23:55
이전에 배운 대로 데이터 파일은 실제 데이터를 포함합니다.
so as we learned before data files gonna contain our actual
21:23:58
데이터베이스에 물리적으로 저장됩니다.
data and they're gonna be stored physically in the database so
21:24:01
각 파일 그룹에 대해 하나 또는
you can go and assign for each file group like one or
21:24:04
여러 데이터 파일과 파일 형식은
multiple data files and the file format here is
21:24:08
dot mdf입니다. 이는 보조 데이터 파일입니다.
dot mdf it is secondary data files
21:24:11
우리는 주 데이터와 보조 데이터가 있지만, 파티션에서는
we have like primary and secondary but in the partitions we
21:24:14
보통 이 mdf 형식을 사용합니다. 다시 말해 파일
usually go with this format that mdf so again the file
21:24:17
그룹은 비논리적 컨테이너이고 데이터 파일은
groups are illogical containers and the data files are
21:24:20
실제 데이터가 저장될 수 있는 물리적 파일입니다.
physical files where our actual data can be stored inside
21:24:23
그렇습니다. 이제 SQL로 돌아가서 데이터를 생성해 보겠습니다.
it so now let's go back to sql in order to create some data
21:24:26
파일입니다. 이제 조금 귀찮은 부분으로 가겠습니다.
files okay so now we're going to come to the little bit annoying part
21:24:29
여기서 파일을 생성할 건데, 구문은
where we're going to go and create files but the syntax is as
21:24:32
매우 간단합니다. 같은 내용을 말할 것입니다. 데이터베이스 변경
well very simple so we're going gonna say the same things alter database
21:24:36
우리의 데이터베이스는 sales DB이고
and our database is sales DB and then
21:24:39
이번에는 파일 추가라고 말할 것입니다. 이제 우리는
this time we're gonna say add file and now we
21:24:42
SQL에 이름뿐만 아니라 물리적
have to give SQL not only the name but the physical
21:24:45
파일의 위치를 제공해야 합니다. 그러니 단계별로 진행하겠습니다.
place of the files so let's do it step by step we're gonna
21:24:48
여러분은 두 개의 괄호를 열어야 합니다. 먼저 SQL에 논리적 이름을 정의해야 합니다. 파일 이름이 아닌 파일의 논리적 이름이므로
open you two parentheses so first we have to define for SQL the logical name it is not the file name it is the logical name of the file so let's give the
21:24:57
예를 들어 이름을 2023으로 하고
name for example, be 2023 and
21:25:00
그 다음에는 이 논리적 이름입니다.
then cover so this is the logical name
21:25:03
이제 다음은 물리적 이름을 제공할 것입니다.
and now the next one is we're going to give the physical name
21:25:07
파일과 경로를 함께
of the file together with the path so we're going to say file
21:25:10
파일 이름을 정의해야 합니다. SQL 서버에는
name equal and now we have to define for sql the
21:25:14
파일의 전체 경로가 있습니다. SQL 서버에는
complete path of the file in sql server there is
21:25:17
데이터가 저장될 기본 경로가 있습니다.
like a default path where the data going to be stored and
21:25:20
저는 같은 경로를 사용할 것이고, 경로는 정말로
i'm going to go and use the same path and the path really depends
21:25:23
버전과 SQL 서버의 유형에 따라 다릅니다.
on the version and as well the type of the sql server
21:25:26
현재 사용 중인 버전
that you are using so for the current version that i'm using for
21:25:30
이 튜토리얼을 위해 여기에서 찾을 수 있습니다
this tutorial we can find it over here in this path
21:25:33
C 드라이브로 가면 프로그램 파일 Microsoft
so if you go to the c then program files microsoft
21:25:36
SQL 서버 MSQL과 저의 버전은
sql server msql and the version for
21:25:39
16 SQL Express이며 MSQL 내부에
me is 16 sql express and then inside msql
21:25:43
데이터가 있습니다. 이 폴더 안으로 들어가겠습니다.
data and so on so we're going to go inside this folder and
21:25:46
여기에서 모든 데이터베이스 파일을 볼 수 있습니다.
now we can see over here all the database files so
21:25:50
예를 들어 여기에서 판매 데이터베이스와 로그를 볼 수 있습니다.
we can see for example here the sales db the sales db logs
21:25:53
어드벤처 작업 데이터베이스도 있습니다. 모든 파일을 볼 수 있습니다.
and we have here the adventure works and so on so you're going to see all
21:25:56
데이터베이스 파일과 파티션 파일을 기본 폴더에 넣겠습니다.
the files of your database and what we're going to do we're going to put as
21:25:59
실제 프로젝트에서는 데이터베이스 관리자에게 정확한 위치를 문의해야 합니다.
well our partitions files inside the default folder
21:26:03
파티션에 대해 SQL로 돌아가겠습니다.
but for real projects you have to ask the database administrators about the exact location where you can put your
21:26:09
여기에서 이 경로를 설정하고
partitions so let's go back to sql and i'm going
21:26:12
파일 이름을 지정해야 합니다. p2023입니다.
to put this path over here and then we have to specify
21:26:15
점과 함께 파일 이름을 지정해야 합니다.
the file name so it's gonna be p2023
21:26:19
df에 넣고 이제 완전한 경로가 있습니다.
dots and now we have to specify the file name so
21:26:22
파일 이름과 함께 거의 다 왔습니다.
in df and with that we have now a complete path
21:26:25
아직 완료되지 않았습니다. SQL에 위치를 알려줘야 합니다.
with the file name so we are almost there but we are not
21:26:28
어떤 컨테이너와 파일 그룹에 넣을지
done yet we have to tell sql where to put this
21:26:31
여기로 가서 파일에 대해 말하겠습니다.
file in which container in which file group so we're
21:26:34
그룹을 선택하고 올바른 것을 선택해야 합니다.
gonna go over here and we're gonna say to file
21:26:37
fg 2023 모두
group and you make sure to select the correct one
21:26:40
그래서 fg 2023 모두
so fg 2023 all
21:26:43
좋아, 그게 다야. 이제 실행하자.
right so that's all let's go and execute it so
21:26:47
해보자. 그렇게 해서 우리는 안에 파일을 만들었다.
let's do it and with that we have created a file inside
21:26:50
파일 그룹을 만들지 않을 것입니다.
a file group i will not be creating like multiple files
21:26:53
하나의 파일 그룹 안에서는 일대일로 진행될 것입니다.
inside one file group it's gonna be like one to one so now what we're
21:26:56
각 파일 그룹에 대해 다른 파일을 생성할 것입니다.
gonna do we're gonna go and create the other files for each file group for each year so we just have to copy and paste and just change the
21:27:03
2024년을 위해 이렇게 될 것입니다.
names so for 2024 gonna be like this so that's it and the same thing for 2025
21:27:17
마지막으로 2026년을 위해서입니다.
and for the last one 2026 and
21:27:25
이제 모든 것을 선택하고 실행할 수 있습니다.
we can go and select now everything and execute it so that's it with that we have created now
21:27:32
네 개의 다른 파일을 생성했습니다.
four different files and we have mapped as well each
21:27:35
나는 보통 많은 파일을 생성하지 않습니다.
file to the correct file group and i usually don't
21:27:38
나는 매년 하나씩만 생성합니다.
create like a lot of files i just create like one for each year
21:27:42
또는 여러 해를 묶어서 생성합니다.
or maybe four bunch of years so you don't have to go
21:27:45
각 날짜에 대해 파티션을 만들 필요는 없습니다.
and make for each day like partition or something like that okay as
21:27:48
이제 메타데이터를 확인해야 합니다.
usual after creating stuff we have to go and check the metadata now
21:27:52
파일 그룹을 쿼리하는 쿼리를 준비했습니다.
have here prepared a query where we query the file groups
21:27:55
모든 데이터 정보가 포함됩니다.
together with the files so all the data informations
21:27:58
마스터 파일 테이블에 있습니다.
could be found inside the table master files and then we
21:28:01
그 테이블을 조인하고 데이터베이스를 선택합니다.
join those tables and select our database so let's
21:28:04
이 쿼리를 실행해 보겠습니다.
go and query this one and now you're gonna get a list of
21:28:07
데이터베이스 안의 모든 파일 목록을 얻을 수 있습니다.
all files inside your database so we
21:28:11
여기에서 데이터베이스의 기본 정보를 확인할 수 있습니다.
see over here we have the primary for the database
21:28:14
파일의 경로와 크기를 확인할 수 있습니다.
itself and you can see the path of the file and as
21:28:17
여기에서 네 개의 파일이 있습니다.
well the size of it and we can see over here we have four files
21:28:20
각 파일에 할당된 파일 그룹과 전체 경로입니다.
and the file group that is assigned to and the complete
21:28:24
각 파일의 크기가 어떻게 증가하는지 모니터링할 수 있습니다.
path of each file and you can monitor over here of
21:28:27
시간이 지남에 따라 하나의 파일이 매우 커질 수 있습니다.
course how the size of each file is growing over
21:28:30
그렇다면 여러 파일로 나누는 것을 고려할 수 있습니다.
the time maybe one of them is getting like really big and then you can think about let's go and split it to multiple files so that's it about how to create data files
21:28:44
좋습니다. 이제 마지막 단계로 넘어가서
all right so now we're gonna move to the last step where we're gonna go and define
21:28:47
함수 스킴을 정의할 것입니다. 이 그림을 보면
the function scheme now if you have a look to this picture
21:28:50
한쪽에서 뭔가 빠져 있다는 것을 알 수 있습니다.
you see that there is something missing from one side we
21:28:53
우리 데이터가 여러 개로 나누는 방법을 정의했습니다.
have defined how to divide our data into multiple
21:28:56
파티션과 다른 쪽에서 모든 파일과
partitions and from the other side we have repaired all the
21:28:59
파일 그룹을 복구했습니다. 이제
files and the file groups and so on and now what is
21:29:02
부족한 것은 이들을 연결하는 방법입니다.
missing is the connection how to connect those
21:29:05
파티션을 파일 그룹에 연결하는 방법입니다.
partitions to the file groups and we can do that by
21:29:08
파티션 스킴을 사용하여 지금 우리가 하는 것은
using the partition scheme so all what we are doing now is
21:29:11
어떤 파티션이 어떤 파일 그룹에 속하는지를 정의하는 것입니다.
just defining which partition belongs to which
21:29:15
예를 들어, 파티션 하나를 파일 그룹 2023에 매핑할 것입니다.
file group so for example we're gonna go and map the partition
21:29:18
2023의 모든 데이터가
one to the file group 2023 and with
21:29:21
파일 그룹 2023으로 가게 될 것입니다.
that all the data of 2023 and earlier gonna
21:29:24
물론 각 파티션을 파일 그룹에 매핑해야 합니다.
go to the file group 2023 and of
21:29:27
그렇지 않으면 SQL에서 오류가 발생합니다.
course we have to go and map each partition to a file group
21:29:30
우리가 파티션 스킴을 구축하면 모든
if you don't do that you will get error in sql and
21:29:33
파티션 스킴을 구축하면 모든 것을 준비할 수 있습니다.
once we build the partition scheme then we can have all
21:29:37
파티션 테이블을 만들기 위해 구성 요소를 준비해야 하므로, 이제 파티션 함수가 데이터를 여러 파티션으로 나누는 방법을 결정하는 것을 간단히 요약해 보겠습니다.
the components ready in order to have partition table so now let's have a quick summarize the partition function gonna decide on how to split your data into multiple partitions.
21:29:47
파티션 스킴은 파티션을 파일 그룹에 매핑하며, 이 다섯 개 그룹은 파일을 정리하기 위한 폴더와 같습니다.
The partition scheme going to go and map the partitions to a file group and the five groups are like folders in order to organize your files.
21:29:56
각 파일 그룹에는 하나 이상의 데이터
And each file group has one or more data
21:29:59
파일이 있으며, 실제 데이터가 물리적으로 저장될 위치입니다.
files where your actual data are going to be stored physically at
21:30:02
이 파일들은 처음에는 혼란스러울 수 있지만, 이제 각 레이어를 이해하면
these files at the start it might be confusing but now as
21:30:06
파티션을 구축하는 것이 더 쉬워질 것입니다.
you understand each layer then it's going to make it easier for you
21:30:09
이제 SQL로 돌아가서 파티션 스킴을 구축합시다. 자, 이제 모든 것을 연결할 가장 쉬운 부분이 있습니다. 구문은 매우 간단합니다. 'create'라고 말할 것입니다.
to build partitions so now let's go back to sql in order to build the partition scheme okay so now we have the easiest part where we're going to connect everything together so the syntax is very simple it's going to say create
21:30:21
파티션 스킴을 만들고 이제 이름을 지정해야 합니다.
partition scheme and now we have to give it
21:30:24
이름을 정해야 하니 파티션 스킴을
a name so let's go with like scheme partition by
21:30:29
연도로 가고 파티션 함수를 매핑해야 합니다
year and now we have to map the partition function
21:30:32
파일 그룹으로 먼저 이렇게 말할 것입니다
with the file groups so first we're going to say as
21:30:35
그리고 여기서 파티션 함수를 정의합니다
and then we define here the partition function so
21:30:39
파티션으로 그리고 이제 파티션이 필요합니다
as partition and now we need the partition
21:30:42
우리가 만든 함수를 파티션으로 사용합니다
function that we have created to as partition by
21:30:45
연도로 그리고 그 후에 매핑할 것입니다
year and then after that we're gonna map
21:30:49
다섯 그룹으로 매핑하는 것이 매우 중요합니다
it to the five groups and here it is very important to
21:30:52
올바른 순서로 매핑하는 것이 중요합니다
map it in the correct order so the order is very
21:30:55
첫 번째는 파일 그룹 2023이었습니다
important so the first one was file group 2023
21:30:59
두 번째는 2024년이고
the second one 2024 and
21:31:02
2025년과 마지막은
we have 2025 and the last one
21:31:05
2026년입니다 다시
2026 so again the
21:31:09
순서가 매우 중요하고 약간 까다로울 수 있습니다
order is very important and as well it's going to be a little bit tricky so sometimes as you are creating like the functions maybe you make mistake that you
21:31:16
우리의 예에서 세 개의 경계가 있습니다
know how much partitions is going to create like in
21:31:19
네 개의 파티션을 생성할 것입니다
our example we have three boundaries and is going to create four
21:31:23
가끔씩 세 개의 경계가 있다고 생각합니다
partitions so it happens sometimes that you think okay i
21:31:26
세 개의 파티션을 얻을 것이라고 생각합니다
have three boundaries and then i'm gonna get three
21:31:29
그것은 정말 정확하지 않습니다 예를 들어
partitions which is not really correct so for example
21:31:32
그 중 하나를 제거하고 세 개의 그룹만 있습니다
let me just remove one of those and let's say i
21:31:35
이제 실행하면 오류가 발생합니다
have only three five groups and let's go and execute this one over here now we are getting error it says the partition function generates more partitions
21:31:45
파티션 함수가 더 많은 파티션을 생성한다고 합니다
than the five groups and that is really correct because our
21:31:48
데이터를 네 개의 파티션으로 나눌 수 있습니다
definition of the logic can split the data into four
21:31:51
세 개의 그룹만 제공하고 있습니다
partitions and now we are giving a scale only three five
21:31:54
마지막 하나를 추가해야 합니다
groups which is not correct so we have to go and add the
21:31:58
마지막 하나와 한 가지 더, 퀼은 당신이
last one and one more thing is quill will not go and check whether you
21:32:01
다섯 그룹에 올바르게 매핑하고 있는지 확인하지 않을 것입니다. 왜냐하면 그것은 그 다섯 그룹의 이름에 대해 신경 쓰지 않기 때문입니다. 예를 들어, 당신이 이것을 끝에 두면
are mapping things correctly to the five groups because it doesn't really care about the naming of those five groups so for example if you go and put this one at the ends
21:32:10
무슨 일이 일어날 수 있는지는 큰 문제가 될 것입니다. 그래서 2023년의 모든 연도가 2024년에 저장될 수 있습니다.
what can happen is going to be a big problem so all the years of 2023 can be stored inside 2024
21:32:16
2024년은 2025년에 있을 것입니다.
2024 gonna be in 2025 so
21:32:19
모든 것이 뒤섞일 것이고 이 소녀는 당신이 말하는 대로 할 수 있습니다.
everything gonna be mixed and this girl can do it like you tell it so
21:32:23
그래서 올바른 정렬을 가지고 있는지 확인하세요. 그래서 그게 다입니다. 이제 우리의 스키마를 만들고 작동하는지 확인합시다. 우리는 이제 파티션을 다섯 그룹에 매핑했습니다.
that's why make sure you have that correct sorts so that's it let's go and create our scheme so it is working this is very simple we just mapped now the partitions to the five groups
21:32:35
그리고 보통처럼 생성 후에 확인합니다.
and as usual we check things after creating and
21:32:38
여기 메타데이터에서 정말 멋진 쿼리를 준비했습니다.
i have prepared here like really nice query from the metadata in
21:32:41
전체를 보기 위해 함수와 파일 그룹을
order to see the whole thing the functions the file groups
21:32:45
스키마를 추가할 수 있습니다. 물론 데이터 파일을 추가할 수 있습니다.
the schemes you can of course and add to it the data files
21:32:48
하지만 저는 여기서 이것에만 집중할 것입니다. 다시 말해, 스퀘어 서버에서
but i'm just gonna stick with this over here so again in square server
21:32:51
파티션 스키마를 위한 전용 테이블이 있습니다. 그런 다음 저는 그것을 함수와 결합하고 목적지 데이터 공간과 결합하여 파티션 번호와 파일 그룹을 얻습니다.
we have a dedicated table for the partition schemes then i'm just joining it with the functions and then with the destination data spaces in order to get the partition number and the file groups
21:33:02
그래서 이제 실행해 봅시다. 그리고 이제 우리가 만든 스키마와 파티션의 함수 이름을 아주 잘 볼 수 있습니다.
So let's go and execute it. And now we can see very nicely the scheme that we have created and the function name of the partition.
21:33:09
그런 다음 파티션 번호와 파일 그룹 이름을 볼 수 있습니다. 그래서 우리가 어떻게 매핑되었는지 볼 수 있습니다.
And then we can see the partition number and the file group name. So we can see how things are mapped together.
21:33:15
이렇게 되면 지금까지 모든 것이 좋습니다.
So if you get it like this, then so far everything is good.
21:33:23
좋습니다. 지금까지 우리가 한 일은 모든 레이어를 준비한 것입니다. 그래서 설정이 모든 테이블에서 사용될 준비가 되었습니다.
All right. So so far what we have done, we have prepared all the layers. So we have the setup is ready to be used in any table.
21:33:31
그래서 우리는 함수, 파일, 파일 그룹과 스키마를 가지고 있으며 모든 것이 준비되었습니다. 하지만 여전히 우리는 그것을 사용하지 않고 있습니다.
So we have the functions, the files, the file groups and scheme and everything is ready. But still, we are not using it.
21:33:37
논리는 존재하지만 파일은 비어 있습니다. 그래서 이제 우리가 할 일은 테이블을 만들 것입니다. 하지만 일반 테이블이 아니라 파티션 테이블입니다.
The logic just exists and the files are empty. So now what we're going to do, we're going to go and create a table, but not a normal one, a partition table.
21:33:44
그래서 이제 그걸 해봅시다. 아주 간단합니다. 테이블을 만들고 이름을 지정해야 합니다.
So let's go and do that. It's very simple as well. So create table and we have to give it a name.
21:33:50
그래서 판매 주문 스키마에서도 가져옵니다. 그리고 저는 주요 파티션을 제공할 것입니다.
So let's get it as well in the schema sales orders. And I'm just going to give it the main partitions.
21:33:55
그래서 이제 이 테이블 안에 몇 개의 열을 정의해야 합니다.
So now we have just to define like few columns inside this table.
21:33:59
주문 ID와 데이터를 가져옵시다.
so let's get an order id and data
21:34:03
정수형으로 하고 주문 날짜를 가져옵시다.
type int and let's go and get an order date we
21:34:06
날짜라는 이름으로 데이터 타입을 날짜로 하고 아마도
call it dates with the data type dates and maybe
21:34:09
하나 더 추가하여 판매라는 이름으로 데이터 타입을 정수로 하겠습니다.
just one more called sales and the data type int so
21:34:12
이것은 우리가 데이터베이스에서 만드는 매우 일반적인 테이블입니다.
this is very normal table that we create in databases but
21:34:16
아직 파티션이 설정되지 않았습니다. 우리가 정의한 모든 것을 사용하기 위해 다음과 같이 할 것입니다.
it's still not yet partitions now in order to use everything that we have defined we're gonna go do the following we're gonna say on and now we have have to tell SQL only the name of the partition scheme.
21:34:28
모든 것이 연결되어 있으며 스키마가 함수와 파일 그룹을 매핑하고 있습니다.
So everything else is like connected and mapped together because the scheme is mapping the function with the file groups.
21:34:35
파일 그룹은 데이터 파일에 매핑되어 있으며 모든 것이 연결되고 있습니다.
The file groups are mapped to the data files and everything is like connecting together. And here in the table we have just to give the name of the scheme.
21:34:42
파티션 스키마의 이름은 연도별 파티션 스키마입니다.
So the name of the partition scheme is a scheme partition by year.
21:34:48
이제 열을 제공하는 것이 매우 중요합니다. 전체 논리와 기능이 날짜를 기반으로 하기 때문입니다.
And now it's very important to give a column. And since the whole logic and the function is based on a date.
21:34:55
여기서 예를 들어 주문 아이디어와 판매를 지정할 수 없습니다.
We cannot go and specify here, for example, the order idea and sales because it makes no sense.
21:35:00
우리는 주문 날짜를 선택하고 여기에 배치할 것입니다.
we're going to go and pick the order date and put it over here
21:35:03
이렇게 해서 우리는 파티션 테이블을 생성했습니다.
and with that we have created a partition table so now what we're
21:35:06
이제 우리는 테이블에서 데이터를 삽입하기 시작할 것입니다.
going to do we're going to go and start inserting that out of our table so let's go and do that we're going to say inserts into sales order partitioned
21:35:17
우리는 이렇게 값을 선택할 것이고, 예를 들어 2023년의 날짜를 가져올 것입니다.
and we're going to pick values like this so one and then let's get any dates like 2023
21:35:23
예를 들어, 월 중간의 판매는 100일 수 있습니다.
like for example my the mid of the month and the sales could be anything like let's say 100.
21:35:28
이제 우리는 파티션 테이블에 하나의 레코드가 있습니다.
so let's go and execute this and let's go query our table so it is this one over here
21:35:39
이제 큰 질문은 SQL이 이 레코드를 어느 파티션, 어느 데이터 파일에 저장했는가입니다.
all right so now we have one record inside our partition table
21:35:42
모든 것이 잘 작동하는지 테스트해야 합니다.
and now the big question is in which partition in which data file did sql store these records so we have to test whether
21:35:49
그래서 우리는 다시 테이블에 질문을 하고 있습니다.
everything is working fine so in order to do that i have prepared
21:35:52
목적지 데이터 공간이 있는 파티션입니다.
as well a query so we are again asking the table
21:35:55
각 파티션의 행 수를 가져올 것입니다.
partitions with the destination data spaces where
21:35:59
우리는 테이블 주문 파티션에 집중하고 있습니다.
we're going to get the number of rows in each partition and then we have the file
21:36:02
이것을 실행해 보겠습니다.
group and we are focusing on our table orders partitions
21:36:05
우리는 네 개의 파티션이 있으며, 새로운 레코드는 2023 파일 그룹의 올바른 위치에 삽입되었습니다.
so let's go and execute this one and now we can see very easily
21:36:08
이로써 우리의 기능과 전체 논리가 올바르게 작동하는지 확인합니다.
we have the four partitions our new record is inserted in the correct place in 2023 file group and in the correct partition
21:36:17
이제 더 많은 레코드를 추가하겠습니다.
so with that we make sure our function and the
21:36:20
레코드 번호 2를 복제하고 2024년의 날짜를 선택할 것입니다.
whole logic that we have built is working correctly so now let's
21:36:23
값을 변경하여 50으로 설정하겠습니다.
go and add more records i'm just gonna go and duplicate it record number two and i'm just gonna pick a date in 2024 and this one gonna be like 20.
21:36:35
값을 50으로 변경합시다. 실행해 봅시다.
let's just change the value so 50. let's go and execute
21:36:39
이제 두 번째 행이 생겼습니다.
it and now we have a second row inside
21:36:42
우리 테이블에 다시 큰 질문은
our table and again the big question is whether
21:36:45
작동하는지 확인하기 위해 다시 실행해 봅시다.
it is working so let's go and execute this again and
21:36:48
이제 파티션 2에 레코드가 삽입된 것을 볼 수 있습니다.
now we can see our record is inserted in the partition 2 in
21:36:52
파일 그룹 2024가 맞습니다.
the file group 2024 which is correct
21:36:55
이제 작동하는지 경계를 확인해 봅시다.
now let's go and check the boundaries whether it is working
21:36:58
정확하게 작동하는지 확인하기 위해 여기서
correctly so i'm gonna go and here in
21:37:02
세 번째 행에서 2025년의 마지막 날을 말할 것입니다.
the third row i'm gonna say the last day of
21:37:05
12월의 마지막 날, 20일로 하겠습니다.
2025 so it's gonna be months 12 and
21:37:09
이제 삽입하고 테이블을 확인해 봅시다.
the last day so 20 let's
21:37:12
새 레코드가 생겼고 이제 확인해 봅시다.
go and insert it and check our table so
21:37:15
이 행이 삽입될 수 있는지 확인해 보겠습니다.
we have a new record and now let's go and
21:37:18
파일 그룹 2025에 삽입될 수 있습니다.
check my expectation here that this row can
21:37:21
실행해 봅시다. 맞습니다, 보시다시피
be inserted in the file group 2025 so
21:37:25
레코드가 올바른 파티션에 삽입되었습니다.
let's go and execute and that is correct as you can see
21:37:28
이것은 경계를 테스트하는 것이 정말 중요합니다.
the record is inserted in the correct partition
21:37:31
정확하게 작동하는지 확인하기 위해 약간 까다롭습니다.
and this is really important to test the boundaries whether they are working
21:37:35
여기서 기대하는 논리가 제대로 작동하는지 확인해 보겠습니다.
correctly because it's a little bit tricky you have this range left right and boundaries and so on so you can do it like this to check whether the
21:37:42
2026년의 첫날을 선택하겠습니다.
expectation of your logic is working correctly and the last one i'm just gonna do it very fast so let's do it 2026 and i'm gonna pick the first day of this year
21:37:55
이제 삽입하고 기대하는 것이 무엇인지 확인해 봅시다.
so let's go and insert it and now what is the expectation i
21:37:58
상당히 간단하다고 생각합니다. 쿼리를 실행해 봅시다.
think it is pretty simple so let's go and query and the first day of this year is inserted in the partition number four so i can say everything is working correctly if you get it like this then you have created successfully
21:38:10
파티션 테이블을 만들었고 이 파티션의 모든 레이어를 수정했습니다.
a partition table and you have repaired all the layers of this partition correctly.
21:38:15
이 작업이 많다는 것을 알고 있지만 솔직히 재미있습니다.
I know this is a lot of work but to be honest it is fun because for the first time in database you feel like you are controlling stuff.
21:38:22
데이터베이스에서 모든 것이 비하인드 씬처럼 보입니다.
Usually in database everything like behind the scenes and you don't know exactly where the files are stored of your tables and so on.
21:38:28
데이터베이스에는 많은 추상화가 있지만, 여기서는 데이터베이스를 깊이 파고들고 모든 파일을 제어하고 관리하고 있습니다. 때때로 이러한 자유와 유연성을 갖는 것이 좋습니다.
There is a lot of abstraction in databases but here like we are getting deep in databases and we are controlling and managing all those files which is sometimes it's nice to have this freedom and flexibility.
21:38:40
좋습니다. 제가 보여드리고 싶은 한 가지가 있습니다. 탐색기에서 데이터베이스로 가면, 여기서 저장소로 가봅시다.
All right, one quick thing that I would like to show you that if you go to the database in the explorer, then let's go to the storage over here.
21:38:47
자, 이제 확장해봅시다. 여기에서 파티션에 대한 정보를 쉽게 찾을 수 있습니다.
So let's expand it. And here you can find easily information about the partitions.
21:38:51
여기에서 우리의 파티션 스킴과 우리가 만든 파티션 함수를 찾을 수 있습니다.
So over here we can find our partition scheme and as well the partition function that we have created.
21:38:56
메타데이터를 쿼리하는 대신 빠른 접근입니다.
It is just a quick access instead of like querying the metadata.
21:39:04
이제 모든 것이 어떻게 연결되어 있는지 간단히 요약해봅시다. 우리는 테이블이 있고, 그 테이블은 파티션 스킴에 연결된 스케일을 지정합니다.
So now let's have a quick summarize how everything is connected together. So we have a table and then we specify for a scale that is connected to a partition scheme.
21:39:12
파티션 스킴에서 모든 것이 연결되어 있습니다. 특정 파티션 함수에 연결되어 있고, 그곳에 파티션이 있습니다.
And in the partition scheme, we have everything connected. It is linked to a specific partition function. And there we have the partitions.
21:39:20
동시에 파일 그룹에 연결되어 있습니다. 그리고 파일 그룹은 데이터 파일에 연결되어 있습니다.
And at the same time, it is connected to file groups. And the file groups are connected to the data files.
21:39:26
보시다시피, 모든 레이어와 요소가 서로 연결되어 있습니다. 이제 이것이 어떻게 작동하는지 봅시다. 우리는 2025년의 마지막 날을 삽입했습니다.
So as you can see, all those layers and elements are connected together. Now, let's see how this works. So we have inserted the last day of 2025.
21:39:34
이제 일어날 첫 번째 일은 파티션 함수가 어떤 파티션에 속하는지를 결정하는 것입니다.
And now the first thing that's going to happen, the partition function going to decide to which partition it belongs.
21:39:39
보시다시피, 이것은 경계 값입니다.
So as you can see, it is a boundary value.
21:39:42
우리가 그것을 리프트로 정의했기 때문에, 왼쪽 파티션인 파티션 3을 타겟으로 삼을 것입니다.
And since we have defined it as a lift, it's going to target the left partition, the partition three.
21:39:47
그런 다음 파티션 스킴이 이를 오른쪽 파일 그룹에 연결할 수 있습니다. 이 시나리오에서는 파일 그룹 2025가 될 것입니다.
And then the partition scheme can connect it to the right file group. And in this scenario, it's going to be the file group 2025.
21:39:54
여기에는 파일이 하나만 있습니다. 따라서 올바른 데이터 파일로도 갈 수 있습니다. 이 파일에서.
And we have here only one file. So it can as well go to the correct data file. And in this file.
21:40:00
SQL이 이 행을 저장할 것이므로 꽤 쉽습니다.
the sql gonna store this row so it is pretty easy
21:40:07
이제 우리는 매우 중요한 부분에 도달했습니다. 우리가 이해할 것입니다.
and now we come to a very important part where we're gonna understand how
21:40:10
파티션이 내 쿼리의 성능을 정말로 향상시키고 있습니다.
the partitions are really improving the performance of my query
21:40:13
물론 우리는 실행 계획을 확인하여 이를 수행할 수 있습니다.
and of course we can do that by checking the execution plan
21:40:16
이제 파티션이 있는 것과 없는 것의 동작을 비교하기 위해서.
so now in order to compare like the behavior with and without
21:40:20
파티션 없이 미러 테이블을 생성해야 합니다.
the partition what we have to do is to create a mirror table without
21:40:23
여기에서 파티션된 테이블이 있습니다. 제가 할 일은 여기에 가서 'INTO'라고 말하고, 'sales_orders_no_partition'이라고 부를 것입니다.
partition so we have our table here the partitioned one what What I'm just going to do, I will go over here and say into and we're going to call it sales orders underscore no partition.
21:40:35
주문 파티션에서 데이터와 구조를 가져오고, 물론 파티션되지 않을 것입니다.
So we are taking the data and the structure from the orders partitions and of course it will not be partitioned.
21:40:41
이제 실행해봅시다. 여기로 가면 두 개의 테이블이 있습니다.
So let's go and execute it. Now if you go over here, we can see that we have two tables.
21:40:47
파티션이 없는 것과 파티션된 것입니다. 이제 우리가 할 일은 두 테이블에 대해 쿼리를 작성하고 실행 계획을 비교하는 것입니다.
We have the no partition and the partitioned one. So now what we're going to do, we're going to write a query on both tables and then compare the execution plan.
21:40:54
먼저, 파티션이 없는 것부터 시작합시다. 이제 파티션의 효과를 보기 위해서, 우리는 '주문 날짜가 같다'고 말할 것입니다.
So first, let's start with the no partition. So from and now in order to see the effect of the partition, what we can do, we're going to say where order dates equal to.
21:41:05
이제 2026년 1월 1일과 같은 값을 선택하겠습니다. 그래서 쿼리를 실행해 보겠습니다.
And now we're just going to pick a value like 2026, the first of January. So let's go and query it.
21:41:10
새로운 쿼리를 실행할 건데, 이번에는 파티션에 대해 할 것입니다.
And we're going to do the same thing, a new query, but this time for the partitions.
21:41:15
실행 계획을 보려면 활성화해야 합니다.
So now in order to see the execution plan, make sure to activate it.
21:41:22
여기 액션 바로 가서 실제 실행 계획을 포함하겠다고 말하겠습니다. 클릭하고 실행해 보겠습니다.
So we go to the action bar over here and we're going to say include the actual execution plan. So let's click on it and execute.
21:41:28
이제 실행 계획이 나왔습니다. 파티션이 없는 경우도 같은 작업을 해보겠습니다. 실행해 보겠습니다.
And with that, we have here an execution plan. And let's do the same thing for the no partitions. So execute.
21:41:35
여기 실행 계획이 있습니다. 실행 계획에서 무엇이 있는지 확인해 보겠습니다. 여기 하나에 집중하겠습니다.
And we have here execution plan. So now let's check what do we have in execution plan. We're going to focus on this one over here.
21:41:40
여기 실행 계획이 있습니다. 실행 계획에서 무엇이 있는지 확인해 보겠습니다. 여기 하나에 집중하겠습니다.
So right click on it and then go to properties. And now we can see a lot of details about the execution plan.
21:41:46
흥미로운 점은 행의 수입니다. 보시다시피, 우리는 네 개의 행을 읽고 있습니다.
But what is interesting is the number of rows. So as you can see, we are reading four rows.
21:41:51
전체 테이블을 의미하며, 물론 여기 CPU와
means the whole table and of course we have here the cpu and
21:41:54
다른 비용을 확인해 보겠습니다. 파티션을 확인해 보겠습니다.
the other costs now let's go and check the partition so
21:41:58
여기 클릭해 보겠습니다. 이제 여기 확인해 보시면
let's click over here so now if you check over here you can see that
21:42:01
총 행 수는 하나입니다. SQL
that total number of rows is one so sql
21:42:04
모든 네 개의 행을 읽지 않았습니다. 오직 한 행만 읽었습니다.
didn't read all four rows it reads only row
21:42:07
이 파티션에는 단 하나의 행만 있기 때문입니다.
and that's because we have in this partition only one row and
21:42:10
사용된 파티션 수는 하나입니다. 파티션을 사용하여
as you can see the number of partition that is used is as
21:42:13
파일에서 검색된 행 수를 줄였습니다.
well only one so as you can see using partition we have reduced the
21:42:16
이제 두 개의 데이터를 두 개의
number of rows that is retrieved from the files
21:42:20
다른 파티션에서 가져오고 실행 계획을 확인해 보겠습니다.
now let's go and retrieve like two data from two
21:42:23
2025년 마지막 날을 목표로 하겠습니다.
different partitions and check the execution plan so
21:42:26
이렇게 실행해 보겠습니다.
let's target 2025 the last day of the
21:42:29
다른 쿼리도 같은 방식으로 실행해 보겠습니다.
year like this so let's go and execute
21:42:32
파티션 없이 확인해 보겠습니다. 여전히
it and the same thing for the other query so
21:42:38
네 개의 행을 읽고 있지만, 다른 쪽으로 가면 실행 계획을 확인하고
let's check the without partition we still we
21:42:41
테이블을 확인해 보시면, 우리는 오직 두 개의 행만 읽고 있습니다.
are reading like four rows but now if you go to the other one if you check the execution plan and check
21:42:47
이번에는 관련된 파티션 수가
the tables can you can see we are reading only two rows
21:42:51
이번에는 관련된 파티션의 수
and this time the number of partitions that are involved
21:42:54
이 쿼리에서 두 개의 파티션이 사용됩니다. 이는 2025년과 2026년의 파티션이 있기 때문입니다.
in this query is two and that's because we have partition for
21:42:57
보시다시피, 이는 우리가 쿼리를 최적화한 노력의 가치가 있습니다.
2025 and 2026 so as you can see it's worth
21:43:00
이것은 큰 테이블에 큰 영향을 미치며, 자원과 읽기 수를 대폭 줄일 수 있습니다.
the efforts we have optimized our queries and this
21:43:03
좋습니다, 친구들. SQL의 파티션에 대한 모든 것입니다.
has a great impact on big tables the number
21:43:06
놀랍고, 데이터베이스뿐만 아니라 다른 많은 데이터 플랫폼과 도구에서도 사용할 수 있습니다.
of resources and the number of reads can be reduced massively
21:43:09
데이터를 나누어 성능을 최적화할 수 있습니다.
all right my friends so that's all about the partitions in sql it
21:43:13
이제 다음 단계로 넘어가겠습니다. 15년 동안 실제 프로젝트에서 SQL로 작업한 후
is amazing and you can use it as well not only in databases but
21:43:16
많은 모범 사례와 팁을 가지고 있습니다.
as well in many other data platforms and tools where you always
21:43:19
제가 아는 모든 것을 모아 최적화할 수 있는 모범 사례와 팁을 보여드리겠습니다.
can divide your data in order to optimize the performance now
21:43:22
이제 30개의 모범 사례에 대해 깊이 들어가기 전에, 황금 규칙을 알려드리겠습니다.
in the next step what i have prepared for you after 15 years working
21:43:26
SQL 옵티마이저는 테이블의 크기에 따라 다르게 반응합니다.
in real projects using sql i have a lot of
21:43:29
따라서 수십만 개의 작은 및 중간 테이블이 있는 경우, 모범 사례를 따르고 있다면 성능 차이를 느끼지 못할 수 있습니다.
best practices and tips for you so i have collected everything that i know and now i'm gonna show you the best practices and tips and tricks that i can give you in order to optimize the performance in sql so let's go
21:43:45
데이터의 크기가 작기 때문입니다. 그러나 백만 개 또는 수억 개의 레코드가 있는 테이블이 있다면
And now before we deep dive into the 30 best practices, I'm gonna give you the golden rule.
21:43:50
모범 사례를 따르면 성능이 얼마나 빨라질 수 있는지 즉시 알 수 있습니다.
The SQL optimizer responds differently for different sizes of tables.
21:43:54
여기서 제 황금 규칙이 있습니다. 저에게서 모범 사례를 얻거나 인터넷에서 무언가를 읽는다면
So this means if you have small and medium tables like hundreds of thousands, you might not notice any performance differences if you are following the best practices.
21:44:02
항상 실행 계획을 사용하여 테스트해야 합니다.
And that's because the size of the data is small. But if you have like a million or hundreds of millions of records in tables, you will immediately notice how things can be faster if you follow the best practices.
21:44:13
예를 들어, 두 개의 쿼리가 동일한 결과를 반환하는 경우, 실행 계획을 확인하는 것을 추천합니다.
And here is my golden rule. If you get any best practice from me or let's say you are reading something in the internet, always you have to test using the execution plan.
21:44:22
실행 계획에서 차이가 없다면, 읽기 쉽고 이해하기 쉬운 것을 선택하세요.
So for example, if you have like two queries are returning the same result of the data, I'm going to recommend you here to check the execution plan.
21:44:28
때때로 성능을 위한 모범 사례를 따를 경우, 쿼리가 조금 더 복잡해질 수 있습니다.
And if you notice there is no differences between them in the execution plan, then pick the one that you see it is easier to read and to understand.
21:44:37
항상 쿼리를 이해하기 쉽게 작성하고 느리다고 느껴질 때만 최적화하세요.
Because sometimes if we If you are following the best practices for the performance, your query might be like little bit more complicated.
21:44:43
여기서 황금 규칙은 항상 테스트하는 것입니다. 새로운 쿼리로 성능을 최적화하고 있다면 그것을 선택하세요.
So always write the query to be understandable and only optimize it if you notice it is slow.
21:44:49
성능 향상이 없다면, 쿼리를 읽기 쉽게 만드는 데 집중하세요.
So the golden rule here is always test. If you find you are optimizing the performance with the new query, then pick that.
21:44:57
항상 테스트, 테스트, 테스트하세요. 실행 계획을 사용하여 최적화할 수 있는 방법을 찾아봅시다.
And if there is no gain in the performance, then focus on making
21:45:00
좋습니다, 쉬운 것부터 시작합시다. 첫 번째 단계는 필요한 것만 선택하는 것입니다.
your queries readable so this is the golden rule always test test test using execution plan so let's deep dive into best practices and we're gonna start by optimizing the performance of our queries
21:45:16
좋습니다, 쉬운 것부터 시작합시다. 첫 번째 단계는 필요한 것만 선택하는 것입니다. 제가 보통 많은 쿼리에서 보는 것은 개발자들이 한 테이블의 모든 열을 선택하는 것입니다.
all right let's start with the easy stuff the first step is select only what you need what i What I usually see in many queries that developers just go and select all the columns from one table.
21:45:25
한 쿼리에서 한 테이블의 모든 열이 필요한 상황을 생각할 수 없다고 말씀드릴 수 있습니다.
And I can tell you I cannot think of one scenario where you need all the columns of one table in one query.
21:45:30
결과적으로 불필요한 열이 포함될 것입니다.
So for sure in the result we will get like unnecessary columns.
21:45:34
불필요한 정보를 읽는 것은 쿼리를 느리게 만들 것입니다. 그래서 이는 보통 나쁜 관행입니다.
And of course reading unnecessary information is going to make your query slower. So this is usually a bad practice.
21:45:41
별표를 사용하지 말고 대신 쿼리에 필요한 모든 열을 나열하세요.
Don't use select star but instead of that go list all the columns that you need for your query.
21:45:47
필요한 것만 선택하도록 하세요. 한 테이블의 모든 열을 선택하지 말고, 그렇게 하면 데이터베이스에서 불필요한 정보를 읽는 위험이 없습니다.
Make sure that you only select what you need, don't go and select all the columns from one table and with that you don't risk reading unnecessary information from the database.
21:45:56
항상 쿼리에 필요한 것만 정확히 선택하도록 하세요. 별표를 사용하지 마세요.
So always make sure that you select exactly what you need for a query, don't go with a star.
21:46:01
좋습니다, 두 번째 팁은 불필요한 DISTINCT와 ORDER BY를 피하는 것입니다.
Okay, tip number two, avoid unnecessary distinct and order by.
21:46:05
많은 개발자들이 많은 쿼리를 작성하면서 기본적으로 항상 DISTINCT와 ORDER BY를 추가하는 경향이 있습니다.
I have noticed that many developers as they are writing a lot of queries, they tend up by default, adding always distinct and order by for each query.
21:46:15
코드를 검토하고 개발자와 논의할 때, 쿼리에서 중복을 제거할 필요가 없다는 것을 알게 됩니다. 중복이 없기 때문입니다.
And as we review the code and discuss it with the developer, we see that we really don't need to remove any duplicates in the query because there are no duplicates and it was only a habit to remove the duplicates using distinct.
21:46:26
ORDER BY도 마찬가지입니다. 많은 상황에서 데이터를 정렬할 필요가 없습니다.
And the same thing for the order by in many situations, there is no need to sort the data at all.
21:46:30
DISTINCT로 중복을 제거하고 데이터를 정렬하는 작업은 실행 계획에서 매우 비싼 작업입니다.
And those operations that distinct removing the duplicate and sorting the data, they are very expensive operations in your execution plan.
21:46:38
그래서 많은 자원을 소모하고 쿼리를 느리게 만들 것입니다.
So they're going to take a lot of resources and slow down your query.
21:46:42
따라서 항상 DISTINCT를 사용하거나 필요하지 않은 경우 ORDER BY를 사용하는 것은 나쁜 관행으로 간주됩니다.
So this is considered as a bad practice if you always go and use distinct even though it's not needed or you are using the order by in order to sort the data when it is not necessary.
21:46:51
따라서 여기서 가장 좋은 방법은 그것들을 피하는 것입니다. 필요할 때만 DISTINCT 또는 ORDER BY를 사용하세요.
So the best practice here is to avoid them. Don't use distinct or order by only if it is necessary.
21:46:57
좋습니다, 다음은 탐색 목적으로 행 수를 제한하는 것입니다.
Okay, the next one for exploration purposes limit the rows.
21:47:01
특히 새로운 데이터베이스에서 작업할 때, 테이블을 탐색하여 내용을 빠르게 확인하고 싶을 것입니다.
So sometimes especially if you are working with a new database you would like to explore the tables just to have a quick peek in order to see the content of the tables.
21:47:10
데이터베이스에 수백만 개의 행이 있는 큰 테이블이 많다면, 이렇게 데이터를 선택하면 많은 자원을 소모하게 됩니다.
And if your database has a lot of big tables with millions of rows and so on, you will be consuming a lot of resources if you just select the data like this.
21:47:18
다른 테이블이 1억 개의 행을 가지고 있다고 상상해 보세요. 이 쿼리를 실행하면 데이터베이스는 1억 개를 모두 가져와야 합니다.
So now imagine that the others has like 100 million. As you run this query, the database has to fetch all the 100 million for you.
21:47:25
탐색을 위해서는 10개의 행만 보는 것으로 충분합니다.
And usually for exploration, it's enough to see like 10 rows and that's going to be enough.
21:47:30
그래서 테이블을 탐색할 때 제한이나 TOP이 없는 것은 나쁜 관행으로 간주됩니다.
That's why it is considered as a bad practice if you are exploring the tables to not have a limit or top.
21:47:36
좋은 방법은 SELECT TOP 10을 사용하고 같은 쿼리를 사용하는 것입니다.
So a good practice would be to say select top 10 and then have the same query.
21:47:41
여기로 가면 10개 행만 가져오고 데이터베이스는 1억 개를 담을 수 없습니다. 10개 행만 담을 수 있습니다.
So if you go over here, you will get only 10 rows and the database will not fit 100 million. It can fit only 10 rows.
21:47:48
많은 테이블을 탐색할 때 데이터베이스에서 많은 자원을 소모하지 않을 것입니다.
And now if you are exploring a lot of tables, you will not consume a lot of resource from the database.
21:47:53
항상 검색하는 행 수를 제한하세요.
So if you are exploring, always limit the number of rows that you are retrieving.
21:48:03
좋습니다. 이제 필터링 최적화에 대해 이야기하겠습니다.
all right so now we're going to talk about how to optimize the filtering
21:48:06
SQL에서 비클러스터 인덱스를 생성하는 것이 좋습니다.
in sql so the tip here is to create a non-clustered
21:48:09
자주 사용되는 열에 대한 비클러스터 인덱스를 생성해야 합니다.
index on frequently used columns in where close so
21:48:12
물론 쿼리를 확인해야 하며, 자주 필터링하는 경우
of course you have to check your queries and so on and if you see
21:48:15
주문 상태를 사용하여 데이터를 필터링하는 경우
that you are frequently filtering the data using the order
21:48:18
주문 상태에 대한 비클러스터 인덱스를 생성하는 것이 좋습니다.
status then it makes sense to create a non-clustered index for this column in order to improve the performance of your query so for this situation i'm going to go and create then
21:48:28
주문 상태에 대한 클러스터 인덱스를 생성합니다.
Ignant clustered index for the table sales order for the order status.
21:48:33
생성한 후에는 쿼리 성능이 향상됩니다.
So once you create it, then you're improving now the performance of your query.
21:48:38
다음은 WHERE 절의 열에 함수 적용을 피하는 것입니다.
Okay, the next one is avoid applying functions to columns in the where clause.
21:48:43
대부분의 경우, 데이터를 필터링하기 전에 열을 변환합니다.
So in many cases, what we usually do is that we go and transform the columns before like filtering the data.
21:48:48
예를 들어, 주문 상태에 대해 lower 함수를 적용합니다.
Like for example, here I'm applying the function lower on the order status because I'm searching for the value delivered.
21:48:55
테이블의 값이 대문자 또는 카멜 케이스인지 확실하지 않습니다.
And I'm not sure about the values in the table, whether they have like a camel case or uppercase or anything.
21:49:02
값을 찾기 위해 주문 상태를 lower로 설정합니다.
But in order to make sure that I'm going to find the value, I'm going to go and say lower the order status and then give here a lower value.
21:49:09
그리고 값이 다르기 때문에 문제가 발생합니다.
And of course, it's going to work. So if you go and search for it, and as you can see, we have here the status delivered.
21:49:14
주문 상태에 인덱스가 있지만 함수 사용 시 인덱스를 사용하지 않습니다.
And the value is different than the one I use because here we have like a capital first character. But here we have a problem.
21:49:21
따라서 전체 인덱스가 쓸모없게 됩니다.
We have an index on the order status. And now if you use any functions like for example here the lower the SQL will not use the index.
21:49:29
그래서 WHERE 절에 함수 사용은 나쁜 관행으로 간주됩니다.
So that means the whole index is now useless and the SQL is not using it.
21:49:34
좋은 관행은 함수 사용을 피하고 데이터에 있는 값을 정확히 쓰는 것입니다.
And that's why we consider it as a bad practice to use functions for the where clause.
21:49:40
그렇게 하면 SQL이 인덱스를 사용하게 됩니다. 이 규칙에 대한 또 다른 예를 보겠습니다.
And instead of that the good practice is to not use any function and to write exactly the value that is used inside your data.
21:49:47
여기서 이름이 A로 시작하는 모든 고객을 선택합니다.
And with that the SQL is going to be happy and use the index that you have created. Okay, let's have another example about this rule.
21:49:54
그렇게 하면 substring 함수를 사용할 수 있습니다.
And here we are selecting all the customers where the first name starts with the A.
21:49:58
이름의 첫 번째 문자를 가져오기 위해서입니다.
So with that we can go and use the function substring in order
21:50:01
A와 일치시키면 결과를 얻을 수 있습니다.
to get the first character of the first name and
21:50:04
이것은 이름에 인덱스가 있는 경우 좋지 않습니다.
once you match it with a then you will get the result and here we have anna
21:50:08
열에 함수를 적용하기 때문에 발생하는 문제입니다.
and this is again bad if you have an index on the first name
21:50:11
그리고 이는 우리가 열에 함수를 적용하고 있기 때문입니다.
and that's because we are applying a function on the column
21:50:14
그래서 이는 나쁜 관행으로 간주되며, 대신에 우리는 도움을 받을 수 있습니다.
so this considered to be a bad practice and instead of that we can go and use the help of the like so we can go and search for this pattern where it starts with the a and then we have a white card
21:50:25
우리는 나머지에 대해 신경 쓰지 않으므로 반드시 a로 시작해야 합니다.
we don't care about the rest so it must start with a so
21:50:28
이것을 실행하면 같은 결과를 얻을 수 있으니 시도해 보세요.
if you go and execute it you will get the same results so try
21:50:31
가능한 한 where 절에서 함수를 피하도록 하세요.
as much as you can to avoid the functions in the where clouds
21:50:34
인덱스를 작동시키기 위해서입니다.
in order to hit and get the index working and
21:50:37
많은 시나리오에서 우리는 사용하기 위한 우회 방법이 있습니다.
in many scenarios we have a workaround in order to use the
21:50:40
변환 없이 함수를 사용하도록 하세요.
function without transformations so try your best to avoid
21:50:44
열에 인덱스가 있는 경우 함수를 사용하지 마세요.
using functions if your columns having an index all
21:50:47
쿼리에서 자주 볼 수 있는 또 다른 예입니다.
right one more example that you see a lot on queries that you
21:50:51
연도로 필터링하고 있습니다.
filter by the year so we are searching for the orders that
21:50:54
2025년에 발생하는 주문을 검색하고 있습니다.
happens in 2025 and we usually go and use
21:50:57
주문 날짜에 인덱스가 있다면 이것은 작동하지 않을 것입니다.
the year order dates and now if you have an index on
21:51:00
여기서 함수를 사용하고 있기 때문입니다.
the order dates this again will not be working because you are using
21:51:03
연도 함수를 사용하는 대신에 사용할 수 있습니다.
a function here so this considered to be a bad practice
21:51:06
주문 날짜에 함수를 적용하지 않도록 하세요.
instead of using the year function you can go and use
21:51:10
우리는 주문 날짜가 경계 사이에 있다고 말합니다.
between so we don't apply a function on the order date
21:51:13
물론 이제 우리의 쿼리는 그리 멋지지 않습니다.
and we say the order date is between the boundaries
21:51:16
첫 번째와 같이 쉽지는 않지만 여전히 두 번째와 함께합니다.
of the year of course now our query is not looking really cool
21:51:19
우리는 인덱스를 타격하고 있으니 필터링할 때 다시 시도해 보세요.
and easy like the first one but still with the second
21:51:22
열에서 함수를 사용하지 않도록 하세요.
one we are hitting the index so again while you are filtering try
21:51:26
인덱스가 있고 사용하지 않는다면 정말 낭비입니다.
to not use functions on the columns because it
21:51:29
대부분의 경우 함수에 대한 우회 방법이 있습니다.
is really waste if you have an index and you are not using it and
21:51:32
이것은 제가 이 팁에 대해 보여주고 싶었던 세 가지 예입니다.
most of the cases you have like a workaround for your function so
21:51:36
좋습니다, 비슷한 것으로 넘어갑니다.
those are the three examples that i wanted to show you about this tip
21:51:39
좋습니다. 비슷한 예로 넘어가겠습니다. 선행
all right moving on to a similar one it says avoid leading
21:51:42
와일드카드는 인덱스 사용을 방해하므로 피하세요.
wild cards as they prevent index usage so
21:51:45
이와 유사한 예로, 예를 들어 제가
this is a similar one let's say say for example i'm searching for the word
21:51:48
성의 마지막 이름에 금이 있는지 검색하고 있습니다.
gold inside the last name and here we have to be careful what
21:51:52
우리가 검색하는 것이 금이 존재해야 합니다.
we are searching for should the gold exist somewhere
21:51:55
성에서 금으로 시작하는지 또는
in the last name or only we are searching for
21:51:58
금으로 시작하는 성만 검색하고 있습니다.
the last name that start with gold if it's
21:52:01
그렇다면 여기서 잘못하고 있는 것입니다. SQL에서
like that we are searching only the last name that starts with gold
21:52:04
선행 와일드카드를 사용하면 SQL이 인덱스를 사용하지 않습니다. 하지만 끝에
then we are doing it here wrong and in sql if
21:52:07
후행 와일드카드는 괜찮고 명확하므로 피하지 않을 것입니다.
you are using the leading white cards then the sql will not be using the index but if you are using the white card at the end
21:52:14
인덱스를 사용하는 것이므로 이것은 나쁜 관행으로 간주됩니다.
and the trailing this one is fine and it's clear will not avoid
21:52:17
인덱스를 잘 사용하지 않게 되기 때문입니다.
using the index so this considered as a bad practice
21:52:21
그보다 선행 와일드카드를 사용하지 않는 것이 좋습니다.
because you will not be hitting the index better
21:52:24
그것이 검색에 충분하다면, 그렇게 하면 인덱스를 사용할 수 있습니다.
than that to not use the white card as a leading and
21:52:27
다음으로 넘어가겠습니다.
if that's enough for your search then with that you are hitting
21:52:30
여러 개의 OR 대신 IN을 사용하라고 합니다.
and using the index okay moving on to the next one
21:52:34
OR 연산자는 성능에 매우 해롭습니다.
it says use in instead of multiple or
21:52:37
사용을 피하도록 하세요. 정말 성능을 저하시킵니다.
or operator is very evil for performance and
21:52:40
필터나 조인에서 사용되든지 간에, 이제 우리는
try to avoid using it it really kills your performance whether
21:52:43
고객이 1 또는 2인 주문을 보여주고자 합니다.
it is in the filters or joins and so on so now we want
21:52:46
또는 3이고, 물론 이것은 나쁜 관행으로 간주됩니다.
to show the orders where the customers is equal to one or two
21:52:49
읽기 어렵고, 그러니 그렇게 하지 마세요.
or three and of course this is considered to be a bad practice
21:52:53
대신 IN 연산자가 있습니다. 고객이
and hard to read and so on please don't do that instead
21:52:56
그 값 중 하나라면 주문을 보여줍니다.
we have the in operator and we are saying if the customer
21:52:59
그래서 실행하면 정확한 결과를 얻을 수 있습니다.
is one of those values then show the orders
21:53:02
그래서 실행하면 정확한 결과를 얻을 수 있습니다.
so if you go and run it you will get the exact results
21:53:06
그리고 첫 번째 쿼리보다 보기 좋을 뿐만 아니라 성능도 더 좋습니다. OR을 많이 작성해야 한다면 in 연산자를 고려하세요.
and it's not only looks nicer than the first query but it has as well a better performance so if you find out writing a lot of ORs, think about the in operator.
21:53:16
데이터 필터링을 위한 최선의 방법입니다.
So those are the best practices for filtering data to improve the performance.
21:53:24
이제 SQL에서 테이블 조인을 최적화하는 방법에 집중하겠습니다.
Okay, so now we're going to focus on how to optimize joining tables in SQL.
21:53:28
첫 번째 팁은 조인의 속도를 이해하고 가능할 때 inner join을 사용하는 것입니다.
So the first tip here is to understand the speed of joins and to use inner join when it's possible.
21:53:35
우리가 배운 것처럼 여러 종류의 조인이 있습니다.
Well, as we learned before, we have like different types of joins, we have the
21:53:38
inner, left, right, outer join이 있으며,
inner, left, right, and outer join and if you talk
21:53:41
성능에 대해 이야기하면 inner join에서 최고의 성능을 얻을 수 있습니다.
about the performance the best performance you will get from the inner join
21:53:44
SQL은 일치하는 행에서만 작동하기 때문입니다.
and that's because sql gonna work only on the matching rows
21:53:48
즉, 노력과 처리 시간이 더 좋습니다.
that means the effort and the processing time is better
21:53:51
다른 조인보다 이제 다음은 left와 right 조인입니다.
than the other joins now in the next one ranking
21:53:54
이들은 inner join보다 약간 느립니다.
we have the left and right joins they are slightly
21:53:57
보통 더 많은 데이터와 행을 처리하기 때문입니다.
slower than the inner join because usually they process
21:54:01
SQL은 일치하는 행뿐만 아니라
more data and more rows than the inner join
21:54:04
일치하지 않는 행도 처리하기 때문입니다.
because sql will work not only with the matching rows as
21:54:07
right와 left 조인은 inner join보다 더 많은 작업을 해야 합니다.
well with the unmatching rows so for right and left sql
21:54:10
이제 최악의 유형인 outer join이 있습니다.
has to do more stuff than the inner join and now the worst type
21:54:14
이 유형은 가장 많은 수의 행을 처리하기 때문입니다.
of joints we have the outer join and that
21:54:17
다른 유형에 비해 일치하지 않는 행을 나타낼 수 있습니다.
and that's because this type works with the biggest number of
21:54:20
왼쪽과 오른쪽 테이블에서 일치하지 않는 행을 나타낼 수 있습니다.
rows compared to the other types it can present unmatching
21:54:23
즉, SQL은 할 일이 많고 이 조인은
rows from the left and from the right tables so
21:54:26
최악의 성능을 가지고 있습니다. 그래서 제 조언은
that means sql has a lot of to do and that's why this joint
21:54:29
최악의 성능을 보이므로 여기 제 조언이 있습니다.
has the worst performance so here my advice
21:54:32
항상 일치하는 행으로 작업하기에 충분하다면 내부 조인을 사용하려고 하세요. 일치하는 행이 충분하지 않다면 왼쪽 조인을 사용해 보세요.
is always try to use the inner join if it's enough to work with the matching rows and if the matching rows is not enough then go with the left join maybe.
21:54:42
하지만 항상 왼쪽 조인 대신 내부 조인을 사용하려고 최선을 다하세요. 그러나 내부 조인이 데이터를 필터링한다는 것을 잊지 마세요.
But try your best always to bring the inner join instead of left join. But don't forget inner join filters the data.
21:54:48
좋아요, 다음은 XSplit을 사용하여 암시적 조인 대신 ANSI 조인을 사용하라고 합니다.
Okay, the next one it says use XSplit join the ANSI join instead of implicit join.
21:54:55
암시적 조인이나 비 ANSI 조인처럼 테이블을 조인하면 나쁜 관행으로 간주됩니다.
Well it is considered as a bad practice if
21:54:58
조인할 때는 일반적인 현대 조인을 사용하는 것이 좋습니다.
you join tables like this the implicit join or the non-ansi
21:55:01
예를 들어 성능에 대해 내부 조인을 사용하는 것이 좋습니다.
join it's better to use the normal modern join
21:55:04
그들 사이에는 차이가 거의 없고 이 시나리오에서는
where you use the inner join for example about the performance
21:55:08
매우 간단하지만 복잡한 쿼리가 있는 경우
there is like no differences between them and for this scenario it's
21:55:11
이렇게 테이블을 조인하는 것은 매우 혼란스러울 수 있으며
very simple but if you have like a complex query then
21:55:14
읽기가 어렵고 최적화하기도 복잡합니다.
joining table like this might be very confusing and really
21:55:17
그래서 최선의 방법은 일반 내부 조인을 사용하는 것입니다.
hard to read and as well complex to optimize that's
21:55:20
그래서 비 ANSI 대신 ANSI 조인을 사용하세요.
why the best practice says go with the normal inner join
21:55:24
좋아요, 다음 팁으로 넘어가서 인덱스를 설정하세요.
so go with the ANSI join instead of the non-ANSI
21:55:28
자신의 절에서 사용되는 열에 대해 인덱스를 설정해야 합니다.
join okay to the next tip make sure to index
21:55:31
두 열 모두 인덱스가 있는지 확인해야 합니다.
the columns used in their own clause so we have to
21:55:34
인덱스는 조회 프로세스를 빠르게 합니다.
go and make sure that both of those columns has an index
21:55:37
인덱스가 없으면 SQL이 전체 테이블 스캔을 수행할 수 있습니다.
because indexes speed up the lookup process
21:55:40
데이터베이스는 순서대로 전체 테이블을 스캔할 수 있습니다.
without an index the sql might go and do a full table scan without an index on those columns the database
21:55:46
일치하는 항목을 찾기 위해 전체 테이블을 스캔할 수 있습니다.
might go and scan the entire tables in order
21:55:50
큰 테이블이 있는 경우 정말 느립니다.
to find a match and that is really slow if you have big
21:55:53
그래서 이제 여기 고객으로 가면
tables so now if you go to the customers over here and
21:55:56
인덱스를 보면 고객 ID에 대한 클러스터형 인덱스가 있습니다.
then to the indexes we can see that we have an
21:55:59
주문에서 고객 ID를 확인하면 인덱스가 없습니다.
index a clustered index for the customer id but
21:56:02
그래서 이건 인덱스가 없습니다.
if you check the customer id in the orders we don't
21:56:06
그것을 수정하기 위해 고객 ID에 대한 비클러스터형 인덱스를 생성할 것입니다.
have an index for that so this one doesn't have an index
21:56:09
외래 키이기 때문에 그렇게 하면 이제 인덱스가 생깁니다.
so in order to fix that we're gonna go and create an unclustered index on the table orders for the customers id since it is
21:56:16
두 열 모두에 대한 인덱스가 생기고, 그로 인해 조인이
a foreign key so once we do that we have now an index
21:56:20
이 두 열에 대한 인덱스가 생겼습니다.
for both of those columns and with that our join
21:56:23
조인이 더 빨라질 것입니다.
gonna be faster okay so now we come to a tip where we
21:56:26
정말로 상황에 따라 다릅니다.
say really it depends on there is like not one
21:56:29
어떻게 할지에 대한 명확한 방법은 없습니다.
clear way on how to do it but let's see if you have a big tables
21:56:32
여기서 우리는 두 개의 테이블을 조인하고 있습니다.
it is better to filter data before joining and here we have like three different scenarios that's gonna deliver the same results but of course the question is which one is the best for performance so now let's have a look to them.
21:56:44
주문 상태에 따라 결과를 필터링하고 있습니다.
What we are doing here, we are just joining two tables and then we are filtering the result based on the order status that comes from the orders.
21:56:52
테이블을 조인한 후 데이터를 필터링하고 있습니다.
So in the first query, what we are doing, we are first joining tables and at the end, we are using where clause in order to filter the data.
21:56:59
조인 조건에서 주문 상태를 추가할 수 있습니다.
So by looking to this, we are just filtering the data after joining the tables. But there is another way on how to do it.
21:57:05
고객 ID로 데이터를 매칭하고 있습니다.
You can go and join the tables, but on the join condition, you can go and add this order status equals to delivered.
21:57:12
조인 중에 필터링이 발생합니다.
So we are matching the data by the customer ID and at the same time we are filtering the data by the order status since we are using the inner join.
21:57:20
먼저 주문 테이블을 준비합니다.
So the filtering is happening during the join or you can do it like this where we have here more stuff to be added where we don't join the table directly with the orders.
21:57:29
필요한 열을 선택하고 데이터를 필터링합니다.
We first prepare the table orders before joining it with the customers.
21:57:34
모든 쿼리를 실행하면 동일한 결과를 얻습니다.
And here our preparation is we are just selecting the columns that we need and we are already filtering the data before doing the join using the subquery.
21:57:44
서브쿼리 없이 데이터를 준비할 수 있습니다.
But if you run all those queries, you will get the exact same results. And of course, there is another way on how to do it.
21:57:49
쿼리가 작고 복잡하지 않다면,
You can go and prepare the data, not in subquery. You can go and use a CTE and then join the result of the CTE with the table customers.
21:57:58
모든 세 쿼리는 동일한 성능을 제공합니다.
So now about the performance, if your query is like small, not that complex,
21:58:03
조인 후 필터링하는 것이 이상하게 들릴 수 있습니다.
and as well, you don't have a big data inside your tables, All those three queries can deliver the same performance.
21:58:09
SQL 최적화기가 매우 똑똑합니다.
I know it's mine sounds weird because here we are like filtering after joining or here we are filtering during the join.
21:58:17
여기 필터가 있다는 것을 이해할 수 있습니다.
Normally in databases, the SQL optimizers are now very smart.
21:58:20
필터를 어디에 두든 SQL은 올바르게 처리합니다.
You can understand that there is a filter here and decide on the best execution plan for you.
21:58:26
복잡한 쿼리가 없다면 적합한 것을 선택하세요.
So actually, wherever you put your filter after, during or before, the SQL is smart enough to do it correctly.
21:58:33
첫 번째 방법을 추천합니다.
So if you don't have complex query and you don't have like big tables, go with the one that suits you.
21:58:38
큰 테이블과 복잡한 쿼리가 있다면,
And I really recommend you to go with the first one because it's logical and easier to understand.
21:58:43
서브쿼리나 CTE에서 데이터를 준비하세요.
But if you have big tables and complex queries, the best practice says try always to prepare the data before joining it.
21:58:51
데이터를 준비하면 실행 계획이 더 나아집니다.
So try to isolate and abstract the pre-step in a subquery or in a CTE before joining it with any other tables.
21:58:59
내 프로젝트에서 큰 테이블이 있는 많은 시나리오에서, 데이터를 조인하기 전에 분리하고 준비하면 실행 계획이 더 나아졌습니다.
And in many scenarios in my project where I have a big table, this did help where the execution plan was better if I isolate and prepare the data before joining it.
21:59:07
작거나 중간 크기의 테이블이 있다면, 일반적인 방법을 사용하세요. WHERE 절을 사용하세요.
So if you have small or medium tables, go with the normal way. Use the where clause.
21:59:12
복잡한 큰 테이블이 있다면, 서브쿼리나 CTE에서 데이터를 준비한 후 테이블과 조인하세요.
But if you have complex big tables, prepare the data in subquery or CTE and then join it with the tables.
21:59:19
이제 테이블 번호 12로 넘어갑니다. 이전 것과 비슷하지만, 이번에는 테이블을 조인하기 전에 데이터를 집계하라고 합니다.
OK, now moving on to table number 12. It is similar to the previous one, but this time it says aggregate data before joining tables.
21:59:28
다시 말해, 큰 테이블의 성능을 개선하기 위한 특별한 경우입니다.
And again, it is a special case to improve the performance of big tables.
21:59:31
이제 우리는 주문과 고객을 조인하는 다음 시나리오를 가지고 있습니다. 고객 ID로 데이터를 집계하고 있습니다.
So now we have the following scenario where we are joining the orders and the customers. And we are aggregating the data by the customer ID.
21:59:39
우리는 단지 고객 테이블을 조인하고 있습니다. 왜냐하면 이름이 필요하기 때문입니다.
But we are just joining the table customers because we need the first name.
21:59:43
결과적으로 고객 ID, 이름 및 주문 수를 갖게 됩니다.
So as a result, we have the customer ID, the first name and the order count.
21:59:47
표준 방법은 테이블을 조인한 후 데이터를 요약하기 위해 GROUP BY를 사용하는 것입니다.
So the standard way is to join the tables and then do a group by in order to summarize the data.
21:59:52
이 쿼리를 보면, 실제로 집계를 위해 조인이 필요하지 않습니다.
Now, if you look to this query, we actually don't need to join in order to do the aggregations.
21:59:57
첫 번째 집계를 수행할 수 있습니다.
we can do first aggregation
22:00:00
집계된 데이터로 주문을 준비한 후, 결과를 고객과 조인하여 이름을 얻습니다.
like preparing the orders with the aggregated data and then join the result with the customers in order to get the first name.
22:00:08
다시 말해, 먼저 준비한 후 조인을 수행합니다. 서브쿼리나 CTE를 사용하여 이를 수행할 수 있습니다.
So again, we prepare first and then we do the join. And we can do that using either the subqueries or using the CTE.
22:00:15
이 시나리오에서는 먼저 GROUP BY를 수행하고 데이터를 집계합니다.
So in this scenario, first, we are doing the group by, we are aggregating the data.
22:00:19
이 결과는 고객 테이블과 조인되어 이름을 얻습니다. 물론 이를 수행하는 방법은 여러 가지가 있습니다.
And the result of this is joined with the customers tables in order to get the first name. Now, of course, there are like many ways on how to do it.
22:00:26
예를 들어, 상관 쿼리를 사용하여 SELECT 문에서 서브쿼리를 사용하고, 여기서 WHERE 조건을 사용하여 상관 쿼리를 만들 수 있습니다.
like for example as well using the correlated queries where we can go and use the subquery in the select statements and then use the where condition over here to make the correlated query.
22:00:37
세 가지 방법이 동일한 결과를 제공할 수 있지만, 어떤 방법이 가장 성능이 좋은지는 다시 질문입니다.
Now although three can deliver the same results but the question here again which one has the best performance.
22:00:42
상관 서브쿼리는 가장 성능이 나쁜 방법이라고 즉시 말씀드릴 수 있습니다.
Well I can go immediately and tell you that correlated subqueries are the worst one.
22:00:48
상관 서브쿼리를 사용하는 것은 항상 피하세요. 성능이 정말 나쁩니다.
Always avoid using correlated subqueries they have really bad performance.
22:00:53
SQL은 각 고객에 대해 개별적으로 집계를 수행하기 때문입니다.
And that's because SQL going to go and do the aggregations for each customer individually.
22:00:59
각 행에 대해 집계를 수행한 후 다음 행으로 넘어가므로 시간이 많이 걸립니다.
So it's going to go like for each row and doing aggregation, then to the next row and so on. So it takes a long time.
22:01:05
이것은 나쁜 관행입니다. 사용하지 마세요. 이제 첫 번째 옵션과 두 번째 옵션이 남았습니다.
So this is bad practices. Don't use it. Now we are left again with the first option and the second option.
22:01:11
여기서 제 팁은 이전 것과 같을 것입니다. 작은 또는 중간 크기의 테이블이 있다면 이 방법을 사용하세요.
And here my tip going to be like the previous one. I'm going to say if you have small to medium size of tables, then go with this one because
22:01:19
읽기 쉽고 이해하기 쉬우며, 같은 성능을 얻을 수 있습니다.
it is easier to read and to understand and you will gain
22:01:22
이 서브쿼리와 정확히 동일한 성능을 얻을 수 있습니다.
exactly the same performance as this sub query
22:01:25
하지만 테이블이 크면 최선의 방법은
but if your tables are big the best practices is
22:01:29
먼저 데이터를 준비하여 데이터를 위로 올리는 것입니다
to prepare first the data to go above the data to
22:01:32
데이터를 필터링하고 서브 쿼리로 격리하는 것입니다
filter the data and to isolate it in a sub query
22:01:35
또는 최종 쿼리와 조인하기 전에 CTE를 사용하는 것입니다
or a cte before joining it with the final
22:01:38
최종 쿼리에서 테이블을 조인하기 전에
table in the final query but again here only for
22:01:41
대규모 테이블에 대해 항상 실행 계획을 테스트하여
big tables and always test check the execution plan whether
22:01:44
정말로 이점이 있는지 확인하십시오. 그렇다면
you are really getting any benefits from it all right so if you have
22:01:47
대규모 테이블을 먼저 CTE 서브쿼리로 준비하십시오
big tables try to prepare the data first in cte subquery
22:01:51
그런 다음 조인합니다. 다음 팁으로 넘어가면
and then join okay moving on to the next tip it says
22:01:54
조인에서 OR 연산자 대신 UNION을 사용하세요
use union instead of our operator in
22:01:57
조인에서 이 의미는 때때로 고객과 주문이라는 두 테이블을 조인할 때
joins so what this means sometimes let's say that you are
22:02:00
조인 키에 대해 여기에서 고객이
joining two tables the customers and the orders and now about
22:02:04
ID는 주문의 고객 ID와 같아야 합니다
the join key you can see over here it says the customer
22:02:07
고객 ID는 판매원의 ID와 같아야 합니다
id should be equal to the customer id from the orders or
22:02:10
이 두 조건 중 하나가 충족되면
the customer id should be equal to the sales person's id
22:02:14
일치하게 되고 OR 연산자에 대해 말씀드릴 수 있습니다
if one of these two conditions is fulfilled then we
22:02:17
여기에서 성능 저하가 발생하며 성능이 매우 나쁩니다
have a match and i can tell you the or operator over
22:02:20
그러므로 피하십시오. 조인에서 OR을 사용하지 마세요
here is a performance killer it has really bad performance
22:02:24
조인에서 인덱스를 피하는 것과 같은 많은 문제가 발생합니다
so try to avoid it don't use or in the
22:02:27
루프 조인을 생성하고 등등
joins it has a lot of problems like it avoid indexes
22:02:30
그래서 우리는 이것을 나쁜 관행으로 간주합니다
it create like loop joins and so on
22:02:33
같은 결과를 얻기 위해 조인을 나눌 수 있습니다
that's why we consider it as a bad practice and
22:02:36
조인을 나누어 고객 ID를 기반으로 데이터를 조인하는 첫 번째 쿼리와
now in order to get the same results we can go and
22:02:39
판매원을 기반으로 하는 두 번째 쿼리를 가질 수 있습니다
split the joins so we can go and have two queries the The first query is joining the data based on the customer ID and the second query based on the sales person.
22:02:49
그런 다음 UNION을 사용하여 두 결과를 병합합니다.
And then we go and merge those two results using the union.
22:02:52
SQL에 비해 더 크고 복잡하게 들리지만, 이를 사용하면 단순한 OR 연산자를 사용하는 것보다 더 나은 성능을 얻을 수 있습니다.
It sounds like bigger and too much for the SQL, but with this you will get better performance than using this simple or operator.
22:03:02
다시 말하지만, 큰 테이블이 있다면 OR 사용을 피하고 대신 UNION을 사용하세요.
So again, if you have big tables, try to avoid using or and instead of that, go and use the union.
22:03:08
다음 단계는 중첩 루프를 확인하고 SQL 힌트를 사용하는 것입니다.
The next step says check for nested loops and use SQL hints.
22:03:12
이제 큰 테이블이 있고 테이블을 조인한다고 상상해 보세요.
Now imagine that we have like big tables and we are joining tables.
22:03:16
따라서 실행 계획을 확인할 때 항상 조인 유형을 확인해야 합니다.
So now if you are checking the execution plan, you have to check always the join type.
22:03:21
예를 들어 여기서는 중첩 루프를 사용하고 있는데, 이는 작은 테이블이 있기 때문에 괜찮습니다.
So for example here it is using the nested loops, which is of course is okay because we have small tables.
22:03:27
하지만 큰 테이블이 있고 SQL이 어떤 이유로 중첩 루프를 사용하고 있다면, 이는 경고 신호입니다.
But if you have big tables and still SQL is using for some reason, the nested loops, then this is alerting.
22:03:33
이것을 변경하기 위해 우리가 할 수 있는 것은 SQL 힌트를 사용하여 해시 조인을 강제로 사용하게 하는 것입니다.
So in order to change this, what we can do, we can go and use the SQL hints in order to order to force SQL to use the hash join.
22:03:41
해시 조인은 큰 테이블과 작은 테이블이 조인될 때 정말 좋습니다.
Hash join is really good if you have a big table like for example the orders that is joins with a small table like the customers.
22:03:48
따라서 마지막에 여기에서 옵션 해시 조인을 작성할 수 있습니다.
So now what we can do at the end we can write over here option hash join.
22:03:52
이제 실행해보고 실행 계획을 확인해 보겠습니다. 이렇게 하면 SQL이 해시 조인 또는 해시 매치를 사용하도록 강제했습니다.
So let's go and execute it and let's check the execution plan and with that we have forced SQL to use the hash join or hash match.
22:04:00
다시 말하지만, 테이블을 평가해야 합니다. 작은 테이블이 있다면 신경 쓰지 마세요.
Again you have here really to evaluate your tables. If you have like small tables don't bother with that.
22:04:06
하지만 큰 테이블이 있고 SQL이 여전히 중첩 루프를 사용하고 있다면, 중첩 루프는 보통 매우 느립니다.
But if you have big tables and SQL still doing the nested loops, nested loops are usually very slow because you have a lot of iterations and so on.
22:04:14
해시 조인에서는 작은 테이블이 메모리에 저장되고 두 테이블 간의 빠른 매칭이 이루어집니다.
And with the hash join, that small table is going to be stored in the memory. And then you have really a quick matching between the two tables.
22:04:22
따라서 SQL에서 테이블을 조인하는 최적화 방법에 대한 모든 모범 사례와 팁입니다.
So those are all the best practices and tips on how to optimize joining tables in SQL. All right.
22:04:27
이제 UNION에 대해 이야기할 것이며, 여기에는 모범 사례가 있습니다.
So now we're going to talk about union and here is the best practices. It says use union all instead of using union if duplicates are acceptable.
22:04:35
중복이 허용된다면 UNION 대신 UNION ALL을 사용하세요.
So it's very simple. If the duplicates are acceptable or let's say that there is no duplicates, then don't go with the union because it needs more time to be executed.
22:04:45
매우 간단합니다. 중복이 허용되거나 중복이 없다면 UNION을 사용하지 마세요.
SQL has to go and check row by row whether we have duplicates or not.
22:04:49
SQL은 중복이 있는지 여부를 한 행씩 확인해야 합니다.
And this usually takes longer time than using the union all.
22:04:53
이것은 보통 UNION ALL을 사용하는 것보다 더 오랜 시간이 걸립니다.
So if duplicates are acceptable or you don't have any duplicates in your data, go with the union all.
22:04:58
중복이 허용되거나 데이터에 중복이 없다면 UNION ALL을 사용하세요.
SQL just have to go and merge all the data without checking
22:05:02
SQL은 중복 확인 없이 모든 데이터를 병합해야 합니다.
anything and the performance is going to be faster all right the next
22:05:05
이렇게 하면 성능이 더 빨라질 것입니다.
one is a little bit tricky so it says use union
22:05:08
하나는 조금 까다롭습니다. UNION을 사용하라고 합니다.
all together with the distinct instead of using union
22:05:11
중복이 허용되지 않는 경우 중복을 제거하고 싶다면.
if the duplicates are not acceptable so you want to remove
22:05:15
중복을 제거하기 위해 우리는 합집합을 사용할 것입니다.
the duplicates so we have learned that in order to do that we're going to go and use the union it's going to go and merge the data and as well remove the duplicates which is really okay
22:05:24
작거나 중간 크기의 데이터에 사용할 수 있습니다.
to use it if you have like smaller data or medium but
22:05:27
수백만 개의 행이 있다고 가정해 보겠습니다.
let's say that you have like millions of rows which is really
22:05:30
중간 및 작은 테이블에는 괜찮습니다.
okay if you have like medium and small tables but again here
22:05:33
거대한 테이블이 있다면
if you have huge tables big tables hundreds of millions
22:05:36
최선의 방법은 모든 합집합을 사용하는 것입니다.
the best practice says go with the union all
22:05:39
그 후에 DISTINCT를 사용합니다.
and afterwards use a distinct so
22:05:43
서브 쿼리에서 모든 합집합을 사용하고
in the sub query we are using union all but in order to
22:05:46
중복을 제거하기 위해 DISTINCT를 사용합니다.
remove the duplicates we use the distincts but again
22:05:49
실행 계획을 확인하기 위해 테스트해야 합니다.
here you have to test it to check the execution plan if you
22:05:52
이점이 있다면 이 버전을 사용하세요.
are getting benefit then go with this version but if
22:05:55
데이터가 크지 않다면 일반 합집합을 사용하세요.
your data is not really big you have hundreds of thousands so go
22:05:58
코드는 더 작고 동일한 효과를 얻을 수 있습니다.
just with the normal union the code is smaller and
22:06:02
대형 테이블에 대해서만 이 최선의 방법을 사용할 수 있습니다.
you will get the same effects but only for large tables you can go
22:06:05
합집합으로 가세요.
with this best practice so that's all what i have for you for
22:06:08
연합 괜찮아
the union okay
22:06:13
자, 이제 집계에 대해 이야기해봅시다. 여기 팁이 있습니다.
so now let's talk about aggregations and here the tip says
22:06:16
집계를 위해 열 스타 인덱스를 사용하세요.
use column star index for aggregations on
22:06:19
예를 들어, 사실 테이블과 같은 큰 테이블에 대해 그렇습니다. 그 이유는
large tables like for example fact tables and that's because
22:06:23
열 스타 인덱스가 데이터를 압축하기 때문에 데이터의 크기가
column star index gonna compress the data so the size
22:06:26
작아지고 집계도 매우
of the data gonna be smaller and as well the aggregation is super
22:06:29
빠릅니다. 왜냐하면 우리는 관련된 것만 선택하고 있기 때문입니다.
fast because we are selecting only the relevant
22:06:32
관련 정보, 즉 관련 열만 선택하므로
informations only the relevant columns so it makes it
22:06:36
대규모 테이블을 집계하는 데 완벽한 설정이 됩니다.
a perfect setup for aggregating large tables and
22:06:39
이제 수억 개의 주문이 있다고 가정하고, 여기 이 쿼리가 있습니다. 최선의 방법은 변환하라고 합니다.
now let's say that we have hundreds of millions of orders and we have this query over here so the best practice says convert
22:06:45
이 테이블을 클러스터형 열 저장소 인덱스로 변환합니다
this table to a clustered column store index
22:06:48
클러스터형 인덱스를 생성하면
so if you go and create this clustered index over
22:06:51
전체 테이블이 놀라운 성능을 발휘할 수 있습니다
here the whole table can have amazing performance
22:06:54
이런 집계를 위해서입니다. 자, 다음은
for aggregations like this all right so to
22:06:57
사전 집계 데이터를 저장하고
the next one it says pre-aggregate data and
22:07:00
보고를 위해 새로운 테이블에 저장한다고 가정해봅시다
store it in a new table for reporting so let's say
22:07:04
우리가 데이터 집계를 수행하는 큰 쿼리가 있다고 가정해봅시다
that we have like a big query where we are aggregating data
22:07:07
이 쿼리는 정말 오랜 시간이 걸립니다. 예를 들어
and so on and this query takes really long time let's
22:07:10
5분 정도 걸린다고 가정해봅시다. 하지만 이제 문제는
say like five minutes or something like that but now the problem with
22:07:13
결과를 보고서로 보여주고 싶다는 것입니다
that i would like to show the results as a report maybe
22:07:16
내 매니저에게 또는 회의 중에 보여주고 싶다면
to my manager or let's say during a meeting it's going to be
22:07:19
모두가 쿼리가 완료될 때까지 기다려야 한다면 정말 안 좋습니다
really bad if everyone have to wait until the
22:07:22
쿼리가 완료될 때까지 기다려야 한다면 최선의 방법은
query is done so the best practice here if you have like
22:07:26
매우 느린 쿼리가 있을 때 할 수 있는 일은
a query that runs very slow what you can do you
22:07:29
결과를 테이블에 저장하는 것입니다
can go and store the results in a table so
22:07:32
여기에서 판매 요약으로 이동한다고 가정해봅시다
if i go over here and say into sales summary
22:07:35
결과를 이 테이블에 저장할 수 있습니다
what can happen is gonna store the result inside this
22:07:39
이제 실행해보겠습니다. 그렇게 하면
table so let's go and execute it and now with that we have
22:07:42
모든 것이 준비된 멋진 테이블이 생깁니다. 이제 해야 할 일은
a nice table where everything is prepared so all which you have to do is
22:07:45
이 테이블을 쿼리하는 것입니다. 물론
to go and query this table and of course it's
22:07:48
선택문만 있기 때문에 매우 빠를 것입니다
going to be very fast because it's only select statements and
22:07:51
그렇게 하면 데이터를 준비하고 사전 집계한 것입니다
with that you have like prepared and pre-aggregated the data
22:07:54
빠른 보고서를 얻기 위해서입니다. 그러니 잊지 마세요
to have like fast reports so don't
22:07:57
큰 쿼리가 있을 때 이 쿼리의 결과를 새로운 테이블에 삽입할 수 있습니다
forget about this if you have a big query you can insert the
22:08:00
보고를 위해 나중에 사용할 수 있도록
result of this query in a new table in order later to use
22:08:04
보고를 위해 이 테이블을 사용해야 하지만, 반드시 확인해야 할 한 가지가 있습니다.
it for reporting but one thing that you have to make sure that you
22:08:07
항상 이 테이블을 업데이트해야 하므로, 새로운 주문이 있으면
have always to update this table so if we
22:08:10
판매 요약에 표시되지 않을 것입니다. 새로운 데이터를 얻기 위해 다시 이 쿼리를 실행해야 합니다.
have new orders it will not be presented inside the sales summary
22:08:13
이제 여기에서 무슨 일이 일어나고 있는지 보여드리겠습니다. 미국 고객의 주문만 보여드리겠습니다.
you have to go and run this query again in order to get new data inside the sales summary so those are the tips on how to improve the performance of your aggregations in your scale
22:08:28
여기에서 이 쿼리를 확인하면 주문과 고객 테이블을 조인하고 있습니다.
so now what is happening here i would like to show the orders but only from customers from usa
22:08:34
주로 주문 정보만 표시하고 있습니다.
so if you check this query over here we are joining the tables order and customers
22:08:38
즉, 고객을 필터링하는 데만 사용하고 있습니다.
but mainly we are showing only the orders information and
22:08:42
주문 테이블을 필터링하는 데 고객을 사용하고 있습니다.
that means we are using the customers only to filter the
22:08:45
이 작업을 수행하는 방법은 여러 가지가 있습니다. 조인만이 아닙니다.
table orders and there are like multiple ways on how to
22:08:48
이 작업을 수행하는 방법은 여러 가지가 있습니다. exists를 서브 쿼리로 사용할 수 있습니다.
do this task so it's not only the joins you can go
22:08:51
서브 쿼리에서 in 연산자를 사용할 수도 있습니다. 이제 오래된 질문이 돌아왔습니다.
and use the exists as a sub query and
22:08:54
어떤 것이 더 나은지 조인할까요, exist를 사용할까요, 아니면 in을 사용할까요?
as well you can go and use the in operator in the sub query and now comes the old but gold question which one is better Should we join or use exist or in?
22:09:06
오, 신이시여, 포럼에 가면 어떤 것이 가장 좋은지에 대해 사람들이 싸우는 것을 볼 수 있습니다.
And oh my god, if you go to the forums, you will see people fighting about which one is the best.
22:09:12
이제
Now about
22:09:27
모범 사례에 대해, 모두가 in 연산자를 사용하지 말라고 동의합니다. 이것이 나쁜 관행입니다.
the best practices, everyone agrees that don't go and use the in operator. So this is the bad practice.
22:09:35
그래서 나쁜 관행입니다. 피하세요. 사용하지 마세요.
So bad practice. Avoid it. Don't use it.
22:09:38
물론, 저는 항상 큰 테이블에 대해 이야기하고 있습니다, 알겠죠? 작은 테이블이 아닙니다.
And of course, I'm always speaking about big tables, okay? Not small tables.
22:09:43
그래서 우리는 다른 테이블의 결과를 기반으로 한 테이블을 필터링하기 위해 이것을 사용하지 않습니다.
So we don't go and use this in order to filter one table based on the result of another table.
22:09:49
따라서 이 시나리오에서는 연산자를 사용하지 마세요. 이제 충돌이 발생합니다. 우리는 조인과 존재가 있습니다.
So don't use an operator in this scenario. Now here comes the conflicts. We have join and exist.
22:09:56
이 두 가지의 성능에 대해 말하자면, 그들은
Well about the performance of those two, they are
22:09:59
제가 이야기하는 중간 테이블에 대해 매우 유사합니다.
very similar for medium tables like i'm speaking about
22:10:02
백 또는 천 등등이지만 여전히 테스트해야 합니다.
hundred or thousand and so on but still you have to test it
22:10:05
실행 계획을 비교해야 하고 만약
you have to go and compare the execution plans and if
22:10:08
동일한 결과를 얻고 두 가지 모두 같은 속도를 가진다면 저는 조인을 선호합니다. 솔직히 말해서 존재하는 것보다 쓰기가 더 쉽기 때문입니다.
you are getting like identical results and both of them are having the same speed then i prefer to go with the join and that's because to be honest it is easier to write the writing that exists.
22:10:21
그래서 제 관점에서 성능이 존재와 같다면 이것이 모범 사례라고 말하겠습니다.
So I'm gonna say from my point of view this is best practice if the performance equal to exists.
22:10:30
하지만 지금 저에게 일어나는 것은 때때로 exists를 사용하여 더 나은 성능을 얻는 것입니다.
But now what happens for me is that sometimes I get better performance using exists.
22:10:36
그래서 저는 제 관점에서 여기서 최선의 방법이라고 말할 것입니다.
So I'm gonna say from my point of view the best practice here.
22:10:40
그리고 이제 당신은 왜 exists를 사용하여 inner join보다 더 나은 성능을 얻는지 물어볼 수 있습니다.
And now you might ask why we are getting with the exist better performance than in the inner join.
22:10:46
그것은 SQL이 서브 쿼리에서 데이터의 존재만 확인하면 되기 때문입니다.
And that's because SQL SQL has only to check the existence of data from the sub query.
22:10:51
하지만 반면에 inner join을 사용하면 SQL이 두 테이블 간의 일치를 시작해야 합니다.
But in the other hand, with the inner join, SQL has to go and start doing matching between two tables.
22:10:56
그래서 모든 일치하는 레코드를 평가하게 됩니다. 존재 여부를 평가하는 것이 아닙니다.
So it's going to go and evaluate all matching records and so on. It is not evaluating whether it exists or not.
22:11:04
그리고 때때로 SQL은 테이블을 조인할 때 중복을 도입할 수 있기 때문에 더 많은 행을 처리해야 합니다.
And as well, sometimes SQL has to deal with more rows because you might introduce duplicates as you are joining tables.
22:11:10
이것은 exists를 사용하면 발생하지 않을 것입니다. 따라서 특정 시나리오에서는 exists를 사용하면 join을 사용하는 것보다 더 나은 성능을 얻을 수 있습니다.
And this will not happen using exists. So for some scenarios, if you are using exist, you might get better performance than using join.
22:11:19
하지만 모두가 연산자를 사용하지 말자고 동의합니다. 자, 다음 팁은 쿼리에서 중복 논리를 피하는 것입니다.
But everyone agrees to not use the operator. Okay, the next tip is to avoid redundant logic in your query.
22:11:26
이것은 많은 서브 쿼리가 있을 경우 자주 발생합니다. 분석해보면 때때로 중복이 있다는 것을 알 수 있습니다.
This happens a lot if you have a lot of sub queries. And if you analyze it, you might find sometimes there are like redundancy.
22:11:33
예를 들어, 이 쿼리에서는 각 직원에 대해 급여가 평균 이상인지 이하인지 태그를 달고 싶습니다.
So for example, this query, I would like to have like a tag for each employee, whether the salary is above the average or below the average.
22:11:41
그래서 이제 우리는 이렇게 할 수 있습니다. 자, 평균보다 급여가 높은 직원의 데이터를 가져오자고 말합니다.
So now we might do it like this. We say, okay, let's get the data for employees where the salary is higher than the average.
22:11:48
그리고 서브 쿼리에서 평균을 계산합니다. 그래서 여기서 평균보다 높으면 평균 이상이라고 적습니다.
And you go and calculate the average in a sub query. So if it's higher than you right here above average.
22:11:53
그리고 이제 우리는 평균 이하로 가자고 말합니다. 그래서 union all을 하고 그 조건은 급여가 평균보다 적어야 합니다.
And now we say, okay, let's go for the below average. So we do a union all and that condition is going to be salary is less than the average.
22:12:01
그리고 이것을 확인하면 문제가 있다는 것을 알 수 있습니다. 우선, 우리는 직원들을 네 번 쿼리하고 있습니다.
And now by checking this, you see that there is a problem. First of all, we are querying the employees like four times.
22:12:07
하나, 둘, 셋, 넷이 있습니다. 그래서 우리는 직원 테이블을 네 번 스캔하고 있습니다.
We have one, two, three, four. So we are scanning the table employees four times.
22:12:13
그리고 여기에서도 같은 논리가 있습니다. 그래서 우리는 급여의 평균을 두 번 계산하고 있습니다.
And as well, we have the same logic over here. So we are calculating the average of salary twice.
22:12:19
그래서 이것은 물론 나쁜 관행이라고 말할 수 있습니다. 그리고 더 나은 방법이 많이 있습니다.
So this is, of course, I can say a bad practice. And there is like many ways on how to do it better than that.
22:12:25
예를 들어, 이 서브쿼리를 SETE에 넣고 여러 번 사용할 수 있습니다. 하지만 윈도우 함수를 사용하면 더 나은 해결책이 있습니다.
For example, you can go and put this subquery in SETE and then use it multiple times. But there is like better solution using the window function.
22:12:32
그래서 이것을 확인하면 매우 간단합니다. 우리는 직원 테이블을 한 번만 읽고 있습니다.
So if you check this, it is very simple. It's me executed. We are reading the table employees only once.
22:12:38
그리고 우리는 case 문을 사용하고 있습니다. 급여가 윈도우 함수보다 높으면.
And then we are using the case statements. If the salary is higher than the window function.
22:12:43
그래서 우리는 전체 직원 테이블 위에 평균을 계산하고 있습니다.
So we are calculating the average on top of the whole table employees.
22:12:47
급여가 평균 이상이면 평균 이상, 평균 이하이면 평균 이하입니다. 그래서 보시다시피 읽기가 더 쉽고 작습니다.
If it's higher than right above average, if it's lower than below average. So as you can see, it is easier to read and it is smaller.
22:12:54
그리고 여기서 성능은 직원들을 네 번 읽고 같은 논리를 반복하는 것보다 훨씬 좋습니다.
And the performance here is way better than reading four times the employees and repeating the same logic.
22:12:59
그래서 항상 쿼리를 살펴봐야 합니다. 같은 것을 반복하고 있다면 나쁜 쿼리를 작성하고 있는 것입니다.
So here you have always to look to your queries. And if you see that you are repeating the same things over and over, then you are writing a bad query.
22:13:08
CTE, 윈도우 함수와 같은 대안을 생각해 보세요. 그러면 테이블을 여러 번 읽거나 같은 논리를 반복하는 것보다 더 나은 방법을 찾을 수 있을 것입니다.
Think about alternatives like CTE, window functions, and I'm sure you will find a better way than reading the table several times or repeating the same logic several times.
22:13:18
쿼리 최적화는 항상 인덱스와 파티션을 사용하는 것만이 아닙니다. 최선의 관행을 사용하는 것이 중요합니다.
So as you can see, optimizing the queries is not always about using indexes and partitions. It's all about using best practices.
22:13:25
쿼리 성능을 최적화하는 방법에 대한 많은 최선의 관행을 다루었습니다.
All right, guys. So with that, we have covered a lot of best practices on how to optimize the performance of your query.
22:13:31
인덱스를 만드는 것만이 아니라, 쿼리를 작성하는 방식이 중요합니다.
And as you can see, it's not always creating indexes, right? In many scenarios, it's about how you write the query.
22:13:41
이제 다음 섹션에서는 테이블 생성에 대한 최선의 관행을 보여드리겠습니다.
And now in the next section, I'm going to show you the best practices on how to create tables.
22:13:47
DDL, 데이터 정의 언어의 최선의 관행입니다.
So the best practices of DDL, data definition language.
22:13:50
테이블 정의가 불량하면 쿼리 성능에 큰 영향을 미칩니다.
If you have a poor definition of your tables, this has a great impact on the performance of your queries. All right.
22:13:56
이제 고객 정보를 생성하기 위한 DDL을 살펴보겠습니다. 최선의 관행을 따르지 않고 있습니다.
So now we have here like a DDL in order to create a table, customer info. and it is not really following best practices.
22:14:03
첫 번째 팁은 가능하면 varchar 및 text 데이터 유형을 피하는 것입니다.
So let's go through it one by one. The first tip is try to avoid the data types, varchar and text if it's possible.
22:14:11
varchar 및 text는 성능을 위해 가장 나쁜 데이터 유형 중 하나입니다. 많은 자원을 소모합니다.
The varchar and text, they are like one of the worst data types for performance because they consume a lot of resources, whatever you do.
22:14:19
varchar 또는 text 열로 데이터를 정렬하면 매우 비싼 작업이 됩니다.
Like for example, if you are sorting the data by a column that is varchar or text, it is very expensive operation.
22:14:25
이런 열 위에 인덱스를 생성하면 비용이 많이 듭니다.
The same thing, if you go like and create an index on top of such a column, it's going to be as well expensive
22:14:29
데이터 단편화 문제를 일으킵니다.
and they cause a lot of problems with the data fragmentations
22:14:32
가능하면 이러한 데이터 유형을 건너뛰도록 하세요.
and many issues so try as much as you can to
22:14:36
모든 열을 검토하여 변경할 수 있는 것이 있는지 확인합시다.
skip those data type if it's possible so now let's go and review
22:14:39
많은 varchar가 있으므로 첫 번째 열을 확인합니다.
all those columns in order to see whether we can change something about
22:14:42
여기 첫 번째 이름이 varchar로 되어 있습니다. 괜찮습니다. 다음은 성입니다.
it because it has a lot of varchars so the first one
22:14:45
성은 text로 되어 있는데, 이는 좋지 않습니다. text는 varchar보다 나쁩니다.
over here we have is varchar because it is the first name well it is okay now moving on to the next one we have the last name as a text which is not really good because text is worse than varchar
22:14:55
text 대신 varchar를 사용하는 것이 좋습니다. 수정해야 합니다.
So it's better to use Vartar than a text. So here we have to fix it So Vartar and I'm going to go with the links 50.
22:15:02
국가는 varchar로 되어 있습니다. 변경할 수 없습니다.
Now moving on to the countries. So the country is going to be varchar. We cannot change that. It contains characters.
22:15:08
고객의 점수는 숫자만 포함되므로 변경할 수 있습니다.
So the next one is the score of the customer. Here we can do something about it. Because scores are only numbers.
22:15:14
이 점수를 건너뛰고 정수로 설정합시다.
So that's why we can go and skip this one. So let's remove it. And say you are integer.
22:15:20
생일은 날짜이며 varchar로 되어 있습니다.
And with that we have avoided using the varchar. And the same thing goes for the birthday.
22:15:25
이것은 좋지 않으며, 이 열을 날짜로 설정하여 건너뛸 수 있습니다.
The birthday is a date and here we have it as a varchar.
22:15:27
날짜가 varchar보다 훨씬 낫습니다. 다음은 정수입니다.
Well, this is not really good and we can skip that by having this column as a date.
22:15:32
그래서 날짜는 varchar보다 훨씬 낫습니다. 알겠죠. 다음은 정수입니다. 그래서 우리는 몇 가지를 수정했습니다.
So date is way better than having a varchar. All right. And the next one is integer. So with that, we have fixed few stuff.
22:15:38
그래서 우리는 점수와 생일을 수정했습니다. 그리고 그 덕분에 저장 공간을 절약했습니다.
So we have fixed the score and the birthday. And with that, we have saved some storage.
22:15:43
점수에 인덱스가 있다면 varchar보다 훨씬 나을 것입니다.
If we have an index on the score, it's going to be way better than having a varchar.
22:15:47
그리고 생일로 데이터베이스를 필터링하면 더 빨라질 것입니다. 다시 말하지만, varchar와 text를 피하는 것이 좋습니다.
And if you are filtering the database on the birthday, it's going to be faster. So again, try best to avoid the varchar and the text.
22:15:54
많은 프로젝트에서 많은 개발자들이 varchar를 사용하는 경향이 있다는 것을 보았습니다.
I have seen in many projects that a lot of developers tend to use the varchar.
22:15:58
모든 것을 varchar로 만드는 것이 더 쉽다는 것을 이해하지만, 정수, 날짜, 부동 소수점인지 결정하는 것이 더 어렵습니다. 모든 것을 varchar와 text에 맞출 수 있습니다.
And I understand it is easier to make everything as a varchar than deciding whether it is an integer, date, float and so on, because you can fit everything in the varchar and text.
22:16:08
하지만 이것은 게으른 것입니다. 이 열의 내용을 이해하는 데 시간을 투자하고 올바른 데이터 유형에 할당하려고 노력하세요. 이는 성능에 정말로 영향을 미칩니다.
But this is lazy. Take time to understand the content of this column and try to assign it to the correct data type because this has really impact on the performance.
22:16:18
다음 항목으로 넘어가면 max 또는
okay to the next one it says avoid using max or
22:16:21
너무 큰 링크를 사용하지 말라는 것입니다. 이제 우리는
overly large links so now we have to keep our eyes on
22:16:24
각 데이터 유형의 링크에 주의를 기울여야 합니다. 기본적으로 막대 차트는
the links of each data type basically the bar charts not
22:16:28
저장 공간을 낭비할 뿐만 아니라
only it's gonna waste like a lot of storage it's also gonna
22:16:31
SQL을 잘못 인도할 것입니다. 큰 인덱스를 생성하여
like mislead the sql by creating large
22:16:34
데이터 자체는 작지만 큰 길이를 정의했기 때문에 불필요한 인덱스가 생성됩니다.
indexes which is totally unnecessary because the data itself is small but because you have defined like a large length is gonna
22:16:42
큰 인덱스는 항상 문제가 됩니다. 왜냐하면
check those informations and make the decision to make a big index
22:16:46
데이터를 정렬하고 검색하는 데 모든 것을 느리게 만들기 때문입니다.
and large indexes are always problematic because
22:16:49
인덱스를 업데이트하여 데이터를 느리게 만들 것입니다. 정말 나쁩니다.
they're gonna slow everything down by sorting the data by retrieving
22:16:52
어디에나 정의하고 맹목적으로 따라가는 것은 좋지 않습니다.
data by updating the index so it is really bad
22:16:55
max 또는 255로 다시 돌아갑니다.
practices if you go blindly and define everywhere
22:16:58
다시 최대값 또는 255
max or 255 again
22:17:02
각 열에 대해 생각할 기회를 주고 예측합니다.
give it a chance to think about each column and predict a
22:17:05
예를 들어 여기서 확인하면, 우리는 이름 변수의 최대값이 varchar라고 말하고 있습니다. 대부분의 이름은 짧기 때문에 첫 이름에 맞추기 위해 varchar의 최대 크기가 필요하지 않습니다.
link for it so for example if we check over here we are saying first name varchart max well most of the first names are short so we We don't need like the maximum size of a varchar to fit a first name.
22:17:17
따라서 여기서는 최대값 대신 50으로 쉽게 설정할 수 있습니다. 국가 열에도 동일한 원칙이 적용됩니다.
So here we can go easily instead of max with the 50. And the same thing goes for the column country.
22:17:22
국가 이름에 255자를 필요로 하지 않습니다.
We don't need 255 characters for the country name.
22:17:27
50자 정도와 같은 더 현실적인 값을 사용할 수 있습니다. 더 작게 설정할 수도 있지만, 50자로 설정하는 것도 괜찮습니다.
We can go with something more realistic like around 50. I think you can even go smaller, but it's fine to have 50.
22:17:32
따라서 여기서의 모범 사례는 데이터를 분석하고 각 열의 크기를 예측하는 것입니다.
So the best practice here is to analyze your data and to predict the size of each column.
22:17:39
여기서 최선의 방법은 데이터를 분석하고 각 열의 크기를 예측하는 것입니다.
And don't be lazy by just defining max everywhere. I know it's faster, but it's bad for performance. Okay, what do you have else?
22:17:46
모든 곳에 max를 정의하는 것에 게으르지 마세요. 빠르긴 하지만 성능에 좋지 않습니다. 자, 다른 것은 무엇이 있나요?
Use the constraint NATNULL as much as possible. The NATNULL is amazing and has a lot of advantages.
22:17:52
NATNULL 제약 조건을 가능한 한 많이 사용하세요. NATNULL은 놀랍고 많은 장점이 있습니다.
Of course, the biggest advantage is that the data integrity of your table.
22:17:56
물론, 가장 큰 장점은 테이블의 데이터 무결성입니다.
So with that, you make sure no nulls are inserted in specific column.
22:18:00
이렇게 하면 특정 열에 null이 삽입되지 않도록 할 수 있습니다.
But it is as well good practices to use it for improving the performance.
22:18:05
인덱스를 생성하는 경우 더 나은 인덱스 성능을 얻을 수 있습니다.
Because if you are creating an index, you're going to get a better index performance.
22:18:09
SQL은 내 트리 안에 null이 없다는 것을 알고 있습니다.
Since SQL knows there is no nulls inside my tree, inside the index.
22:18:13
쿼리를 작성할 때 특정 열이 null이 아니어야 한다고 필터를 사용하는 경향이 있습니다.
And in the other side, if you are writing a query, we tend to use a filter where we say a specific column should not be null.
22:18:20
DDL에서 null이 아니라고 확실히 하면 이 필터를 건너뛸 수 있습니다.
But if you make sure that in the DDL it is not null, then you can skip this filter. And with that, you are reducing the size of your query.
22:18:27
우리는 모든 열을 살펴보고 null과 null이 아닌 것을 결정할 것입니다.
So what we're going to do, we're going to go through all the columns and decide whether it is not null and null. So for example, the first name and the last name, they should not be null.
22:18:33
그래서 첫 번째 이름과 성은 null이 아니어야 합니다.
So that's why I'm going to say not null. And the same thing for the last name.
22:18:38
그래서 null이 아니라고 말할 것입니다. 성도 마찬가지입니다.
not null for the customer id we're going to talk about it soon
22:18:41
고객 ID에 대해 곧 이야기할 것입니다.
because we're going to convert it to primary key and primary keys are usually not
22:18:44
null이 아니어야 하며, 제약 조건을 만들어야 합니다.
null so now for the country we may have it in the business that's
22:18:47
총 구매 및 점수에 대해 이야기해 보겠습니다.
it should not be null so we go and make a constraint
22:18:50
새로운 고객이라면 데이터에 null이 있을 수 있습니다.
about it now about the total purchases and scores if
22:18:54
그래서 비워두고 생일은 보통 선택 사항이 될 것입니다.
it is new customer maybe we can have a null inside our data
22:18:57
고객이 직원인지 여부도 null이 될 수 있습니다.
so we're going to leave it empty and i think birthday is going to be usually optional
22:19:00
제약 조건을 가질 수 있는 세 개의 열을 찾았습니다.
so we're going to leave it as well and whether the customer is employee or not this could be as well a null so with that we have
22:19:07
다음으로 넘어가면, 모든 테이블이 클러스터형이어야 한다고 합니다.
found out like three columns where we can have a constraint about the not null and if you go and create like an index on the country it can be a better index.
22:19:16
모든 테이블이 클러스터형이어야 합니다.
Okay moving on to the next one it says make sure that
22:19:19
기본 키가 있어야 하며, 관계를 구축하는 데 도움이 될 수 있습니다.
all your tables inside the database have a clustered
22:19:22
기본 키와 외래 키가 있는 테이블 간의 관계를 구축하는 데 도움이 됩니다.
primary key and as well it can help you building the relationship
22:19:25
SQL 서버에서 기본적으로 클러스터형 인덱스가 됩니다.
between tables where you have primary keys and foreign keys and you can join tables then very easily and as well a primary key has importance for the
22:19:33
기본 키에 인덱스가 있는 것이 좋습니다.
performance and in SQL server, the default going to be a clustered index, which is really good to have an index on the primary key because sometimes you are doing like an update operations or delete operations.
22:19:44
조인 테이블의 조회에 도움이 될 수 있습니다.
It can help out by the lookups of joining tables.
22:19:47
기본 키를 갖는 것에는 많은 성능 이점이 있으며 모든 테이블에 기본 키가 있는지 확인하세요.
So there are a lot of performance benefits of having a primary key and make sure that all your tables having a primary key.
22:19:53
테이블의 문제를 보면 기본 키가 없으며 기본 키는 고객 ID가 될 수 있습니다. 그러니 그렇게 해봅시다.
So as you can see the issue of our table, we don't have a primary key and our primary key can be that customer ID. So let's go and do that.
22:20:00
기본 키와 기본적으로 클러스터형이 될 수 있습니다.
primary key and as I said as a default can
22:20:03
클러스터형이 될 수 있지만, 만약을 대비해 적어두겠습니다.
be clustered but I'm gonna write it down in case if
22:20:07
다른 데이터베이스에서 작업할 때 클러스터형인지 확인하세요.
you are working with different databases make sure it is clustered
22:20:10
다음으로 넘어가겠습니다. 기본 키에 관한 것만이 아닙니다.
okay moving on to the next one it's not only about the primary key
22:20:13
외래 키를 관리해야 하며, 최선의 방법은
we have to take care of our foreign keys so the best practice
22:20:16
자주 사용되는 외래 키에 대해 비클러스터형 인덱스를 생성하라고 합니다.
says create non clustered index for
22:20:19
자주 사용되는 외래 키는 두 테이블을 연결하고 조인하는 데 중요합니다.
the foreign keys if they are frequently used the foreign keys are usually important in order to connect and join two tables and usually
22:20:27
우리는 그것을 자주 사용하며 때때로 데이터를 필터링하기 위해 사용합니다.
we frequently use it and not only that we use it sometimes
22:20:30
데이터를 필터링하기 위해 비클러스터형 인덱스를 생성하면 속도를 향상시킬 수 있습니다.
in order to filter the data and if you create a non-clustered
22:20:34
그것을 할 수 있는 방법은 매우 간단합니다. 비클러스터형 인덱스를 생성할 것입니다.
index for that it can improve the speed so what you
22:20:37
외래 키에 대한 고객 정보 테이블에 비클러스터형 인덱스를 생성할 것입니다.
can do it's very simple we're going to go and create a non-clustered index
22:20:40
외래 키인 직원 ID에 대해 비클러스터형 인덱스를 생성하는 것은 매우 간단합니다.
on our table customers info for the foreign key
22:20:44
고객 정보 테이블의 외래 키인 직원 ID에 대해 비클러스터형 인덱스를 생성하세요. 이 외래 키는 쿼리에서 자주 사용되는 중요한 외래 키입니다.
employee id so how to do it is very simple we're going to go and
22:20:47
좋습니다, 친구들. 보시다시피 DDL을 개선하고 최적화하는 방법에 대한 많은 모범 사례가 있습니다.
say create non-clustered index on our table the customers info on our foreign key the employee id but again make sure that this is an important foreign key that is used frequently from your queries.
22:20:59
건강한 DDL은 쿼리의 성능을 향상시킬 수 있습니다.
All right, friends. So as you can see, there are a lot of best practices on how to improve and optimize the DDL.
22:21:05
이제 다음 섹션에서는 인덱싱에 대한 모범 사례와 팁을 보여드리겠습니다.
Having a healthy DDL can improve the performance of your queries.
22:21:08
좋습니다, 첫 번째 모범 사례이자 가장 중요한 것은 과도한 인덱싱을 피하는 것입니다.
Now, in the next section, I'm going to show you the best practices and tips and tricks about indexing. So let's go.
22:21:18
너무 많은 인덱스는 삽입 및 업데이트 속도를 저하시킬 것입니다.
All right, the first best practices and the most important one is avoid over indexing
22:21:22
삭제 작업을 느리게 하고 실행 계획을 혼란스럽게 할 것입니다.
because too many indexes gonna slow down the insert update
22:21:26
올바른 인덱스를 선택하는 계획과 성능에 대해.
delete operations and it's gonna confuse as well the execution
22:21:29
시스템 전체의 성능이 저하될 수 있습니다. 또 다른 팁은
plan about choosing the right index and the performance
22:21:32
인덱스 사용을 모니터링하는 것입니다.
of the whole system gonna go down and another tip is to
22:21:35
인덱스 사용량을 모니터링하면
monitor the usage of the indexes and i can tell you
22:21:38
생성되는 인덱스의 90%는
90 percent of the indexes that is being created usually
22:21:42
전혀 사용되지 않아서 많은 공간을 차지하고
are not used at all so they are taking a lot of space slowing down everything so go and drop those unused indexes in your system the next
22:21:51
정기적인 작업을 수행하는 것이 최선의 방법입니다.
best practice is to have a regular job like maybe
22:21:54
주간 작업을 수행하여 통계를 정기적으로 업데이트해야 합니다.
a weekly job so first you have to update the statistics regularly
22:21:58
새로운 데이터를 삽입하고 데이터를 수정할 때
as you are inserting new data and modifying data inside
22:22:01
데이터베이스의 통계와 메타데이터가
your database the statistics and the metadata of your tables
22:22:04
구식이 될 수 있으며 이는 매우 나쁩니다.
might get outdated and this is really bad because you
22:22:07
쿼리에 대한 최적의 실행 계획을 얻지 못하고
will not get an optimal execution plan for your queries and
22:22:10
쿼리가 느려질 것이므로 모든 통계를 정기적으로 업데이트해야 합니다.
this is going to slow down your queries of course so regularly make sure that all the statistics are updated in order to have an
22:22:17
최적의 실행 계획을 세우고
optimal execution plan and what else we can do in this weekly
22:22:21
인덱스를 재구성하고 재조직하는 것입니다.
job is that we can go and rebuild and reorganize
22:22:24
데이터 조각화를 방지하는 것입니다.
our indexes and that is to make sure that we are
22:22:27
데이터 조각화는 매우 나쁘며
preventing data fragmentations in our indexes
22:22:30
많은 사용되지 않는 공간이 생길 수 있습니다.
data fragmentations in your indexes is really bad because there
22:22:33
클러스터형 인덱스의 순서가 올바르지 않으므로
will be a lot of unused spaces the order of your clustered
22:22:37
최소한 주간으로 모든 인덱스를 재구성하고 재조직해야 합니다.
index will not be correct so make sure that at least weekly you are rebuilding and reorganizing all your indexes so those are the best practices of
22:22:45
성능을 개선하고 인덱싱을 최적화하는 방법입니다.
improving the performance and optimizing your indexing
22:22:48
프로젝트에서 매우 큰 테이블로 어려움을 겪고 있다면
if you are struggling with a very large tables in your projects
22:22:52
사실 테이블을 사용하고
like having facts tables then go and use
22:22:55
SQL 파티셔닝을 사용하여
sql partitioning in order to divide these
22:22:58
테이블을 더 작은 조각으로 나누어
tables into smaller pieces which can improve
22:23:01
성능을 개선할 수 있습니다.
the performance whether you are reading data from the table
22:23:05
테이블에서 데이터를 읽거나 쓸 때
or writing data and of course you can go and mix
22:23:08
이 파티션 테이블에 열 저장 인덱스를 적용하면 최상의 성능을 얻을 수 있습니다.
things where you can go and apply a column store index on this partition table then you will get the best performance if you are having large tables.
22:23:22
좋아요, 친구들. 그래서 그게 바로 최고의 실천 팁입니다.
All right friends so that's all those are the best practices tips
22:23:25
그리고 제가 여러 해 동안 일하면서 연결한 요령입니다.
and tricks that I've connected in the many years working
22:23:28
SQL과 관련하여 항상 명확한 쿼리를 작성하는 데 집중하세요. 읽기 쉽고 이해하기 쉽게 만드세요.
with SQL and now my final thoughts about this is that try always to focus on making clear queries make it like easy to read and easy to understand
22:23:39
성능 최적화는 필요할 때만 시도하세요. 작은 데이터베이스가 있다면 성능에 대해 너무 걱정하지 마세요.
and try to optimize the performance only if it's needed so if
22:23:42
작은 데이터베이스가 있다면 성능에 대해 너무 걱정하지 마세요.
you have like small database don't worry a lot about the performance
22:23:45
SQL 최적화기가 최상의 계획을 선택할 것이고,
because the sq optimizer gonna pick the best plan for you and
22:23:49
단순한 쿼리를 작성하는 데만 집중하세요. 성능 문제가 발생하면 항상
focus only on having simple queries and if
22:23:52
실행 계획을 사용하여 테스트하세요. 그것이 당신의 판단 기준이 되어야 합니다.
there is like performance problem always test using the
22:23:55
인덱스를 적용하거나 쿼리를 다시 작성할 때는 항상 실행 계획을 사용하여 이전과 이후를 비교하세요.
execution plan it should be your judge so if you are applying
22:23:58
좋아요, 친구들. 그래서 성능을 최적화하기 위한 모든 팁과 요령이었습니다.
an index or you are rewriting your queries always compare before and after using the execution plan and if you are gaining more performance then adopt the new query or the new index.
22:24:09
이제 다음 장에서는 SQL을 사용할 때 AI를 어떻게 활용하는지 보여드리겠습니다.
Alright my friends so that's all the tips and tricks best practices that I have for you in order to optimize the performance and with that we have covered now everything about this chapter the performance optimization.
22:24:18
좋아요, 이제 AI와 함께 일하는 미래의 개발자로서 중요한 것을 공유하고 싶습니다.
Now in the next chapter I'm going to show you how I use AI in order to assist me while I'm using SQL. So let's go.
22:24:29
진정한 기술을 쌓고 개발자로 성장하는 가장 좋은 방법 중 하나는 복잡한 작업과 문제를 스스로 해결하는 것입니다.
Alright so now I would like to share something important with you especially as a future developer that is working with AI.
22:24:35
복잡한 작업에 갇히고 해결책을 찾기 위해 스스로 코드를 작성할 때, 여기서 마법이 일어나고 진정한 학습이 이루어집니다.
One of the best ways in order to truly build skill and to grow as a developer is by working on complex tasks and issues on your own.
22:24:44
너무 빨리 AI에게 해결책을 요청하면 전문가가 되기 위한 필수 단계를 건너뛰게 됩니다.
So when you are stuck on complex tasks and you are pushing yourself to find a solution for it and you are writing your code on yourself, here the magic happens and the real learning can happen.
22:24:55
그리고 그보다 더 중요한 것은, AI가 언제 잘못되었는지 이해할 수 있는 기술이 개발되지 않을 것입니다.
And if you jump too quickly and ask the AI for a solution, what you are doing, you are skipping an essential step in order to become an expert.
22:25:03
제 추천은 규율을 가지고, 항상 스스로 작업을 해결하려고 하고, 해결 방법이 더 이상 없을 때만 AI에 의지하는 것입니다.
And more important than that, you won't develop skills in order to understand when and where the AI was wrong.
22:25:10
그래서 그것이 제 의견이자 조언입니다. 그럼 빠르게, ChatGPT는 무엇인가요?
So my recommendation here is to have a discipline, always try to solve the task on your own, and only turn to AI if you don't have any more ideas on how to solve the task.
22:25:20
OpenAI에서 개발한 AI 프로그램으로, 질문을 이해하고 인간과 유사한 답변을 제공하도록 훈련되었습니다.
So that's my opinion and my advice for you. So quickly, what is ChatGPT?
22:25:28
그럼 GPT는 무엇을 의미할까요? G는 Generative를 의미합니다.
It is an AI program that is developed by OpenAI that is trained to understand questions and provide human-like answers.
22:25:36
그렇다면 GPT는 무엇을 의미할까요? G는 생성적(Generative)을 의미합니다.
So what GPT stands for? The G stands for Generative.
22:25:40
즉, 데이터 모델이 새로운 콘텐츠, 새로운 텍스트를 생성할 수 있다는 뜻입니다. P는 사전 훈련된(Pre-trained)을 의미합니다.
So that means the data model can generate a new content, new text. And P stands for Pre-trained.
22:25:46
데이터 모델은 이미 방대한 양의 데이터로 훈련되어 있습니다. T는 변환기(Transformer)를 의미합니다.
The data model is already trained on huge amount of data. And the T stands for Transformer.
22:25:52
이는 문맥을 매우 빠르고 정확하게 이해하기 위해 프롬프트의 문장을 처리하는 신경망 아키텍처의 일종입니다.
It is type of neural network architecture that processes your sentences in the prompts in order to understand the context behind it very fast and accurate.
22:26:02
다른 한편으로, 우리는 GitHub Copilot이 있습니다. 이는 GitHub에서 개발하였으며 OpenAI의 동일한 데이터 모델을 사용하고 있습니다.
And in the other hand, we have the GitHub Copilot. It is developed by the GitHub and as well using the same data models from the OpenAI.
22:26:10
즉, Shadgpt와 Copilot은 둘 다 OpenAI에서 개발한 동일한 언어 모델을 사용하고 있습니다.
So that means both Shadgpt and Copilot, both of them are using the same language model that is developed from OpenAI.
22:26:19
그래서 GitHub Copilot은 GitHub에 있는 수많은 코드로 학습했습니다.
So the GitHub Copilot did train on tons of codes that is available in GitHub.
22:26:24
코드 편집기에서 코드를 작성할 때, 예를 들어 Visual Studio와 같은 프로그램에서 실시간으로 제안을 제공합니다.
So how it works as you are writing a code in the code editor, like for example, Visual Studio, it's going to provide real time suggestions as you are writing and typing your code.
22:26:34
이 두 가지, ShadGPT와 Copilot을 비교하면,
So now if you compare those two, ShadGPT and the Copilot, we
22:26:37
ShadGPT는 웹사이트나 앱을 통해 AI와 상호작용할 수 있는 독립형 애플리케이션입니다.
can say that the ShadGPT is a standalone application where you can interact with it using a website or an app where you go and start a conversation with the AI.
22:26:47
반면에 Copilot은 코드 편집기에 직접 통합되어 있습니다. 예를 들어 Visual Studio Code와 같습니다.
Where on the other hand, the copilot is directly integrated in your code editor. Like for example, the Visual Studio Code.
22:26:54
이것은 ShadGPT보다 훨씬 더 좋습니다. AI와 실시간 상호작용이 가능하기 때문입니다.
This is way better than ShadGPT because you have real-time interaction with the AI.
22:26:59
Copilot을 사용하면 코딩 중에 실시간 도움을 받을 수 있습니다.
This is a great advantage for the copilot because everything in one place.
22:27:03
ShadGPT의 주요 목적은 원하는 주제에 대해 AI와 대화하는 것입니다.
So with the copilot, you are getting real-time assistance during your coding.
22:27:08
소프트웨어 개발에만 국한되지 않습니다. 반면에 Copilot은 소프트웨어 개발 지원에만 집중합니다.
So the main purpose of the ShadGPT is to have a conversation with the AI for any topic that you like.
22:27:14
개발자로서 코드를 작성할 때 코드의 자동 완성이나 코드 블록 제안을 받게 됩니다.
not limited only for software development. But in the other hand, a copilot focuses only on assisting the software development.
22:27:23
이것이 Shadgpd와 Copilot 간의 주요 차이점입니다.
Where you as a developer, as you are writing your code, you are getting auto-completion of the code, or maybe a block of code as a suggestion.
22:27:31
소프트웨어 개발을 하거나 데이터 프로젝트를 진행할 때, 물론 프로젝트에서의 역할에 따라 다릅니다.
So these are the key differences between Shadgpd and Copilot.
22:27:39
프로젝트에서 수행해야 할 다양한 작업과 활동이 있을 것입니다.
Now, if you are doing software development, or you are working with data projects, And of course, it depends on your role in the project.
22:27:45
새로운 아이디어에 대한 브레인스토밍, 솔루션 인코딩, 디버깅, 문서 생성, 다양한 아키텍처 논의, 로드 코스 분석 등이 있을 것입니다.
There will be many different types of tasks and activities that should be done in the project.
22:27:50
각 프로젝트의 활동과 작업의 범위는 보통 매우 큽니다.
Like there will be a lot of brainstormings about new ideas, encoding solutions, debugging, generating documentations, discussing the different types of architecture, doing road course analyzes.
22:28:02
물론, 이러한 작업과 활동을 지원하기 위해 다양한 AI 도구를 사용할 수 있습니다.
So the spectrum of activities and tasks in each project usually is very huge.
22:28:07
모든 것을 포괄할 수 있는 AI 도구는 없습니다. 저는 Copilot과 ShadGPT를 오가며 사용합니다.
And of course, we can go and use the help of different AI tools to assist us with those tasks and activities.
22:28:13
이제 다양한 작업을 ShadGPT 또는 Copilot에 매핑해 보겠습니다. 이제 ShadGPT에 집중해 보겠습니다.
And there is like not one AI tool that can cover all those stuff. I tend to jump between copilots and something like ShadGPT.
22:28:20
첫 번째는 브레인스토밍과 아이디어입니다. 그래서
OK, so now I'm going to go and map those different tasks to either ShadGPT or copilots. So now let's focus on the ShadGPT.
22:28:26
프로젝트에 큰 작업이나 문제를 가지고 있다면,
The first one is brainstorming and ideas. So
22:28:29
해결책을 찾고 싶을 때, 저는 보통
now if we have in our project a big task or let's say a big issue
22:28:32
우리가 해결책을 찾고 싶어하는 것에 대해, 나는 주로 사용하려고 합니다.
that we want to find solution for it, I tend to use, of
22:28:35
물론, 주제에 대해 논의하고 여러 아이디어를 탐색하고 논의한 다음 모든 아이디어를 평가하기 위해 Shagipity와 같은 도구를 사용합니다.
course, tools like Shagipity in order to have a discussion about the topic, in order to explore and discuss multiple ideas and then start evaluating all those ideas.
22:28:45
내가 Shagipity를 사용하게 된 다음 단계는 프로젝트 계획을 하는 것입니다. 그래서 그것도 높은 수준의 것입니다.
The next one where I found myself using Shagipity is doing the project planning. So it is as well something high level.
22:28:51
프로젝트 디자인에 대해 Shagipity와 논의할 수 있습니다.
You can go and discuss with the Shagipity about the design of your projects.
22:28:55
프로젝트의 이정표와 로드맵에 대해서도 논의할 수 있습니다.
And you can as well discuss the milestones, the roadmap of the projects.
22:28:59
다음으로 Shagipity를 사용하는 것은 학습, 지식 및 연구입니다.
The next thing that I find myself using Shagipity is for learning, knowledge and research.
22:29:04
대규모 데이터 프로젝트를 작업하는 경우 클라우드 서비스와 AI 분석 도구의 양에 압도될 것입니다.
If you are working with big data projects, you will be overwhelmed with the amount of cloud services and AI analytics tools.
22:29:11
따라서 물론 새로운 것을 배우고 정보를 수집할 수 있습니다.
So and of course, you can go and learn new stuff, gather information and knowledge using Shagipity.
22:29:17
다음 작업으로 문서 생성을 진행하겠습니다.
OK, moving on to the next task, we have generating documentations.
22:29:20
문서 작성을 항상 힘든 과정이며 많은 시간을 소모합니다.
Writing documentations is always a painful process and consumes a lot of time.
22:29:24
문서를 생성하기 위해 Shagipity와 같은 도구를 사용합니다.
And I tend to use tools like Shagipity in order to generate those documentations.
22:29:29
물론 문서를 항상 검토하고 간결하게 만듭니다.
But of course, I always review the documentations and make it short. Okay, moving on to another topic where I use Shadgpt is that to discuss architecture.
22:29:37
새로운 프로젝트를 시작하는 경우 다양한 아키텍처 유형이 있을 것입니다.
Of course, if you are starting new projects, there will be like different types of architecture in order to implement the projects.
22:29:42
프로젝트에 적합한 아키텍처에 대해 논의할 수 있습니다.
And of course, you can discuss with Shadgpt about the different types of architecture.
22:29:46
프로젝트 사양을 제공하면 적합한 아키텍처에 대해 논의할 수 있습니다.
And if you give the specifications about your projects, then you can discuss with Shadgpt which architecture is suitable for the project.
22:29:54
항상 연구하는 작업 중 하나는 모범 사례, 팁 및 요령을 탐색하는 것입니다.
And another task that I find myself always like researching is exploring the best practices, tips and tricks.
22:30:00
Shagipity와 추천 사항에 대해 논의할 수 있습니다.
So you can have a discussion with the Shagipity about the recommendations, what are the best practices,
22:30:06
복잡한 작업이 있을 경우 Shagipity와 논의하여 작은 조각으로 나누고 해결책을 찾습니다.
what are the common pitfalls in order to make sure that your code and your solution is always up to date with the best practices.
22:30:13
프로젝트에 복잡한 작업이 있을 경우 Shagipity와 논의합니다.
And one more thing, if there is like in the project, a very complex task, then I tend to have a discussion with a tool like Shagipity in order to break this complex task into small pieces and start finding the solution for each piece.
22:30:25
이제 Copilot을 사용하여 다양한 작업을 해결하고 있습니다.
And now in the other hand, I'm using Copilot in order to solve different type of tasks. So here where I get my hand dirty in the code.
22:30:32
코딩 중에는 항상 Copilot을 사용하여 도움을 받습니다.
So while I'm coding, I'm using all-time Copilot in order to assist me because it provides directly inline suggestions and help me to code faster and reduce the human error that I might make.
22:30:43
코드 작성이나 디버깅 중에는 Copilot을 사용합니다.
So while I'm writing a code or debugging, I tend to use Copilot and I don't find myself going to SHA-GPT to ask about code or syntax.
22:30:52
리팩토링은 소프트웨어 개발에서 매우 유명한 작업입니다.
we can do it directly in the copilot. And one task that is very famous in any software developments, we have the refactoring.
22:30:59
느리고 나쁜 디자인의 코드를 리팩토링할 수 있습니다.
So if you have like a code that is slow and bad designs and you want to refactor the whole code, you can do it directly in your code together with the copilot in order to find optimizations.
22:31:08
인라인 주석을 추가하기 위해 Copilot을 사용합니다.
And I use as well copilot in order to add inline comments. So I don't find myself going to chatgpt and asking to add comments to my code.
22:31:16
코드에서 직접 Copilot을 사용할 수 있습니다.
You can do it directly in your code using copilot.
22:31:19
모든 것이 완벽하게 작동하면 모범 사례와 좋은 성능을 갖게 됩니다.
And of course, if everything is working perfectly, I have the best practices, the good performance, I have the comments.
22:31:24
코드의 스타일과 형식을 유지해야 합니다.
It's still you have to maintain nice style and format of your code. And of course, now we can do that directly using the copilot.
22:31:30
코드의 스타일과 형식을 유지해야 합니다. 물론, 이제 우리는 코파일럿을 사용하여 직접 할 수 있습니다.
We don't have to go and jump to ShadGPT in order to style and format your code. And as you can see, I'm currently using both of them for different types of tasks.
22:31:37
다시 말해, 뭔가 논의해야 할 것 같으면 ShadGPT로 갑니다.
So again, if I have the feeling that I have to discuss something, I go to ShadGPT.
22:31:42
아이디어가 매우 명확하고 해결책을 알게 되면 코파일럿을 사용하여 코드를 작성하기 시작합니다.
But once the idea is very clear and I know the solution, then I start using copilot in order to write the code.
22:31:50
코파일럿의 도움으로 깔끔하고 전문적인 코드를 제공할 수 있습니다.
And with the help of the copilot, I can deliver clean and professional codes.
22:31:54
현재 Shadjpity와 코파일럿을 이렇게 사용하고 있습니다.
So this is how I currently use both Shadjpity and copilots.
22:32:02
자, 친구들. 이제 제가 할 것은 Visual Studio 코드에서 GitHub 코파일럿에 대한 간단한 가이드를 보여주는 것입니다.
Okay, friends. So now what I'm going to do, I'm going to show you a quick guide about the GitHub copilot in the Visual Studio codes.
22:32:08
프로필을 만들고 Visual Studio에 연결하면 코파일럿의 새로운 아이콘을 받게 됩니다.
Once you create a profile and connect it to your Visual Studio, you will get a new icon for the copilot.
22:32:14
그곳에 가면 상태를 빠르게 확인할 수 있고, 코파일럿을 비활성화할 수도 있습니다.
So once you go there, you can see quickly the status. and as well you can go and disable the copilots.
22:32:20
이렇게 되어 있으면 코파일럿이 활성화된 것입니다.
So if you have it like this that means your copilot is active.
22:32:23
모든 것이 준비되면 매우 간단하게 코드를 작성하기 시작하면 됩니다.
So now once you have everything up and running what you have to do is very simple just go and start writing your code.
22:32:30
선택 문을 입력하기 시작하면 회색 텍스트가 보입니다.
So start typing any select statements and now you can see that we have a gray text.
22:32:35
이 회색 텍스트는 고스트 텍스트라고 합니다. 코파일럿의 자동 완성으로, 'select star from table'이라고 표시됩니다.
This gray text called the ghost text. It is an auto completion from the copilot and now it says select star from table and now as you can see as a mouse hover on it
22:32:45
여기서 세 가지 제안이 있습니다. 하나, 둘, 셋.
we can see that i can go and switch between different suggestions
22:32:49
셋째 것을 선택할 것이며, 여기서 말하듯이
so here we have like three suggestions one two three and
22:32:52
제안을 수락하고 싶다면 해야 할 일은
i'm gonna go with the third one so now here as it says if
22:32:55
탭을 누르는 것입니다. 그러니 가서 해봅시다.
you want to accept the suggestion all what you have to do is to
22:32:59
전체를 수락하는 것이지만, 이제 우리는 코드의 일부만 수락할 것이라고 말해야 합니다.
press tab so let's go and do it so you are accepting the
22:33:02
그것을 하려면 Ctrl을 누르고 오른쪽 화살표를 누릅니다.
whole thing but now we should say you know what i'm gonna accept only part of the code so let's go again and write select so this time we're gonna be selective in order to do
22:33:11
그렇게 하면 고스트의 일부를 수락하게 됩니다.
that hold control and then with the right arrow and
22:33:14
모두가 아닌데, 물론 전체를 수락하고 싶다면 그냥
with that we are accepting part of the ghost not
22:33:18
탭을 누르면 됩니다. 이제 고스트 텍스트를 트리거하는 또 다른 방법이 있습니다.
everything but of course if you are accepting the whole thing just go
22:33:21
먼저 주석을 정의하여 고스트 텍스트를 트리거하는 방법이 있습니다.
with the tab and now there is another way in order to trigger the
22:33:24
예를 들어, 점수를 기준으로 상위 세 고객을 선택하고 싶습니다.
ghost text and that's by defining first a comment for
22:33:28
쿼리를 작성하기 시작하면 코파일럿이 주석에 관련된 쿼리를 작성할 것입니다.
example we want to select the top three customers based on the score so
22:33:31
여기서 두 가지 제안이 있습니다. 여기서 정렬 기준이 있는 것과 없는 것이 있습니다.
now once you start writing the query the copilot is going to go and write a query that is relevant for the comments so now as you can see we are getting top three from customers because we want the top three customers.
22:33:41
여기 두 가지 제안이 있습니다. 여기에서 정렬 기준을 선택하거나 선택하지 않을 수 있습니다. 그래서 저는 정렬 기준을 선택하고 탭을 누르겠습니다.
And here we have like two suggestions. Like over here, we have the order by or without it. So I will go with order by and hit tap.
22:33:49
이제 여기 또 다른 제안이 있습니다. 데이터가 높은 것부터 낮은 것까지 제공되도록 하는 것이 맞습니다. 자, 다음으로 넘어갑니다.
And now here another suggestion, which is correct in order to serve the data from the highest to the lowest. All right, moving on to the next one.
22:33:54
SQL에서 배운 것처럼, 작업을 해결하기 위해 여러 가지 솔루션과 쿼리 변형이 있을 수 있습니다.
As we learned in SQL, in order to solve a task, there could be like multiple solutions and multiple variants of queries that solving the same task.
22:34:03
예를 들어, 고객을 총 주문 판매액에 따라 순위 매기는 작업이 있다고 가정해 봅시다.
So let's say that we have this task rank customers based on their total order sales.
22:34:07
쿼리를 작성하기 시작하면 현재 유령 텍스트가 표시됩니다. 하지만 이제 할 수 있는 것은 Ctrl + Enter를 누르는 것입니다.
So what you can do if you start writing the query, we are getting now the ghost text. But now what you can do, we can go and hit control enter.
22:34:14
이제 오른쪽에서 무슨 일이 일어나는지 보겠습니다. 다양한 제안을 받게 됩니다. SQL에서 이 작업을 해결하는 방법에 대한 아홉 가지 제안이 있습니다.
So now what happens on the right side, you will get different suggestions. And here we have like nine suggestions on how to solve this task in SQL.
22:34:22
이제 해야 할 일은 모든 제안을 살펴보고 하나를 선택하는 것입니다.
So now what you have to do is to go through all those suggestions and pick one.
22:34:25
예를 들어, 세 번째 제안을 선택하고 제안을 수락하면 코드 편집기에 표시됩니다.
For example, I can go with the suggestion number three and say accept suggestion and you will get it in your code editor.
22:34:32
이것이 우리가 코파일럿 자동 완성과 AI를 직접 통합하는 것을 의미하는 것입니다.
So this is what we mean with the copilot auto-completion and integrating the AI directly as you are developing and writing a code.
22:34:38
이제 코파일럿에서 유령 텍스트와 자동 완성을 사용하는 것 외에도 인라인 샷을 사용하여 AI와 상호 작용할 수 있습니다.
Now in the copilot, not only using the ghost text and the auto-completion, we can go and interact with the AI using inline shots.
22:34:47
이것은 샤드기비티와 비슷한 것입니다. 샷을 트리거하려면 Ctrl-I를 누르면 됩니다.
So it's something like Shadgibity. Now in order to trigger the shot, what you're going to do, you're going to go and hit Ctrl-I.
22:34:53
그런 다음 코파일럿에게 질문할 수 있는 장소가 생깁니다.
And then you're going to get a place in order to ask the copilot a question.
22:34:56
예를 들어, 쿼리를 판매 주문 테이블과 조인합니다.
Like for example, join the query with the table sales orders
22:35:03
이제 실행해 보겠습니다.
so let's go and hit it now
22:35:07
고객이 조인된 전체 쿼리를 얻은 것을 볼 수 있습니다.
as you can see we got a full query where the customers is joined
22:35:10
주문과 함께 조인되며 테이블이 완전히 올바릅니다.
with the orders and it is totally correct how the table
22:35:13
조인된 테이블이므로 코파일럿은 이미 모든 것을 알고 있습니다.
are joins so that means copilot knows already all
22:35:17
데이터베이스에 있는 테이블과 열을 조인하는 방법도 알고 있습니다. 정말 놀랍습니다.
the tables that i have in the database and as well the
22:35:20
열과 그것들을 결합하는 방법은 정말 놀랍습니다. 그래서 만약
columns and how to join them this is amazing so if
22:35:23
샤드기비티보다 더 빠릅니다. 샤드기비티에서는 질문하기 전에 데이터베이스와 열을 입력해야 합니다.
you like it you go and accept it of course and this is way faster
22:35:26
질문하기 전에 데이터베이스와 열을 입력해야 합니다.
than having shagip t because in shagip t you have to introduce
22:35:29
당신의 데이터베이스, 당신의 열 및 기타 사항을 묻기 전에
your database your columns and stuff before even asking
22:35:33
그럼 우리는 무엇을 더 할 수 있을까요? 코드를 강조 표시하고
anything this is exactly the power of copilot
22:35:36
다시 샷을 시작할 수 있습니다. 여기서
now what else we can do with that we can go and highlight part
22:35:40
이 열을 집계로 교체하라고 말할 수 있습니다.
of our codes and then start again the shots and here we can
22:35:43
이 열을 집계로 바꿉니다
say replace this column with an aggregation
22:35:46
셀을 집계로 바꿉니다
of the cells so
22:35:49
이제 확인을 클릭하세요. 보시다시피, 집계로 교체되었습니다
let's go and hit okay now as you can see it's replaced it with an
22:35:53
집계 함수와 코드가 매우 중요합니다
aggregate function and one thing that is very important the code
22:35:56
아직 변경되지 않았으므로 강조 표시되고 있습니다
is not changed yet so it is highlighted and showing
22:35:59
제안을 드리며, 이제 수락하거나 거부해야 합니다
you a suggestion and now you have to accept it or discard it
22:36:02
거부하면 코드에 아무런 변화가 없지만
if you discard and nothing gonna change in your codes but once
22:36:05
수락하면 원래 코드를 교체합니다
you say accept it's gonna go and replace your original code
22:36:09
이제 그렇게 하면 코드가 교체됩니다
so if you go and do that now your code is replaced
22:36:12
AI 제안으로 교체됩니다. 코파일럿에 대한 또 다른 점은
with the ai suggestion okay another thing about the copilot
22:36:15
코드의 문제를 수정하려고 합니다
it's trying to fix the issues that you have in your codes
22:36:18
예를 들어, 여기 오류가 있습니다. 마우스를 올려보세요
so for example we have here an error if you go and mouse over it
22:36:21
오류를 보기 위해 코파일럿의 메뉴를 볼 수 있습니다
you can see a menu from the copilot in order to view the error
22:36:24
오류를 수정하기 위해 오른쪽 클릭하면
or to fix it and another way to do that if you right click on
22:36:27
코파일럿으로 이동하면 볼 수 있습니다
it you go to the copilot and here you can see we can
22:36:31
설명하거나 수정할 수 있습니다. 설명하면 새로운 창이 열립니다
explain or fix so if you go and explain you will get another window
22:36:34
코드의 문제에 대한 설명을 얻고 이해하면 수정 요청할 수 있습니다
where you get an explanation about the issue in your code and once you understand it you can go and ask the copilot in order to fix it so let's go over here and go to fix
22:36:45
코파일럿이 문제를 수정했습니다. 선택 문장의 순서에 관한 것이었습니다
and with that the copilot did fix the issue it was all about the
22:36:48
먼저 그룹화한 후 정렬해야 합니다
order of the select statements so first you have to do the group by
22:36:51
문제를 찾고 수정하는 데 도움이 됩니다
then the order by so it helps you to find issues and to fix
22:36:54
코드를 작성하고 비주얼 스튜디오와 상호작용할 때
it as well and now as you might already notice as we are writing
22:36:57
작은 노란색 반짝임을 자주 보게 됩니다
the code and interacting with the visual studio you
22:37:01
왼쪽에 아이콘이 보일 것입니다. 코파일럿이 도와줄 수 있다고 생각할 때마다
will often get a sparkle this little yellow sparkle
22:37:04
클릭하면 코파일럿이 할 수 있는 다양한 메뉴가 나타납니다
on the left side so you will see this icon each time the copilot thinks it can help so if you go and click on it
22:37:10
수정, 설명, 변경 등을 포함하여 여러 가지를 할 수 있습니다
you will get a menu of different stuff that the copilot can do for
22:37:13
당신은 수정, 설명, 수정 등을 좋아합니다.
you like fixing explaining modifying and so on well
22:37:16
친구들, 이게 바로 코파일럿입니다.
my friends that's it this is the copilot and
22:37:19
매우 간단하지만 개발자에게는 매우 강력합니다.
it is very simple but yet very powerful for developers
22:37:23
SQL뿐만 아니라 파이썬과 같은 모든 것에 대해 그렇습니다.
and of course not only for sql for anything like for python
22:37:26
모든 것이 한 곳에 통합되어 있어, 샤GPT로 이동하여 질문할 필요가 없습니다.
and so on everything is integrated in one place i don't have to
22:37:29
이제 SHAGBT 프롬프트의 구조와 기본 구성 요소를 이해하는 것부터 시작하겠습니다.
jump to shagpt and ask stuff it is live and i can do it directly as i'm writing my codes so that's all for copilot all right friends so now Now let's switch to SHAGBT.
22:37:39
첫 번째 구성 요소이자 가장 중요한 것은 작업입니다.
So let's start first by understanding the structure and the basic components of SHAGBT prompts.
22:37:49
AI가 무엇을 해야 하는지 명확히 정의해야 합니다.
So the first component and the most important one, we have the tasks. You have to be very clear by defining what the AI should do.
22:37:56
명확한 작업이 없으면 AI는 무엇을 해야 할지 이해하지 못합니다.
And without having a clear tasks, the AI will not understand what to do. So this is mandatory in each prompt.
22:38:03
그 후에는 약간의 맥락을 제공해야 합니다.
And then after that, you have to provide some context.
22:38:06
예를 들어, 나는 학생이거나 데이터 엔지니어라고 말하는 것입니다.
So you give some background information like for example you say I am student or I am a data engineer and so on.
22:38:13
또 다른 구성 요소는 사양을 추가하는 것입니다.
And another component we have to add specifications.
22:38:16
주제 추가 또는 제외, 단어 수와 같은 세부 사항을 포함합니다.
So in the task you give the main task what the AI should do but with the specifications you go in details.
22:38:22
여기서 많은 요구 사항과 세부 사항을 지정하여 기대에 부합하는 답변을 얻습니다.
Like for example which topic should be added or maybe excluded, the number of word counts.
22:38:28
맥락과 사양 모두 중요합니다.
So here you are specifying a lot of wishes and small details and specifications in order to get an answer that meets your expectations.
22:38:36
그 후에는 규칙을 지정하는 것과 같은 추가 구성 요소가 있습니다.
So both of the context and specifications, they are important.
22:38:39
여기서 AI에게 규칙을 주는 것입니다.
And then after that, we have some nice to have components like, for example, specifying a rule.
22:38:44
AI에게 전문가, 교사, 면접관으로 행동하라고 지시합니다.
So here you give the AI a rule, like, for example, you tell it to act as an expert, as a teacher, interviewer.
22:38:51
AI가 역할을 수행하도록 설정하고 마지막 구성 요소는 톤입니다.
So you are setting the AI to play a rule. And the last component that you can add is as well the tone.
22:38:58
답변의 목소리를 정의하여 더 친근하고 읽기 쉽고 매력적으로 만듭니다.
Here you are defining like the voice of the answer in order just to make the answer like more friendly and easy to read and engaging.
22:39:05
규칙과 톤은 선택 사항이며, 모든 구성 요소를 사용하면 더 나은 결과를 얻을 수 있습니다.
So the rule and the tone they are nice to have and if you go and use all those components you will get a better result from the AI.
22:39:13
예를 들어, 다음 프롬프트를 사용해 보겠습니다.
So let's take for example the following prompts explain SQL window functions.
22:39:18
매우 간단하고 짧으며 여기에는 작업이라는 구성 요소만 있습니다.
So this is very simple and very short and here we have only one component the task.
22:39:23
데이터 분석을 위한 것인지 데이터 엔지니어링을 위한 것인지 맥락을 제공하지 않습니다.
So you are not giving any context whether it is for data analytics or for data engineering.
22:39:28
AI에게 맡기면 기대에 미치지 못하는 답변을 받을 수 있습니다.
So you leave it up to the AI and maybe the answer that you will get will not meet the expectation that you have.
22:39:34
이제 원하는 방식으로 형성하고 싶다면 더 많은 요소를 추가해야 합니다.
And now if you want to shape it in the way that you want, you have to add more components.
22:39:38
예를 들어, 이 프롬프트는 당신이 고급 SQL 전문가라고 말하고 있습니다.
Like for example, this prompt you are saying you are senior SQL experts.
22:39:42
여기서 우리는 AI의 역할을 정의하고 있습니다. AI는 이제 SQL 전문가로 행동해야 합니다.
So here we are defining the role for the AI. So the AI should act now as an SQL expert.
22:39:49
다음 섹션에서는 프롬프트에 대한 맥락을 추가하고 있습니다.
And then the next section, we are adding a context to the prompts.
22:39:52
우리는 SQL 서버를 사용하여 SQL 프로젝트에서 일하는 데이터 분석가라고 말하고 있습니다.
So we are saying I'm data analyst working on SQL projects using SQL server.
22:39:57
이제 AI로부터 받을 답변은
So now the answer that you will get from the AI
22:40:00
SQL 서버의 구문을 사용하고 분석 주제에 집중할 것입니다.
gonna use the syntax of the SQL server and focus on
22:40:03
그래서 우리는 프롬프트에서 주요 작업을 지정합니다.
the topic of analytics that's why the context is very important
22:40:06
작업은 SQL 윈도우 함수의 개념을 설명하라고 말합니다.
and then we go specify in the prompt the task the main
22:40:09
그리고 다음을 수행하고 이제 우리는 더 세부적인 내용을 제공합니다.
task so we say explain the concept of SQL window functions
22:40:12
AI가 제공해야 할 내용에 대한 세부 사항입니다.
and do the following and now we go and give more fine
22:40:16
각 윈도우 함수를 설명하고 구문을 보여주라고 말하고 있습니다.
details about what the AI should provide we
22:40:19
그들이 중요한 이유와 사용 시기를 설명하고 상위 세 가지 사용 사례를 나열하라고 말하고 있습니다.
are saying explain each window function and show the syntax describe
22:40:23
그 후에는 설명의 톤을 지정하는 것이 좋습니다.
why they are important and when to use them and list the top three use cases so you are are now specifying what you are expecting from the AI.
22:40:31
그래서 우리는 톤이 대화식이고 직접적이어야 한다고 말합니다.
And after that, of course, it is nice to have we specify the tone of the explanation.
22:40:37
당신은 매력적인 내용을 읽고 있습니다. 이 프롬프트는 정말 길지만 여전히 개념을 설명하는 것보다 훨씬 더 나은 결과를 얻을 수 있습니다.
So we say that tone should be conversational and direct as if you are speaking to me one to one so that it is not like you are reading a document.
22:40:45
그래서 이것들은 제가 보통 대화와 논의를 시작할 때 사용하는 주요 요소들입니다.
You are reading something that is engaging. So I know this prompt is really big, but still you will get way better results than only saying explain the concepts.
22:40:55
다음으로 제가 프로젝트에서 사용하는 자주 사용하는 프롬프트를 보여드리겠습니다.
So those are the main components that I usually use if I'm starting like a conversation and a discussion with the sharegbt.
22:41:06
이제 회사에서 sharegbt를 사용할 때의 주의 사항입니다.
Okay, next I'm going to show you the frequently used prompts that I use in my projects. Now, a little bit awareness about using sharegbt in companies.
22:41:14
새로운 회사에서 일하고 있다면 sharegbt 사용 규칙에 대해 문의하세요.
If you are working in a new company, make sure to ask about the rules of using sharegbt because some companies offer their own chatbots for few security reasons.
22:41:24
규칙을 확인한 후에 바로 chatgpt로 넘어가세요.
So make sure always to check with the rules before jumping
22:41:27
자, 첫 번째 프롬프트부터 시작해봅시다.
immediately to chatgpt all right so let's start with the first prompt
22:41:30
우리는 프로젝트에서 해결해야 할 SQL 작업을 위해 chatgpt를 사용할 수 있습니다.
we can use chatgpt in order to solve an sql
22:41:33
먼저 맥락부터 시작합니다. chatgpt에게 제가
task that you have in the project so let's see these prompts it
22:41:36
SQL 서버 데이터베이스가 있고 두 개의 테이블이 있다고 말하고 있습니다.
start first with the context so i'm telling chatgpt that i
22:41:39
SQL 서버 데이터베이스가 있고 두 개의 테이블이 있습니다.
have an sql server database and we have like two tables
22:41:43
이제 ChatGPT에게 데이터베이스를 설명해야 합니다.
so now i have to explain for chatgpt the database that
22:41:46
주문이라는 테이블이 있고 다음과 같은 열이 있습니다.
i have so i'm saying we have a table called orders and we
22:41:49
고객이라는 또 다른 테이블이 있습니다.
have the following columns and we have another table called customers
22:41:52
고객에 대한 열을 소개하겠습니다.
and here are the columns for the customers so that i give
22:41:55
내 데이터베이스에 있는 테이블에 대한 맥락을 제공합니다.
sharegbt a context about the tables that i have in
22:41:58
SQL 서버입니다. 이제 맥락이 생겼으니 다음 단계는
my database and as well i was precise about the database
22:42:02
SQL에게 무엇을 해야 할지 말할 것입니다.
it is sql server now after we have the context the next
22:42:05
다음 작업을 수행하십시오. 고객을 순위 매기는 쿼리를 작성하십시오.
step is that i'm going to tell sql what to do so i'm telling the ai
22:42:08
판매를 기준으로 고객을 순위 매기고, 출력에서 기대하는 내용을 자세히 설명합니다.
do the following write a query to rank customers
22:42:11
쿼리만으로는 충분하지 않습니다. 주석도 원합니다.
based on their sales and then i'm detailing what i'm expecting to have at the output so the result should include customer id full name country total sales and so on and here I'm adding like more tasks.
22:42:22
주석을 포함하되, 명백한 부분에 대한 주석은 피하십시오.
It's not enough to have a query. I would like as well to have a comments So
22:42:26
주석을 포함하라고 하면 불필요한 주석이 많아질 것입니다.
I'm saying include comments, but avoid commenting and
22:42:29
물론, 주석을 포함하라고 하면 불필요한 주석이 많아질 것입니다.
obvious parts because if you tell shagipati just include comments You
22:42:33
이제 불필요한 댓글이 많이 달릴 것이다. 물론 정사각형에서.
will get a lot of unnecessary comments now Of course in square
22:42:36
항상 같은 결과를 달성하는 다양한 변형이 있습니다.
there is like not one solution for a task There is
22:42:39
그래서 보통 내 옵션을 이해하고 싶습니다.
always like different variants on how to achieve the same
22:42:42
AI에게 이 버전을 평가하고 두 가지에 집중하도록 작업을 줍니다.
task So usually I would like to understand what are my options That's why I'm telling shagipati write three different versions of the query to achieve this task And then I would like to evaluate each of those versions.
22:42:53
읽기 쉽고 성능이 좋습니다. 자, Shadgpity가 어떤 결과를 줄지 봅시다.
And that's why I'm giving the task for the AI to evaluate those versions and to focus on two things.
22:42:59
여기에서 첫 번째 솔루션을 볼 수 있습니다.
It is easy to read and as well has good performance. Okay. So let's see what Shadgpity gonna give us other results.
22:43:05
여기 CTE에서 테이블이 먼저 조인됩니다.
So we can see the first solution over here where Shadgpity is using the CTE.
22:43:10
그런 다음 판매를 집계하기 위해 그룹화가 있습니다.
So we can see in the CTE over here that the table first are joined.
22:43:13
2단계에서는 여기에서 순위 창을 볼 수 있습니다.
And then we have like a group by in order to aggregate the sales.
22:43:17
판매를 순위 매기기 위한 함수가 있습니다.
step two we can see over here we have the rank window
22:43:21
그렇게 할 수 있습니다. 두 번째 버전을 확인해 봅시다.
function in order to rank the sales so of course
22:43:24
버전 번호 두 개를 확인해 보겠습니다.
you can do that let's check the version number two over
22:43:27
여기서 서브 쿼리를 사용했습니다.
here so they i used the sub query and
22:43:30
먼저 데이터를 준비하고 집계를 수행한 후 데이터를 조인합니다.
it is as well a nice solution where the shadipity
22:43:34
윈도우 함수를 사용하는 쿼리입니다.
first prepared the data so first done the aggregation before joining the data let's get the last solution over here so we have here single
22:43:43
가장 작은 쿼리입니다. CTE가 없습니다.
query using window function which is as you can see it is
22:43:46
서브 쿼리가 없으므로 테이블을 조인합니다.
the smallest one we don't have ctes we don't have any
22:43:49
그룹 바이를 윈도우 함수와 함께 수행합니다.
sub queries so first it is joining the tables and
22:43:52
그 후 평가를 받습니다.
doing together the group by together with the window function
22:43:56
AI는 두 가지에 집중합니다.
and after that we get an evaluation from the
22:43:59
가독성과 성능입니다.
ai where as you can see it focuses on two things the
22:44:02
가독성이 정말 높습니다.
readability and the performance so it is saying with the cte
22:44:05
서브 쿼리와 마지막 버전과 비교할 때.
the readability is really high compared to the
22:44:09
서브 쿼리와 그룹화가 있는 마지막 버전으로
sub query and to the last version where you have the group by
22:44:12
첫 번째 버전이 가독성 면에서 가장 좋았습니다.
together with the window function so i totally agree with the sharegbt the
22:44:15
성능을 확인하면 성능이 보통입니다.
first version was the best one for the readability now
22:44:18
두 번째 서브 쿼리가 좋고 마지막 것이.
checking the performance you can see the performance is moderate the
22:44:22
성능 면에서 가장 좋습니다.
second one the sub query is good and the last one is the
22:44:25
계획이 있습니다. 가독성과 성능 간의 균형이 있습니다.
best for the performance but of course always this with the execution
22:44:28
가독성과 성능 간의 균형이 있습니다.
plan so as you can see there is like a trade-off between the
22:44:31
가독성이 우선이라면 첫 번째 버전을 선택하세요.
readability and the performance if the priority is readability
22:44:34
세 번째 버전으로 가세요. 세 가지 솔루션이 있습니다.
then go with the version one but if the priority is the performance then go with the version three as you can see we got three
22:44:41
하나의 작업에 대한 솔루션입니다.
solutions for our one task and you can now evaluate which one you want to use and this is really amazing right?
22:44:47
다음으로 자주 사용하는 것을 넘어갑니다.
Alright moving on to the next one that I frequently use we have imprompt to improve the readability.
22:44:53
복잡한 작업을 위한 SQL 쿼리를 작성할 때입니다.
As you are creating an SQL query for a complex task
22:44:56
많은 CTE와 서브 쿼리를 작성하게 될 수 있습니다.
you might end up writing a lot of CTEs sub queries
22:45:00
조인 서브 쿼리가 많아질 수 있습니다
you might end up having a lot of joins sub queries
22:45:03
CTE가 수백 줄이 될 수 있고
ctes hundreds of lines and you might
22:45:06
전체적인 그림을 잃을 수 있습니다. 그래서 제가 항상 하는 것은
lose the big picture so what i always do i give
22:45:09
쿼리를 Chat GPT에 주고 최적화를 요청하는 것입니다
the query to the chat gpt and ask it to optimize it in
22:45:12
더 읽기 쉽게 하고 중복성을 찾기 위해서입니다
order to be more readable and to find any redundancy
22:45:15
제 쿼리를 통합하기 위해서입니다. 이제 프롬프트를 확인해 봅시다
in my query in order to consolidate it so now let's
22:45:18
프롬프트에는 다음 SQL 서버 쿼리가 길고
check the prompt it says the following sql server query is long
22:45:22
이해하기 어렵다고 나와 있습니다. 그리고 AI에게 작업을 줄 것입니다
and hard to understand and then we're gonna give the ai tasks
22:45:25
첫 번째 작업은 가독성을 향상시키는 것입니다
so the first task is to improve its readability and
22:45:28
다음 작업은 코드에서 중복성을 감지하는 것입니다
the next one is to detect any redundancy in the code
22:45:32
제거하고 쿼리를 통합하기 위해서입니다
in order to remove it and to consolidate the query so
22:45:35
쿼리를 간결하고 작게 만들고 물론
to make our query compact and small and of course to include
22:45:38
일부 주석을 포함하고 명백한 부분에는 주석을 달지 않는 것입니다
some comments and not to comment the obvious parts and
22:45:41
항상 최적화가 있다면 학습 과정이 있어야 합니다
now always if there is like some optimizations there should be
22:45:44
그래서 AI에게 각 개선 사항을 설명해 달라고 요청하고 있습니다
a learning process so i'm asking now the ai to explain
22:45:47
그 이유를 이해하기 위해서입니다. 그래서 다음 번 쿼리를 작성할 때
each improvement to understand the reasons behind it
22:45:51
그런 실수를 피할 수 있습니다. 물론 쿼리를 AI에게 주어야 합니다
so that's next time i'm writing the queries i can avoid
22:45:54
좋습니다. 이제 Chat GPT의 답변을 확인해 봅시다
those mistakes and of course you have to go and give the query to
22:45:57
프롬프트에 대한 답변입니다. 보시다시피 정말 긴 쿼리가 있습니다
the ai all right so now let's check the answer from the chat
22:46:00
결과에서 이제 개선된 쿼리를 확인할 수 있습니다
gpt for my prompt so as you can see we have a really
22:46:03
우리는 단 하나의 도시만 있습니다. 정말 놀랍습니다
long query and here we have now from the result
22:46:06
이전에는 다섯 개, 여섯 개의 도시가 있었고
the improved query so we can see that we
22:46:09
여기서 볼 수 있습니다
have only one city well that is crazy we
22:46:12
Chat GPT가 모든 것을 하나의 도시로 정리했습니다
had before like five six cities and we can see here
22:46:15
그리고 모든 집계와 윈도우를 수행했습니다
that the chat gpt managed to put everything in
22:46:18
하나의 도시에서 모든 집계를 수행하고
one city and then do all the aggregations and the window
22:46:21
최종 선택을 잘 수행합니다.
function and then we have here the final select well
22:46:25
이전 쿼리에 비해 큰 개선입니다.
this is a huge improvement to the previous query let's
22:46:28
CTE를 통합했다고 설명합니다.
check here the explanation so it says it consolidated the ctes so
22:46:31
모든 도시를 하나로 결합했습니다.
combined all the cities into one and many other stuff like there were a lot of unnecessary
22:46:37
여기서 작은 개선이 있습니다.
joins and so on and here a small improvement where
22:46:40
쿼리가 다섯 개 도시 대신 하나만 사용됩니다.
it uses the concat instead of the plus because concat is standards for multiple databases and here we have a final benefits so we have shorter
22:46:50
로직을 결합하면 스캔 수를 줄일 수 있습니다.
query instead of five cities we have only one and
22:46:53
테이블의 스캔 수를 줄일 수 있습니다.
combining the logic you're gonna reduce the number of scans of
22:46:56
AI가 내 코드의 문제를 찾아 개선했습니다.
the tables which is correct so as you can see it is the magic
22:46:59
가독성을 높이고 중복을 줄였습니다.
of the ai it found the issues in my code improved
22:47:02
불필요한 조인 등을 제거했습니다.
the readability and reduced all the redundancy and
22:47:05
다음 프롬프트로 넘어가겠습니다.
unnecessary joins and so on in the sql scripts
22:47:08
쿼리 성능 최적화에 관한 것입니다.
okay moving on to the next prompt it is about optimizing
22:47:11
수백만 개의 데이터가 있는 큰 프로젝트에서
the performance of my query and if you are working in
22:47:15
쿼리가 성능을 따르지 않으면 문제가 됩니다.
big projects where you have like millions of data in your tables it's
22:47:18
성능을 위한 모범 사례를 따르지 않으면
going to be an issue if you are writing queries that are not following the
22:47:21
AI와 함께 내 스크립트를 확인합니다.
best practices for performance so that's why i go
22:47:24
성능을 위한 모범 사례를 확인합니다.
and double check with the ai whether my script is following the
22:47:28
성능을 위한 모범 사례는 평소처럼 프롬프트에 있습니다.
best practices for the performance so as usual in the prompt
22:47:31
쿼리가 느리므로 AI에게 작업을 제공합니다.
we have to go and give the context so the following sql server
22:47:34
성능을 개선하기 위한 최적화를 제안합니다.
query is slow and then we start giving the ai some
22:47:37
개선된 SQL 쿼리를 제공해 주세요.
tasks so propose optimizations to improve its performance
22:47:40
그 이유를 항상 이해하고 싶습니다.
and provide me then the improved sql query
22:47:43
다른 방식으로 작성하는 것이 더 좋습니다.
and i would like always to understand the reason why it's
22:47:46
다른 방식으로 작성하는 것이 좋습니다.
better to write it in another way so thus by the next
22:47:49
각 개선 사항을 이해하기 위해 설명합니다.
time i improve while i'm writing the query so explain
22:47:53
우리에게 그리고 마지막에 우리는 쿼리를 제공합니다.
each improvement to understand the reasoning behind
22:47:56
이제 다음 쿼리에 대한 프롬프트를 시도해 봅시다.
us and then at the end we go and give our query okay
22:47:59
이 쿼리에는 많은 나쁜 관행이 있습니다.
so now let's try the prompts on the following query over here so
22:48:02
상관 서브 쿼리를 사용하여 집계하는 것과 같은.
on this query we have a lot of bad practices like for example doing
22:48:05
WHERE 절 안에 많은 함수를 사용하고 있습니다.
aggregations using correlated sub query we
22:48:09
인덱싱에 좋지 않으며 많은 OR 연산자를 사용하고 있습니다.
are using a lot of functions inside the where clause which
22:48:12
여기에도 다시 서브 쿼리가 있습니다.
is not really good for indexing and we are using a lot of
22:48:15
샤기프티가 모든 나쁜 관행을 찾을 수 있는지 확인해 보겠습니다.
or operators and here we have again a sub query so
22:48:19
샤기프티의 결과를 확인해 봅시다.
let's check whether shagipty can find all those bad practices
22:48:22
이제 최적화된 쿼리가 있습니다.
so let's check the results from the shagipty and
22:48:25
조금 더 길지만 더 나은 관행이 있습니다.
as you can see now we have an optimized query it is a little
22:48:28
샤기프티가 쿼리에서 LOWER를 교체했습니다.
bit longer but i think we have here better practices so we have here a lot of changes let's check what shagipty did so first it replaced the lower in the query
22:48:37
WHERE 절에서 함수를 사용하는 것이 좋지 않다고 합니다.
it says us it's not really good to use functions in
22:48:40
함수 없이 다른 상태로 LOWER를 교체했습니다.
the where clause so that the index can work so it's
22:48:44
상관 서브 쿼리를 피하고 있습니다.
replaced the lower with the other status without the function the
22:48:48
대신 LEFT JOIN을 사용하고 있습니다.
next one so it is avoiding the correlated sub
22:48:51
상관 쿼리 없이 테이블을 정상적으로 조인하고 있습니다.
query so instead of that it is using a left
22:48:54
WHERE 절에서 함수를 피하고 있습니다.
join so it is joining the table normally without doing any correlated queries and as well it is avoiding the function here in the
22:49:02
범위를 사용하고 있습니다.
where clouds and instead of that it is using the range using
22:49:05
성능에 더 좋습니다.
between and the next one it is using exist better than
22:49:08
AI를 사용하여 쿼리 성능을 최적화할 수 있습니다.
in which is better for the performance of course so as you can see you
22:49:12
최고의 관행을 따르는 스크립트로 변환할 수 있습니다.
can use the ai in order to optimize the performance of your query
22:49:15
샤기프티의 모든 변경 사항을 맹목적으로 따르지 마십시오.
and to convert it to a script that is following
22:49:18
물론 최선의 방법을 따르며, 제 추천은 항상 제안된 모든 변경 사항을 맹목적으로 따르지 말라는 것입니다. 각 추천을 하나씩 테스트하세요.
the best practices of course my recommendations always don't go blindly with all changes that is suggested from the shagibite always take each recommendation one by one test it
22:49:29
그래서 다음으로 넘어가겠습니다. 흥미로운 내용입니다. 프롬프트를 사용하여 실행 계획을 최적화하고 이해할 수 있습니다.
and evaluate it using your knowledge. Okay, to the next one, it is interesting one, we can use a prompt in order to optimize and understand the execution plan.
22:49:38
현재 실행 계획은 보통 고급입니다. 실행 계획을 이해하고 읽기 위해 많은 노하우와 경험이 필요합니다.
So now the execution plans usually are advanced. So you need a lot of know how and experience in order to understand and read the execution plan.
22:49:47
큰 쿼리가 있다면 흐름과 정확한 문제를 이해하는 것이 정말로 악몽이 될 것입니다.
And if you have a big query, it's going to be really nightmare in order to understand the flow and where is exactly the issue.
22:49:53
하지만 이제 우리는 혼자가 아닙니다. AI 어시스턴트가 이 복잡한 내용을 이해하는 데 도움을 줄 것입니다.
But now we are not alone, we have assistant the AI in order to help us understanding this complex stuff.
22:49:59
우리가 할 수 있는 것은 실행 계획의 스크린샷을 찍고 ChargbD에 업로드하는 것입니다.
So what we can do, we can take a screenshot of the execution plan and upload it to ChargbD.
22:50:04
그리고 우리는 이 이미지를 SQL 서버 쿼리의 실행 계획이라고 말합니다.
And we say the image is execution plan of SQL server query.
22:50:08
이제 우리는 다음 작업을 부여합니다. 실행 계획을 단계별로 설명하세요.
And now we give the following task to say, describe the execution plan step by step.
22:50:13
그 후에 SQL에 성능 병목 현상을 식별하도록 지시할 것입니다. 정확한 문제는 어디인가요?
After that, I'm going to tell SQL to identify the performance bottlenecks. And where is exactly the issue?
22:50:19
내 쿼리를 느리게 만드는 것은 무엇인가요? 이것이 실행 계획을 읽는 가장 어려운 부분입니다.
What makes my query slow? This is of course the hardest part of reading an execution plan.
22:50:24
성능 문제를 식별하면 성능을 개선하고 최적화할 방법을 제안해 달라고 요청할 것입니다.
and once it identifies the performance issues i'm
22:50:27
먼저 실행 계획을 이해하고 문제를 식별한 후 최적화하세요.
gonna ask it to suggest ways to improve the performance and optimize
22:50:30
이제 사진을 업로드하고 AI에 요청한 후 결과를 확인합니다.
the execution plan so first understand the
22:50:33
실행 계획 문제를 식별하고 어떻게
execution plan identify the issues and how to
22:50:36
최적화할 수 있는지 알겠습니다. 사진을 업로드하고 요청한 후
optimize it okay so now after uploading the photo and asking
22:50:39
AI로부터 다음과 같은 결과를 얻었습니다. 이제 실행 계획에 대한 자세한 설명을 볼 수 있으며, 많은 세부 사항이 있습니다. 모든 내용을 다루지는 않겠습니다. 테이블 스캔부터 시작하겠습니다.
the ai we have the following results so now we can see a detailed explanation about the execution plan and there is a lot of details i will not go through everything so we start with the table scans
22:50:51
그 다음 클러스터 스캔과 중첩 루프가 있습니다. 여러 개의
then the cluster scan and the nested loops so we have several
22:50:54
중첩 루프가 있고, 그 다음 집계와 최종 단계가 있습니다.
nested loops and then the aggregation and the final step so
22:50:58
이제 이 SQL이 내 쿼리에 대해 배경에서 무엇을 하고 있는지에 대한 멋진 설명이 있습니다.
that now we have like a nice explanation what this sql
22:51:01
전문가가 아니어도 실행 계획을 이해할 필요는 없습니다.
is doing behind the scenes for my query and you don't
22:51:04
AI에게 이에 대해 물어볼 수 있습니다. 이제 매우 중요한 것은
have to be an expert understanding the execution plan you
22:51:07
병목 현상이 어디에 있는지, 문제가 무엇인지 이해하는 것입니다. 여기서 우리가 가진 것을 살펴보겠습니다. 첫 번째로 테이블이 있다고 가정해 보겠습니다.
can ask the ai about it now what is very important is to
22:51:10
스캔이 있습니다. 이는 정말 나쁜 상황입니다. 즉, 이 테이블 주문
understand where are the bottlenecks what are the problems so let's see what we have here so let's say the first one we have a table
22:51:17
아카이브에는 인덱스가 없다는 것을 의미합니다. 그래서 이렇게 말합니다.
scan which is really bad that means this table the orders
22:51:21
archive does not has any index so it says
22:51:24
테이블 스캔은 테이블에 유용한 인덱스가 부족하다는 것을 나타냅니다.
the table scan indicates a lake of useful index on the table which
22:51:27
엔진이 전체 테이블 또는 행을 스캔하도록 강제합니다.
forces the engine to scan the whole table or rows
22:51:30
현재 매우 중요한 것은 중첩 루프입니다.
and now what is very important is the nested loops
22:51:34
조인에서 큰 테이블이 있는 경우 정말 나쁩니다.
in the joints this is really bad if you have
22:51:37
작은 데이터 세트가 있는 경우 괜찮다고 하지만,
big tables so he is saying it's fine if you have like
22:51:40
많은 행이 있는 경우 정말 문제가 될 것입니다.
small data sets but it's gonna be really problematic if you have many rows so as you can see we are getting more
22:51:46
우리는 실행에서 발생하는 문제에 대한 더 많은 지식을 얻고 있습니다.
knowledge about the issues that we have from our execution
22:51:49
계획과 마지막 단계는 제안입니다.
plan and the last step it is the suggestions so
22:51:53
첫 번째이자 가장 명백한 것은 인덱스를 추가하는 것입니다.
the first one and the most obvious one is to add an index to
22:51:56
주문 아카이브에 비클러스터 인덱스를 추가하는 것입니다.
the orders archive the non-clustered index well if there
22:51:59
인덱스가 전혀 없다면 클러스터 인덱스를 먼저 사용하겠습니다.
is no index at all i would go first with a cluster index
22:52:02
비클러스터 인덱스와 즉시 사용하지 않고,
not immediately with the non-clustered index and then some
22:52:05
다른 최선의 방법도 있지만, 이 방법이 매우 관련성이 있다고 생각합니다.
other best practices but i think this one is very relevant
22:52:08
조인 유형을 변경하여 사용할 수 있습니다.
is to change the join type so you can use
22:52:11
힌트를 사용하여 머지 조인 또는 해시 조인을 사용할 수 있습니다.
the hints in order to use a merge join or a hash
22:52:14
이제 우리는 그것이 어떻게 작동하는지 이해하고 문제를 파악했습니다.
join so now we understand how it works where are the issues
22:52:18
모든 것을 수정하기 위한 제안이 무엇인지입니다.
and what the suggestions to fix it all right the next prompt
22:52:21
복잡한 SQL 쿼리를 작성할 때 디버깅에 관한 것입니다.
is about debugging as you are writing a complex SQL query
22:52:24
실행할 때 데이터베이스에서 오류가 발생할 수 있습니다.
you might get from the database an error when you execute
22:52:27
문제의 근본 원인을 찾는 것이 어려울 수 있습니다.
it and sometimes it is challenging to find the root
22:52:30
첫 번째, 오류 메시지를 설명하십시오.
cause of the issue so we have the following prompts first the context is gonna say the following SQL server query causing this error then we can paste the error message that we are getting and And then we ask the AI to do the following stuff.
22:52:43
그런 다음 AI에게 내 스크립트에서 문제의 근본 원인을 찾도록 요청합니다.
First, explain the error message. So I would like to have better understanding of the error.
22:52:47
문제를 찾은 후 AI에게 수정 방법을 제안하도록 요청합니다.
And then we ask the AI to find the root cause of the issue from my scripts.
22:52:52
물론 프롬프트에 SQL 쿼리를 제공해야 합니다.
And after finding the problem and the issue, we're going to ask the AI to suggest how to fix it.
22:52:57
쿼리를 실행하면 다음과 같은 오류가 발생합니다.
And of course, we have to give in the prompt as well our SQL query. All right. So now I have the following query.
22:53:03
그리고 내가 실행하면 다음과 같은 오류가 발생합니다. sales.order.sales 열이 집계에 포함되어 있지 않기 때문에 선택 목록에서 유효하지 않다고 합니다.
And if I execute it, I'm getting the following error. It says the column sales.order.sales is invalid in the select list because it is not contained in the aggregations and so on.
22:53:14
그래서 지금 무슨 일이 일어나고 있는지 잘 모르겠습니다. AI에게 물어봅시다. ChatGPT가 어떻게 대답했는지 확인해 봅시다.
So I'm not really understanding what's going on. Let's ask the AI about it. So let's check what ChatGPT did answer.
22:53:20
group by를 사용할 때, 선택한 모든 열은 group by에서도 사용해야 합니다.
When you are using group by, every column in the select must be used in the group by as well.
22:53:25
그리고 당신의 쿼리에서 몇 개의 열을 선택하고 있는데, 이 열은 유효합니다. 다른 두 개도 유효합니다.
And it says in your query, you are selecting few columns, which is this one is valid. The other two as well valid.
22:53:32
하지만 우리는 rank 함수 안에 하나가 있습니다.
But we have one inside the rank function.
22:53:35
그것은 유효하지 않습니다. 이제 여기서 더 많은 것을 볼 수 있습니다.
it is invalid okay so now we can see here more
22:53:38
루트 원인에 대한 세부정보가 있습니다. 창을 사용할 때
details about the root cause it is saying when you are using window
22:53:41
rank와 같은 함수는 집계 함수와 직접 작동하지 않습니다.
function like the rank it doesn't directly work with
22:53:44
그래서 그것은 명확하게 나타냅니다.
the aggregate functions so it indicates clearly that
22:53:48
rank 함수 안의 sales는 문제입니다. 그래서 여기서 수정을 봅시다.
the sales inside the rank function is the
22:53:51
우리는 여기에서 sales가 전혀 없기 때문에 여기에 가질 수 없습니다.
issue so let's see the fix over here so since
22:53:54
파트ition에 sales가 없기 때문에, 여기에 대한 수정은 sales의 합계를 사용하는 것입니다.
we don't have here sales at all you cannot have here
22:53:57
수정에 대한 좋은 설명이 있습니다. 그래서 여기에서 볼 수 있습니다.
sales in the partition that's why the fix here is to use the sum of sales because we have it in the select and here you have as well
22:54:05
오류 메시지에 대한 설명이 있습니다. 루트
nice explanation about the fix so you can see here
22:54:08
원인이 정확히 문제가 있는 위치를 가리키고 있습니다.
we have an explanation about the error message the root
22:54:11
수정 사항을 제안하고 수정 사항을 설명합니다. 이것이 바로
cause it's pointing exactly where there's the issue suggesting
22:54:14
코드를 디버깅할 때 해야 할 단계입니다.
a fix and explaining the fix and this is exactly
22:54:17
좋습니다. 다음 프롬프트로 넘어갑니다. AI를 사용할 수 있습니다.
the steps that you have to do if you are debugging a code
22:54:20
내가 SQL에서 얻고 있는 결과를 설명합니다. 때때로 당신은
all right moving on to the next prompt we can use ai to
22:54:24
프로젝트에 있는 SQL 쿼리를 가질 수 있고
explain the result that i'm getting from sql well sometimes you
22:54:27
특정 결과를 얻고 있는 이유를 이해하지 못할 수 있습니다.
might have an sql query that you have in the project and
22:54:30
보통 우리는 맥락부터 시작합니다. AI에게 나는 이해하지 못했다고 말합니다.
you are not understanding why you are getting specific results so
22:54:33
다음 SQL 서버 쿼리의 결과를 이해하지 못했습니다. 그리고 우리는
as usual we start with the context we tell the ai i didn't understand the
22:54:37
AI에게 다음을 하도록 요청합니다. 먼저 분해합니다.
result of the following sql server query and then we
22:54:40
SQL이 쿼리를 단계별로 처리하는 방법을.
ask the ai to do the following first break down
22:54:43
SQL이 쿼리를 처리하는 방법
how sql processes the query step by
22:54:46
단계별로 설명을 듣고 싶습니다
step and as well i would like to get an explanation for each
22:54:50
결과가 어떻게 형성되는지
stage and how the result is formed so
22:54:53
여기서 최적화는 필요하지 않습니다
as you can see here i don't need any optimizations i don't need in the
22:54:56
쿼리를 출력하세요. 설명이 필요합니다.
output any query i just need an explanation and
22:54:59
그런 다음 마지막에 쿼리를 붙여넣게 될 것입니다. 자, 이제 다음 쿼리가 있습니다. 우리는 1과 20 사이의 숫자를 생성하는 재귀 CTE가 있습니다.
then at the end you're gonna go and paste your query Okay, so now we have the following query We have a recursive CTE where we are generating like numbers between 1 and 20
22:55:09
연속 재귀 CTE는 보통 복잡합니다.
Contilu recursive CTEs are usually like complicated
22:55:12
이해하기 어려울 수 있습니다. 그래서 이제 AI에게 물어본 후 이 쿼리의 결과를 이해하는 데 어려움을 겪고 있을 수 있습니다.
to understand So now maybe we are having hard time understanding
22:55:15
우리는 쿼리 구조에 대한 설명을 먼저 받았습니다. 그래서 CTE를 메인 쿼리와 함께 사용하고 있다고 합니다.
the result of this query after asking the AI about it We got the explanation first about the query structure So it says you are using the CTE with the main query.
22:55:24
좋습니다, 하지만 정말 흥미로운 것은 SQL이 이 쿼리를 단계별로 어떻게 실행했는지를 이해하는 것입니다.
Well, OK, but what is very interesting is to understand step by step how SQL executed this query.
22:55:30
그래서 첫 번째 단계는 앵커 쿼리를 실행하러 간다고 합니다. 그래서 우리는 먼저 1을 얻을 것입니다.
So it tells the step one is going to go and execute the anchor query. And that's why we will get first the one.
22:55:36
그리고 다음 단계에서는 재귀 쿼리가 처음으로 실행될 것입니다.
And then the next step, the recursive query going to be executed for the first time.
22:55:40
그래서 현재 값에 1을 더하고 있다고 합니다. 보시다시피, 1 더하기 1은 2가 됩니다.
So it is saying, OK, we are adding one to the current value. So as you can see, one plus one, we will get two.
22:55:46
그리고 두 번째 반복에서는 2 더하기 1, 즉 3이 됩니다.
And then in the iteration two, we will get two plus one, three.
22:55:51
그리고 이 과정은 1에서 20까지의 모든 결과를 얻을 때까지 계속 반복됩니다.
and it will keep repeating this process until we get all the results from 1 to 20.
22:55:56
그리고 여기 재귀 쿼리의 종료에 대한 설명도 있습니다.
And then as well, we have here an explanation about the termination of the recursive query.
22:56:00
그래서 필터가 루프를 벗어나는 방법이라고 합니다. 20에 도달하면 멈출 것입니다.
So it's saying the filter is the way out of the loop. So once we reach the 20, it will stop.
22:56:07
그리고 메인 쿼리에 대한 몇 가지 정보가 있습니다. 이를 통해 SQL이 어떻게 작동하는지, 그리고 왜 이러한 결과를 보는지에 대한 깊은 지식을 얻게 될 것입니다.
And then a few informations about the main query. And with that, you will get a deep knowledge about how SQL works and why you are seeing those results.
22:56:15
이것은 ShareGPT의 정말 놀라운 사용 사례입니다. 자, 친구들, 이제 제가 가장 좋아하는 프롬프트에 대해 이야기하겠습니다.
This is really amazing use case for the ShareGPT. Alright friends, so now we're going to talk about my favorite prompts.
22:56:22
AI를 사용하여 제 코드를 스타일링하고 포맷할 수 있습니다.
So we can use the AI to style and format my code.
22:56:26
이제 복잡한 쿼리를 작성하고 작업을 해결하는 데 모든 것이 올바르고 성능을 위해 최적화되면,
So now once you are done writing a complex query to solve a task and everything is correct and optimized as well for the performance.
22:56:33
이제 코드를 검토하여 스크립트를 스타일링하고 포맷할 시간입니다. 그래서 다음 프롬프트가 있습니다.
Now it's time to go and review your code in order to style and format your script. So we have the following prompt.
22:56:40
다음 SQL Server 쿼리는 이해하기 어렵다고 합니다. 그래서 이제 AI에게 다음을 요청합니다.
It says the following SQL Server query is hard to understand. So now we ask the AI to do the following.
22:56:46
코드를 다시 스타일링하여 읽기 쉽게 만드세요. AI의 다음 작업은 모든 열 별칭을 정렬하는 것입니다.
Restyle the code to make it easier to read. And the next task for AI is to align all the columns aliases.
22:56:52
가끔 코드를 스타일링하고 포맷하기 위해 도구를 사용하면 많은 새로운 줄이 생기는 것을 발견할 수 있습니다.
Sometimes if you are using any tool to style and format your code, you will find that it is bringing a lot of new lines.
22:56:59
그래서 저는 AI에게 말합니다, 간결하게 유지하세요. 불필요한 줄 바꿈을 도입하지 마세요.
So I tell here the AI, keep it compact. Do not introduce unnecessary new lines.
22:57:03
AI의 마지막 작업은 최선의 관행을 따르고 있는지 확인하는 것입니다. 그리고 물론, 마지막에 무엇이 필요합니까?
And the last task for the AI is to make sure it is following the best practices. And of course, what do we need at the end?
22:57:10
우리의 쿼리입니다. 좋아요, 이제 다음 쿼리가 있습니다.
Our query. OK, so now we have the following query.
22:57:13
보시다시피 매우 성가신 쿼리가 있습니다.
and as you can see we have very annoying query where
22:57:16
읽기가 정말 어렵고 그 이유는 형식 때문입니다.
it is really hard to read and that's because the format
22:57:20
정렬에 대해 이야기하고 싶지 않지만, 보시다시피 여기 있습니다.
and the styling of the query is really bad i don't want
22:57:23
소문자와 대문자가 혼합되어 있습니다.
to speak about the alignment and so on but as you can see we have here
22:57:26
키워드에 대문자가 있고, 물론 개발하고 코드를 작성하는 경우입니다.
lower cases we have here uppercase sometimes for
22:57:29
이런 식으로 전달하면 정말 좋지 않으니, shardypt가 이를 어떻게 수정할 수 있는지 봅시다.
the keywords and of course if you are developing and writing codes
22:57:32
보시다시피 이제 제 쿼리가 훨씬 더 보기 좋습니다.
and you are delivering something like this it is really not nice so let's see how shardypt can fix it okay so now after executing the prompt
22:57:39
우선 모든 키워드가 대문자입니다.
as you can see now my query looks way nicer so
22:57:42
우리의 CTE는 읽기 정말 좋습니다.
first of all all the keywords are uppercase and then
22:57:46
여기 충분한 간격이 있고 모든 것이 정렬되어 보입니다.
you can see our ctes are really nice to read we have
22:57:49
정말 좋고, CASE WHEN이 매우 명확합니다.
here enough spacing the alignment of everything looks
22:57:52
여기 충분한 간격이 있고 모든 것이 정렬되어 보입니다.
really nice and the case when is very clear and
22:57:55
읽기 쉬운 주 쿼리가 있습니다.
the main query over here is as well easy
22:57:58
그들은 스타일링과 포맷팅을 훌륭하게 해냈습니다.
to read so they have done wonderful job styling and formatting
22:58:02
제 코드와 여기에서 변경된 내용을 설명합니다.
my code and here you have like explanation what did change so first it is saying okay all the keywords are capitalized
22:58:09
별칭과 열의 정렬 등입니다.
the alignment of the aliases and the columns and so on so
22:58:12
그 덕분에 정말 잘 스타일링된 포맷된 쿼리를 얻었습니다.
with that we got a really nice styled formatted query
22:58:15
다른 사람들과 공유할 수 있습니다.
that we can share with others okay moving on to the next
22:58:18
AI를 사용하여 생성할 수 있습니다.
one we can use ai in order to generate
22:58:21
주석을 추가하는 것과 관련하여, 주석을 생성하는 것은 보통 개발자에게 매우 성가신 일입니다.
the commentations and as well to add comments to my
22:58:24
그리고 물론 이것은 정말 나쁩니다.
code creating the commentations and adding comments to code is usually something very annoying for the developers and sadly i see a lot of developers that they tend to not add any comments or anything to their codes.
22:58:37
다른 개발자를 생각하지 않기 때문입니다.
And of course this is really bad because you are not thinking about other developers that are reading your code.
22:58:46
그리고 이 과정이 귀찮고 시간이 걸리기 때문에 AI의 도움을 받아 이러한 것들을 만드는 속도를 향상시킬 수 있습니다.
And since this process is annoying and takes time, we can use the help of AI to improve the speed of creating those stuff.
22:58:58
다음 프롬프트를 확인해 봅시다. 이 SQL Server 쿼리는 주석과 문서를 연결합니다.
So let's check the following prompt. It says the following SQL Server query links comments and documentation.
22:59:04
우리는 먼저 쿼리의 시작 부분에 전체 목적을 설명하는 주석을 삽입하라고 말하고 있습니다.
So we are saying first insert a leading comment at the start of the query describing its overall purpose.
22:59:11
이것은 일반적으로 하는 일입니다. 우리는 시작 부분에 짧은 설명을 추가합니다.
So this is what you usually do we add at the start a short description
22:59:15
다음 코드에 대해 그리고 필요한 경우에만 주석을 추가해야 하며, 명백한 진술은 피해야 합니다.
about the following code and then it should go and add comments only where clarification is necessary and very important it should avoid obvious statements.
22:59:24
인덱싱과 같아서 과도하게 주석을 달지 마세요.
So it's like indexing don't over
22:59:27
코드에 주석을 달고, 일반적으로 데이터 분석을 위한 쿼리를 생성할 때 비즈니스 규칙과 변환을 설명하는 것이 좋습니다.
commenting your code and usually if you are creating query for For data analytics, it's really good to explain the business rules and transformations that you are doing inside your query.
22:59:37
그리고 쿼리가 어떻게 작동하는지 설명하는 또 다른 문서가 필요할 수 있습니다. 지금은 주석을 추가하라고 요청하고 있습니다.
And maybe another documentation describing how the query works. So for now, we are asking to add comments and the commentations.
22:59:44
물론 쿼리를 추가해야 합니다. 자, 이제 이 프롬프트를 내 쿼리 중 하나에 사용해 보겠습니다. 결과를 확인해 봅시다.
And of course, you have to go and add your query. Okay, so now I just use this prompt to one of my queries. Let's go and check the results.
22:59:51
이제 첫 번째 주석이 가장 중요합니다. 전체 쿼리의 목적을 제공합니다. 그러니 무엇이라고 말하는지 봅시다.
Now the first comment is the most important one because it gives the overall purpose of the whole query. So let's see what it's saying.
22:59:58
이 쿼리는 고객을 식별한다고 말하고 있습니다.
It's saying this query identifies.
23:00:00
총 급여를 기준으로 고객 목록을 제공합니다.
customers based on their total salaries and provide list
23:00:03
총 판매와 할당된 세그먼트가 있는 고객 목록입니다. 고객 세분화가 있습니다.
of customers with their total sales and
23:00:06
우리는 높은 가치, 중간 가치 및 낮은 가치를 가지고 있습니다.
their assigned segments so we have here like customer segmentations
23:00:10
이 주석으로 쿼리의 전체 목적을 알 수 있습니다.
we have high value medium value and low value so
23:00:13
그런 다음 여기와 같은 인라인 주석이 있습니다. 그래서 이렇게 말합니다.
with this comment we have the overall purpose of the query and
23:00:16
각 고객의 첫 번째 도시에서 총 판매를 계산합니다.
then we have the inline comments like here so it says
23:00:19
이제 두 번째 도시에 대해 전체 설명이 있습니다.
it's calculate the total sales for each customer for the first city
23:00:22
세그먼트가 어떻게 구성되는지에 대한 설명이 있습니다.
and now for the second city we have here a full description
23:00:26
물론 고객 세그먼트의 비즈니스 규칙에서 비롯됩니다.
how the segment is builds and this is built
23:00:29
따라서 총 판매가 높은 값은 위에 있습니다.
of course from the business rule of the customer segments
23:00:32
100 이상과 그 사이에 있는 값입니다. 잘, 이것은
so it's say the high values for total sales above
23:00:35
사례 승리는 정말 쉽습니다. 그래서 실제로 읽을 수 있습니다.
like 100 and between and so on well this
23:00:38
사례 승리에서 그러나 복잡한 쿼리가 있는 경우
case win is really easy so actually you can read it from
23:00:41
사례 승리는 정말 쉽습니다. 그래서 실제로 사례 승리의 전체 텍스트를 갖는 것이 좋습니다.
the case win but if you have like complex queries it's
23:00:45
사례의 전체 텍스트를 갖는 것이 정말 좋습니다.
really nice to have the full text of the case win and
23:00:48
그런 다음 주요 쿼리를 추가하면 여기에서 최종 출력을 볼 수 있습니다.
then add the main query you can see here the final output
23:00:51
인라인 주석이 정말 좋습니다.
and the inline comments so as you can see it's really
23:00:54
우리 코드 안에 멋진 주석이 있습니다.
nice comments inside our codes and now the next one we have
23:00:57
비즈니스 규칙에 대한 문서와 같습니다.
like a document about the business rule and i
23:01:00
비즈니스 규칙에 대한 AI와 전적으로 동의합니다.
totally agree with the ai that the business rule is here about
23:01:04
고객 세분화에 관한 것입니다.
the customer segmentations so we have here again
23:01:07
비즈니스 규칙에 대한 짧은 문서가 있습니다.
very nice like short documentations about the business rules
23:01:10
쿼리가 잘 작동하는 방법에 대한 문서입니다.
that we have and then we have another document about
23:01:13
작은 쿼리에는 너무 많습니다.
how the query is working well i think this
23:01:16
문서를 더 짧게 만들도록 요청할 수 있습니다.
is too much for small query we can go and ask the shadow to make
23:01:20
문서를 더 짧게 만들도록 요청할 수 있습니다.
the documentation like shorter so
23:01:23
우리 쿼리에 대한 전체 문서가 있습니다.
as you can see we have a full documentation about our query
23:01:26
비즈니스 규칙에 대한 멋진 주석이 있습니다.
about our business rules and we have really nice comments
23:01:29
전체 프로젝트를 개선하는 것이 매우 중요합니다.
in our code all right now moving on to the next prompt
23:01:32
전체 데이터베이스를 개선해야 합니다.
it is very important to improve the whole
23:01:35
DDL 스크립트를 가져와서 AI에게 전달합니다.
project the whole database so what we're gonna do we're gonna go and
23:01:38
AI에게 데이터베이스 최적화를 요청합니다.
take our ddl scripts and give it to the ai and
23:01:42
여기에서 최적화할 수 있는 많은 것들이 있습니다.
start asking ai to optimize our database
23:01:45
데이터베이스와 함께 최적화할 수 있는 것들입니다.
ddl so here there is a lot of things that you can optimize
23:01:48
다음 SQL Server DDL 스크립트를 최적화해야 합니다.
with the database so let's check this prompt it's gonna say the
23:01:51
AI에게 다음 작업을 요청합니다.
following sql server ddl script has to be optimized and
23:01:55
이름을 확인하도록 요청합니다.
we ask the following task from the ai the first one is
23:01:58
테이블과 열이 많은 데이터베이스에서 작업해야 합니다.
to check the naming so if you have a database where you have a lot of
23:02:01
특정 명명 규칙으로 작업해야 합니다.
tables and columns and so on you should be always working
23:02:04
특정 명명 규칙을 사용하여 항상 작업해야 합니다.
with a specific naming convention so here just to
23:02:07
사용하는 명명이 올바른지 확인하십시오.
make sure that the naming that you are using is correct then
23:02:11
DDL에서 매우 중요한 것은 데이터 유형입니다.
what is very important in ddls is the data type
23:02:14
데이터 유형은 최적화에 매우 중요한 역할을 합니다.
data types plays very crucial role in optimizing
23:02:18
쿼리를 최적화하기 위해 AI에게 데이터를 확인하도록 지시합니다.
your queries so we are telling the ai to check the data
23:02:21
유형이 최적화되었는지 확인하는 것입니다.
types and whether they are optimized as well and now
23:02:24
관계형 데이터베이스를 구축하는 경우 많은 기본 키가 있습니다.
the next point is about the data integrity so if you
23:02:27
그리고 네 개의 키가 있으며 AI에게 무결성을 확인하도록 지시할 수 있습니다.
are building a relational database you will have a lot of primary keys
23:02:30
모든 키의 무결성을 확인할 수 있으며 다음 포인트는 인덱스에 대한 것입니다.
and four keys and you can tell the ai to check the integrity of
23:02:34
사용 중인 전체 인덱스를 확인하도록 AI에게 지시할 수 있습니다.
all those keys the next point is about indexes here
23:02:37
DDL 스크립트에서 누락된 것이 없는지 확인합니다.
you can tell the ai to check the overall indexing that you are using
23:02:40
중복 여부를 확인하는 것도 포함됩니다.
in the ddl scripts just to make sure that we are not missing anything and as well to check whether we have duplicates so it is really great check
23:02:49
마지막 점검은 테이블의 정규화를 확인하는 것입니다.
and the last check is that to check the normalizations of the table to
23:02:52
데이터 모델을 확인하고 제안 사항이 있는지 확인합니다.
check the data model and whether there is like any suggestions about
23:02:55
테이블을 분할하고 정규화하는 것에 대한 제안입니다.
splitting tables and normalizing tables or they
23:02:59
이상한 중복이 있는지 확인합니다.
are like some weird redundancy okay so now what we're
23:03:02
이제 우리는 챗봇에게 최적화를 맡길 수 있습니다.
gonna do we can let the chat bt to optimize the
23:03:05
판매 데이터베이스의 DDL을 최적화합니다.
ddl of the sales db so now we have here the ddl of the customers employees orders and so on and after running it we have the following results so now we have here again
23:03:15
AI가 변경 사항에 대한 주석을 추가하고 있습니다.
the DDL but optimized one and here the AI is
23:03:18
기본 키에 대한 자동 증가를 추가했습니다.
adding comment about the changes so here it added the
23:03:21
부정적인 점수가 아닌지 확인하는 것입니다.
auto incremental for the primary key and here for example
23:03:24
직원에 대한 또 다른 점검입니다.
a check that is not a negative score and
23:03:27
생일이 미래의 날짜가 아닌지 확인합니다.
for the employees here another check to make sure that
23:03:30
생일은 미래의 어떤 것이 아니므로 모든 것들이
the birthday is not something in the future so all those
23:03:34
성별에 대한 유효한 값을 제한합니다.
constraints in order to make sure that the quality of the table
23:03:37
테이블의 품질을 보장하기 위한 제약 조건입니다.
is good and here for the gender it is restricting the valid values that could be used inside this column and many
23:03:44
여기 성별에 대한 유효한 값을 제한하고 있습니다.
other stuff and at the end we have like the key changes
23:03:47
이름 규칙에 대해 이야기하고 있습니다.
so about the naming it's saying that we have to stick with one
23:03:51
여기에서 우리는 파스칼 표기법을 사용하고 있습니다.
naming convention so here it did understand that we are using the
23:03:54
예를 들어, 이 제품은 제품 이름을 호출해야 합니다.
pascal case and for those two columns we have an issue
23:03:57
데이터 유형에 대해 모든 세부 사항을 설명하고 싶지 않습니다.
like for example this product it should call the product name
23:04:00
예를 들어, 가격과 판매를 위해 int 대신 disable을 사용하지 말라고 합니다.
and for the data types i don't want to go in all details so here for
23:04:03
그래서 채팅 GPT가 DDL에 모든 외래 키를 추가했습니다. 좋았습니다.
example it says don't use the int use a disable for the price and sales for the integrity is saying go and add foreign keys i I think for the orders, we don't have any foreign keys that is used in the DDL.
23:04:15
이제 인덱싱에 대해 이야기하겠습니다.
So the chat GPT did go and add all the foreign keys in the DDL. So that was good.
23:04:22
보시다시피, 우리의 DDL에서 많은 최적화를 할 수 있습니다.
And now about the indexing, it says since we have primary keys, we will get automatically the clustered indexing and the foreign keys should get as well an index in order to improve their queries and so on.
23:04:32
프로젝트에서 DDL을 작업하고 있다면 AI에게 최적화할 수 있는 것을 물어보세요.
So as you can see, there is a lot of optimizations that could be done in our DDL.
23:04:37
견고하고 최적화된 DDL을 갖는 것은 쿼리 속도를 향상시킵니다.
So now if you are working on the project and you have a DDL, go ask the AI, what could we optimize? I'm sure you will find something.
23:04:44
이제 AI를 사용하여 SQL 프로젝트에 유용한 사용 사례로 넘어갑니다.
And this is very critical because having a solid and optimized DDL improves, of course, the speed of the queries.
23:04:51
AI를 사용하여 테스트 데이터 세트를 생성하는 것입니다.
All right. So now we come to a very useful use case of using AI for your SQL projects.
23:04:56
쿼리의 논리를 테스트하기 위해 작은 데이터 세트를 갖는 것이 항상 좋습니다.
And that is by using AI to generate test datasets.
23:05:00
때때로 존재하지 않는 논리를 구축하고 있습니다.
It is always really nice to have small datasets in order to test the logic of your query.
23:05:05
데이터베이스에 존재하지 않는 논리를 구축하고 있습니다.
Sometimes you are building a logic that does not exist yet in
23:05:09
시나리오를 테스트할 수 없다면 정말 나쁠 수 있습니다.
your database and of course if you are not able to test the scenario
23:05:12
다음 프롬프트를 확인해 보겠습니다.
that you are developing it can be really bad and it is always very painful process in order to generate a datasets for your code but of course now it is easier because we have the help of AI.
23:05:23
다음 SQL Server DDL 테스트를 위한 데이터 세트가 필요하다고 합니다.
So let's check the following prompt. It says I need the datasets for testing the following SQL Server DDL.
23:05:29
AI에게 다양한 작업을 지정해야 합니다.
And now next we have to specify for the AI different tasks. The first one is we have to define the shape of the datasets.
23:05:36
출력을 어떻게 원하십니까?
So how do you want the output? Do you want it as an insert statement or do you want it as an Excel or a file and so on?
23:05:42
항상 현실적인 데이터 세트를 원합니다.
Now the next specifications, I would like always to have a dataset that is realistic.
23:05:47
작은 데이터 세트를 갖고 싶습니다.
So I would like to always have a dataset that is relevant and realistic, not to get dummy word data.
23:05:53
물론 Chargbt에 데이터 세트의 정확한 크기를 지정할 수 있습니다.
So again, he's like only configurations about the data set. The next configuration is that I would like to have a small data set.
23:05:59
물론, Chargbt에 데이터 세트의 정확한 크기를 지정할 수 있습니다.
Of course, you can go and specify for Chargbt the exact size of your data sets.
23:06:03
100,000행 또는 수백만 행을 원한다고 말할 수 있습니다. 원하는 크기를 정의할 수 있습니다.
You can say I would like to have like 100,000 rows or millions of rows and so on. So you can define the size that you want.
23:06:10
저는 작은 데이터 세트를 원합니다. DDL에 여러 테이블이 있고 그 테이블에 기본 키가 있다면 데이터 세트가 정확해야 합니다.
For me, I would like to have like small data sets. And now what is very important that if you have multiple tables in your DDL and those tables have primary keys and primary keys, the data set should be correct.
23:06:22
AI는 조인할 수 있는 키를 생성해야 합니다. 데이터를 함께 조인하면 이상한 결과를 얻지 않을 것입니다.
So the AI should generate keys that is joinable. So if you go and join data together, you will not get to weird results.
23:06:29
물론, 데이터 세트에 null을 포함할지 여부와 같은 사양을 계속 추가할 수 있습니다.
And of course, you can go and keep adding specifications, whether you want to have nulls or no nulls inside your data sets.
23:06:35
예를 들어, null 값을 도입하지 말라고 말하고 있습니다. 마지막에 AI에 DDL을 제공해야 합니다.
So for example, I'm saying don't introduce any null values. And of course, at the end, you have to go and give the DDL for the AI.
23:06:42
하나의 테이블이거나 전체 데이터베이스일 수 있습니다. 하나의 테이블이나 수백 개의 테이블에 대한 데이터 세트를 생성할 수 있습니다.
It could be one table or the whole database. So you could generate a data set for one table or hundreds of tables.
23:06:49
이제 shagbt에게 이 데이터를 생성해 달라고 요청하고 있습니다.
okay so now i'm asking the shagbt to create this data
23:06:52
두 개의 테이블인 직원과 주문에 대한 세트입니다.
sets for two tables the employees and the orders
23:06:56
결과를 확인해 보겠습니다. 이제 매우 작은 것을 볼 수 있습니다.
let's check the results so now we can see very small
23:06:59
직원 테이블에 대한 멋진 삽입 문이 있습니다.
nice insert statements for the table employees so
23:07:02
여기에는 서로 다른 정보가 있는 다섯 명의 직원이 있습니다.
we have over here like five employees with the different informations
23:07:05
이제 주문 테이블에는 많은 열이 있습니다.
and now for the table orders we have a lot of columns
23:07:08
네 개의 주문이 있으며, 판매원 ID는 직원 테이블에서 가져옵니다.
so as you can see we have four orders and what is very important is that the salesperson id comes from the table employees so as you can see we have two
23:07:17
직원에게 이미 있는 하나와
and one where we have it already in the employees and
23:07:20
여기에는 가짜 주소와 같은 나머지 정보가 있습니다.
the rest of the informations we have like here fake addresses
23:07:23
그것으로 우리는 매우 좋은 테스트를 가지고 있습니다.
and stuff so with that we have a very nice test
23:07:26
데이터 세트를 데이터베이스에 삽입하기 위해
data sets in order to be inserted to our database to
23:07:29
쿼리를 테스트하기 위해 아마도 확장해 달라고 요청할 수 있습니다.
test our queries of course we can go and ask maybe to extend
23:07:33
아마도 네 개의 주문 대신 20개의 주문으로 변경할 수 있습니다.
it maybe instead of only four orders we can go with 20 orders and so on so we can go and change the size of it and here we have some notes about the data itself so it is really amazing we are now generating this data
23:07:45
우리의 DDL을 사용하여, 이제 다음 쿼리가 있습니다.
using our ddls all right so now we have the following query and of
23:07:48
SQL 서버를 사용하고 있다고 가정해 봅시다.
course we are using the sql server and let's say that you are migrating
23:07:51
SQL 서버에서 MySQL로 마이그레이션한다고 가정해 봅시다.
from sql server to mysql so let's ask shagbt
23:07:54
내 코드를 MySQL로 변환해 달라고 shagbt에게 요청합니다.
to convert my code to mysql all right so
23:07:58
실행한 후, 이제 동일한 쿼리가 있지만
after running it as we can see now we have the same query but
23:08:01
mysql에서 is null 대신에 사용하고 있습니다
in mysql so instead of the is null we are using
23:08:04
kawalis와 여기서는 더하기 연산자 대신에 연결을 사용하고 있습니다
kawalis and here we are using the concatenation instead of the plus operator and instead of the get date in mysql we use the now
23:08:12
함수와 마지막으로 여기서 사용하는 것은 상위 10개입니다
function and the last thing we are using here top 10 but
23:08:16
제 스케일에서는 limit 10을 사용하고 있으며 여기서는 매우
in my scale we use limit 10 and here we have very
23:08:19
좋은 설명을 하고 있습니다. 그래서 여러분이
nice explanation about that transition so as you
23:08:22
보시는 것처럼 놀랍고, 만약 여러분이 기업에서 일하고 있다면
can see it is amazing and if you are working on companies
23:08:25
프로젝트에서 이런 일이 발생할 수 있습니다
and in projects this might happen that there is like
23:08:28
하나의 데이터베이스에서 다른 데이터베이스로 마이그레이션을 시작하는 결정
decision to start migrating from one database to another
23:08:32
데이터베이스와 그러면 여러분의 프로젝트는 마이그레이션의 큰 작업을 수행해야 합니다
database and then your project is going to get a big task of migrating the
23:08:35
데이터 마이그레이션, ddl 및 쿼리와
data migrating the ddls and the queries and
23:08:39
모든 것을 포함하여 마이그레이션을 도와주기 위해 공유를 사용하는 것을 정말 추천합니다
everything and i really recommend using the share in order to
23:08:42
마이그레이션을 도와주기 위해 공유를 사용하는 것을 정말 추천합니다
help with the migration otherwise this big task might take a really long time so as you can see this is really amazing how shagipty can improve the speed of your projects
23:08:55
좋습니다. 이제 다음 섹션에서는 사용할 수 있는 프롬프트를 보여드리겠습니다
okay now in the next section i'm going to show you the prompts that you can use
23:08:58
학생으로서 또는 새로운 프로그래밍 언어를 배우고 있다면, shagipty를 사용하여 SQL 코스를 생성하도록 요청할 수 있습니다.
as a students or if you are learning any new programming language okay so the first thing that you can do with shagipty is that you can ask it to generate an SQL course.
23:09:08
그래서 Shagipity에게 프로그래밍 언어를 배우는 여정에서 단계별로 안내해 달라고 요청할 수 있습니다.
So you can ask the Shagipity to guide you step by step on your journey learning any programming language.
23:09:14
AI와 완전히 일대일로 진행하고 싶습니다. 그래서 코스를 만드는 데 있어 충분한 맥락을 제공하는 것이 매우 중요합니다.
And you want to do it completely one-to-one with the AI. So first, it is very important in creating a course is that to give enough context.
23:09:23
예를 들어, 매우 짧습니다. SQL 코스를 생성하고 상세한 로드맵과 아젠다를 요청하고 있습니다.
So in this example, it is very short. I'm saying create an SQL course with a detailed roadmap and agenda.
23:09:29
물론 더 많은 사양을 제공할 수 있습니다. 현재 지식에 대해 이야기할 수 있습니다.
But of course, you can go and give more specifications. You can tell about your current knowledge.
23:09:34
어떤 데이터베이스 유형으로 작업하고 싶은지 지정할 수 있습니다. MySQL, SQL Server.
You can specify which database type you would like to work with MySQL, SQL Server.
23:09:39
AI에게 더 많은 맥락과 세부 정보를 제공할수록 더 나은 결과를 얻을 수 있습니다. 그리고 코스를 구성할 수 있습니다.
So the more context and details you give for the AI, the better results you're going to get. And then you go and configure your course.
23:09:46
예를 들어, SQL 기초부터 시작하여 복잡한 주제로 진행할 수 있습니다.
So you can say, for example, start with SQL fundamentals and advance to complex topics.
23:09:52
또한 초보자 친화적으로 만들어 달라고 요청할 수 있습니다. 주제를 처음 배우는 경우 중요합니다.
And as well, we can say, make it beginner friendly. And it is important if it is the first time you are learning about the topic.
23:09:58
이제 코스의 초점을 형성해야 합니다. 여기서 데이터 분석에 관련된 주제를 포함하라고 말하고 있습니다.
And now we have to shape the focus of the course. Like I'm saying here, include topics that is relevant for data analytics.
23:10:04
SQL은 데이터 엔지니어링, 데이터 분석을 위한 다양한 주제에서 널리 사용됩니다.
Because SQL is widely used in different topics for data engineering, data analytics.
23:10:10
각 코스에서 사용 사례에 집중하는 것이 정말 중요합니다.
And it's really important in each course to focus on use cases.
23:10:14
그래서 우리는 실제 데이터 분석 사용 사례와 시나리오에 집중하라고 말하고 있습니다.
So we are saying focus on real world data analytics use cases and scenarios.
23:10:18
물론, 당신은 당신의 과정에 대한 더 많은 세부 정보를 추가할 수 있습니다. 좋아요, 이제 이 과정을 만들기 위해 Chagivity에 요청했습니다.
And of course, you can go and add more details about your course. Okay, so now I just asked the Chagivity in order to make this course.
23:10:25
이제 우리의 과정의 로드맵과 구조를 살펴보겠습니다. SQL 기초로 시작합니다.
So now let's see the roadmap and the structure of our course. So it starts with the phase one with the SQL fundamentals.
23:10:32
기본 선택, WHERE 절 등으로 시작합니다.
So it starts with the basic select where and so on.
23:10:35
다음 섹션에서는 ORDER BY, GROUP BY, INSERT, UPDATE, DELETE에 대해 이야기합니다. 기본적인 내용입니다.
Then the next section we are talking about order by, group by and insert, update, delete. So the basic stuff.
23:10:40
이제 로드맵에서 두 번째 단계인 중급 SQL을 다룹니다.
Now in the roadmap you get the phase two intermediate SQL.
23:10:44
여기에서는 INNER JOIN, 몇 가지 함수, 텍스트, 날짜 및 CASE 문과 뷰에 대해 이야기합니다.
So here we are talking about inner joins, few functions, about the text, the date and the case statements and views.
23:10:50
이제 세 번째 단계로 넘어가며, 분석을 위한 고급 SQL이 있습니다.
And now to the phase three, we have the advanced SQL for analytics.
23:10:54
여기에서는 윈도우 함수, CTE, NULL 함수 및 몇 가지 변환을 사용한 데이터 정리에 대해 다룹니다.
So we have the window functions, the CTE and data cleaning using the null functions and few transformations.
23:11:01
그런 다음 네 번째 단계로 넘어갑니다. 여기에서 실제 사용 사례에 대해 이야기하기 시작합니다.
Then we go to the phase number four. Here in your roadmap, you start talking about real world use cases.
23:11:07
여기에는 여러 프로젝트가 있습니다. 보시다시피, SQL을 배우기 위한 매우 탄탄한 로드맵입니다.
And here you have like multiple projects. So as you can see, this is really solid roadmap in order to learn SQL.
23:11:13
이제 다음 단계에서 할 수 있는 것은 각 장에 대해 깊이 파고들기 시작하는 것입니다.
And now in the next step, what you can do, you can start deep diving into each of those chapters until SQL to start.
23:11:20
좋아요, 첫 번째 단계와 첫 주에 대한 더 많은 세부 정보를 제공하겠습니다.
OK, with the phase number one, with the week one to give more details. All right.
23:11:24
이제 다음 단계로, SQL 학습을 위한 의제와 로드맵을 갖추면 특정 장과 SQL 개념에 집중할 수 있습니다.
So now the next one, once you have the agenda and the roadmap learning the SQL, now you can go and focus on specific chapters, specific SQL concepts.
23:11:32
이 프롬프트에서는 먼저 맥락을 설명하고 있습니다. SQL 윈도우 함수에 대한 자세한 설명을 원합니다.
So in this prompt, we are saying the context first. I want detailed explanation about SQL window functions.
23:11:39
그 후, 우리는 AI에게 설명의 정확한 구조를 지정하고 있습니다.
And now after that, we are specifying for the AI the exact structure of the explanation.
23:11:44
먼저, 윈도우 함수가 무엇인지 설명해야 하며, 이해를 돕기 위해 비유를 제공해야 합니다.
So first, it should explain what are the window functions and maybe as well to give an analogy in order to understand exactly what is window functions.
23:11:52
그 후, 우리는 왜 윈도우 함수가 필요한지, 언제 사용하는지 설명해야 합니다.
And after that, it should explain why we need them and when to use the window functions.
23:11:57
기본을 이해한 후에는 윈도우 함수의 구문에 대해 배우기 시작할 수 있습니다.
So once you understand the basics, then you can start learning about the syntax of the window functions.
23:12:01
그리고 몇 가지 간단한 예제를 제공해야 합니다.
And it should provide as well a few simple examples.
23:12:05
마지막으로, SQL 함수에 사용되는 가장 좋은 또는 가장 자주 사용되는 사례를 보여줘야 합니다.
And at the end, I should show you the best or the most frequently used cases used for the SQL with the functions.
23:12:12
이것은 제가 새로운 것을 배우기 위해 좋아하는 패턴입니다. 이제 SQL 함수에 대한 설명을 어떻게 할지 봅시다.
So this is the pattern that I like in order to learn something new. All right. So now let's see how they are going to explain the SQL with the functions.
23:12:18
보시다시피, 함수와 함께 SQL 이해라는 제목으로 시작합니다.
So as you can see, it starts with the title understanding SQL with the functions.
23:12:22
여기에는 간단한 정의가 있고, 그 다음에 비유가 있으며, 학생을 평가하는 교사에 대한 비유가 있습니다.
So we have here a quick definition and then we have an analogy and the analogy about like a teacher grading students.
23:12:29
좋습니다, 우리는 랭크 함수가 있기 때문에 좋습니다.
Well, that's nice because we have the rank function.
23:12:33
여기에서 윈도우 함수에 대한 좋은 비유가 있습니다.
so you have here a nice analogy about the window function and
23:12:36
그럼 우리는 윈도우 함수가 왜 필요한지 이해합니다.
then we understand why do we need the window functions well
23:12:39
저는 원시 레벨 세부정보를 얻기 위해 전적으로 동의합니다.
i totally agree in order to have raw level details with
23:12:42
집계 작업을 수행할 수 있으므로 집계를 수행할 수 있습니다.
the aggregations so you can do aggregations while
23:12:45
원시 레벨 세부정보를 유지하면서 복잡한 계산을 할 수 있습니다.
maintaining the raw level details and as well you can
23:12:48
그룹으로 모든 것을 할 수 없기 때문에 이러한 함수로.
do complex calculations because you cannot do everything with a group
23:12:51
윈도우와 함께 작동하는 함수로.
by these functions that only work with the window and then
23:12:54
사용할 때에 대한 설명이 있습니다.
we have some explanation when to use them so we see
23:12:57
여기에서 윈도우 함수의 구문을 예로 들어보겠습니다.
here for example the syntax of the window function so
23:13:01
함수 파티션을 나누고 정렬합니다.
it divided to a function partition order by over and
23:13:04
그에 대한 몇 가지 설명이 있습니다.
here few explanation about that then we have a few simple
23:13:07
쿼리와 함께 몇 가지 간단한 예시가 있습니다.
examples with queries so explaining the
23:13:10
모든 함수에 대한 예시를 확장하도록 요청할 수 있습니다.
different functions but not all of them of course you can go and
23:13:13
윈도우 함수의 상위 세 가지 사용 사례를 볼 수 있습니다.
ask the shagipty to extend the examples for all
23:13:17
SQL 윈도우 함수의 개념에 대한 훌륭한 설명이 있습니다.
functions and now we can see the top three use cases for the window functions so we use it in order to rank the data and as well to build the running totals and the moving average and at the At the end, we have a summary.
23:13:29
이것은 제 프로젝트에서 자주 사용합니다.
So as you can see, we have a wonderful explanation about the concept of the SQL window functions. Okay, moving on to the next one.
23:13:35
프로그래밍에서는 서로 매우 가까운 다양한 개념이 있습니다.
And this one, I use it very frequently in my projects. There is like in programming always different concepts that are very close to each other.
23:13:43
때때로 혼란스럽고 큰 차이가 무엇인지 명확하지 않습니다.
And sometimes it is confusing and not really clear what are the big differences between them.
23:13:47
여기에서 다양한 SQL 개념을 비교할 수 있는 프롬프트가 있습니다.
So here I have for you a prompt in order to compare different SQL concepts.
23:13:52
프롬프트는 SQL 윈도우 함수의 차이를 이해하고 싶다고 말합니다.
So now the prompt says, I want to understand the differences between SQL window functions
23:13:57
그리고 그룹으로, 둘 다 일반적으로 사용됩니다.
and the group by so both of them are used usually
23:14:00
SQL에서 데이터를 집계하는 데 사용됩니다.
to aggregate data in sql and i would like to understand more
23:14:03
둘 사이의 주요 차이를 설명하는 작업을 정의합니다.
what are the differences between them so we define for the ai the following
23:14:06
무엇을 사용할지 이해하는 것이 정말 중요합니다.
task explain the key differences between the two concepts
23:14:09
각 개념을 예시와 함께 설명합니다.
and then it's really important to understand when to use what so
23:14:12
각 개념을 사용할 때의 예시를 설명합니다.
describe when to use each concept with examples and
23:14:16
각 개념의 장점과 단점을 이해하는 것이 정말 좋습니다.
it's really nice to understand as well the advantages and
23:14:19
각 개념의 단점과 마지막에 두 함수 간의 차이를 간단히 요약하고 싶을 것입니다.
the disadvantages of each concept and at the end you would like maybe to get a quick summarization about the differences between those two functions
23:14:26
한 표에 나란히 배치하여 보겠습니다.
side by side in one table okay so now let's see how the
23:14:29
이 두 개념의 차이를 보기 위한 표입니다.
share gpd can compare those two concepts so first we have really nice
23:14:33
예를 들어 출력 세분화는 다음과 같습니다.
table in order to see the differences between those two so for
23:14:36
윈도우 함수는 원시 수준의 세부 정보를 제공합니다.
example the output granularity it says the
23:14:39
그룹별로 집계된 결과를 제공합니다.
window function provides calculation at the raw level details where
23:14:43
함수에 대해 이야기할 때 순위, 누적 합계, 이동 평균을 허용합니다.
the group by provides aggregated results at the group
23:14:46
이것은 차이에 대한 훌륭한 개요입니다. 그런 다음
level detail and if you are talking about the functions it allow ranking running total moving average and the group by it allows only the basic aggregations like some average count.
23:14:56
어떤 개념을 언제 사용할지에 대한 것입니다.
So this is really nice overview for the differences. Then
23:14:59
윈도우 함수는 원시 수준의 세부 정보를 원할 때 사용됩니다.
we have when to use which concepts so it's telling
23:15:02
여기에서 좋은 예시를 볼 수 있습니다.
the window function it is used if you want raw level details together with
23:15:06
그룹별로 사용할 수 있는 예시입니다.
the aggregations and here you have like a nice example
23:15:09
데이터를 카테고리로 요약할 때 사용할 수 있습니다.
for the group by it says you can use it for example when
23:15:12
데이터를 지역별로 그룹화할 수 있습니다.
summarizing data into categories like here grouping
23:15:15
각 개념의 장단점이 있습니다.
up the data by the region and then after that we
23:15:18
윈도우 함수의 장점은 모든 행을 가져오는 것입니다.
have like pros and cons for each concept so the advantage of
23:15:22
이해하고 사용하기가 더 쉽습니다.
the window function we get all the rows and for the group i
23:15:25
윈도우 함수의 단점은 더 복잡하다는 것입니다.
it is like easier to understand and to use for
23:15:28
그룹의 단점은 세부 정보를 제거한다는 것입니다.
the disadvantage of the window function it is more complex for
23:15:31
행에 대한 세부 정보를 제거합니다.
the group i the disadvantage is it removes the details
23:15:34
두 개념 간의 나란히 비교입니다.
about the rows and at the end we have like side by side comparison
23:15:38
두 SQL 개념 간의 전체 세부 비교입니다.
between those two concepts so as you can see we have really nice
23:15:41
AI와 함께 SQL을 연습하는 것은 단순히 읽는 것으로는 충분하지 않습니다.
full detailed comparison between those two sql concepts practicing sql with the ai well it is really not enough to just read about
23:15:50
무언가 또는 코스를 따라가고 시청하기 위해
something or maybe to follow and watch a course in
23:15:53
무언가를 배우기 위해 항상 연습해야 합니다
order to learn something you have always to practice and
23:15:56
새로운 프로그래밍 언어를 연습하기 위해 자료를 찾는 것이 정말 어렵습니다
of course it is really hard to find a materials in order to
23:15:59
새로운 프로그래밍 언어를 연습하기 위해 이렇게 할 수 있습니다
practice a new programming language so we can do it like this
23:16:02
SQL 트레이너 역할을 하는 규칙을 제공합니다
we give a rule act as an sql trainer and
23:16:06
그런 다음 SQL 연습을 도와달라고 요청하는 맥락을 설정합니다
then a context where we say and help me practice sql
23:16:09
윈도우 함수와 이 훈련을 구성합니다
window functions and then we go and configure this training
23:16:12
다음과 같이 이 연습을 진행하여 AI가 작업을 제공하도록 합니다
this practice by doing the following we tell it to make it interactive practicing so the ai provide a task
23:16:18
해결책을 제시하고 중요한 것은
and you give a solution and what else is important is that it
23:16:21
간단한 데이터 세트를 제공합니다
provides you a simple data set and of course you can specify
23:16:24
원하는 데이터 세트가 산업 데이터인지
which data set you want is it industrial data
23:16:28
의료 데이터인지 또는 원하는 것이 무엇인지
set or healthcare or anything you want and then we tell
23:16:31
AI가 점진적으로 증가하는 SQL 작업을 제공합니다
the ai give sql task that's gradually increase in
23:16:34
기본부터 시작하여 고급까지 진행합니다
difficulty so we start with the basics until getting advanced
23:16:37
작업을 수행하고 AI에게 SQL 서버 역할을 하도록 지시할 수 있습니다
tasks and you can tell the ai to act as an sql server and show the results of your query so you would like to get as a result not only the correct
23:16:46
정확한 해결책이나 피드백을 보고 싶습니다
solution or feedback you want to see the result of the
23:16:49
쿼리의 결과를 보고 AI가 검토하도록 합니다
query that you gives and then finally the ai should go and review
23:16:52
쿼리에 대한 피드백을 제공하고 개선 사항을 제안합니다
your queries provide a feedback and suggest improvements
23:16:55
좋습니다, 이제 연습을 시작합시다
okay so now let's start practicing i gave the prompt
23:16:58
간단한 데이터 세트를 가지고 있습니다
to chatgbt and now we have simple data
23:17:01
판매 ID, 직원, 지역, 판매 날짜 및 금액이 있습니다
sets so it is very simple we have the sales id employee
23:17:04
첫 번째 작업이 있습니다
region sales dates and amounts and then we
23:17:07
직원들의 총 판매량에 따라 순위를 매기는 쿼리를 작성하라고 합니다
have the first task so it says write a query to rank employees by their total sales so here you have like an example
23:17:15
이제 당신의 차례입니다
output and now it says your turn so the
23:17:18
샤르딥이 당신의 답변을 기다리고 있습니다
shardip is waiting for your answer okay so now i just prepared
23:17:21
쿼리를 준비했어요. 어떤 일이 일어날지 보죠.
a query for it let's see what can happen once
23:17:24
게시했더니 쿼리에서 오류가 발생했어요.
i post it oh no i got some errors in the query
23:17:27
집계에서 오류가 발생했다고 하네요.
so let's see what we have so it says error in the aggregations
23:17:30
판매 대신 금액을 사용해야 해요.
you should use the amount instead of sales
23:17:33
불필요한 파티션이 있다고 하네요.
and it says unnecessary partition by in the
23:17:37
그래서 올바른 쿼리를 확인해 보죠.
rank and so on so let's check the correct query so we have here the group by and then we have to do the window function without
23:17:45
파티션을 사용하지 않는 창 함수가 필요해요.
using partition pi so that was a mistake and
23:17:48
이 쿼리의 결과는 이거예요.
the result of this query gonna be this one and here i have really
23:17:51
첫 번째 작업에 대한 좋은 피드백을 받았어요.
nice feedback about the first task so now it asked
23:17:54
다음 작업에 대해 물어봤어요.
me about the next task so i'm gonna say yes so now
23:17:57
두 번째 작업에 대해 이야기해 보죠.
we have the task number two about the running total we have a task
23:18:00
데이터가 있으니 쿼리를 작성해야 해요.
and we have the data and we have now to write a query
23:18:03
작업을 해결하기 위해 쿼리를 작성해야 해요.
in order to solve the task so my friends it is nice right interactive and not only scale you can go and practice any programming language now moving on
23:18:11
마지막 프롬프트로 넘어가죠.
to the last prompt you can use ai in order to prepare
23:18:15
SQL 면접 준비를 할 수 있어요.
you for sql interview so let's say that you
23:18:18
면접에 초대받았다고 가정해 보죠.
are invited to an interview and you would like to prepare yourself for
23:18:21
AI와 함께 빠르게 준비할 수 있어요.
it so you can do a quick preparation together with the ai so
23:18:24
면접관 역할을 하라고 말할 수 있어요.
you can say the following act as interviewer and prepare me for
23:18:27
SQL 면접을 준비할 수 있어요.
sql interview and now you can go and configure the interview
23:18:30
일반 SQL 면접 질문을 요청할 수 있어요.
where you can say ask common sql interview questions and make it interactive so it provides a question and then wait for you to
23:18:38
기본부터 고급까지 진행할 수 있어요.
answer and then you can say gradually progress to advanced topics
23:18:42
답변을 평가하고 피드백을 줘요.
so from basics to advanced and it is very important that
23:18:45
면접 준비에 정말 좋은 방법이에요.
it evaluates your answer and give you a feedback so
23:18:48
정말 추천해요. 준비할 수 있어요.
it is a really great way to prepare for interviews and
23:18:51
SQL 면접뿐만 아니라 다른 시험도 준비할 수 있어요.
i really recommend it to do it and you can prepare yourself not only
23:18:54
학교 인터뷰를 준비할 수 있을 뿐만 아니라
for an escolar interview you can prepare yourself for an escrow exam
23:18:57
에스크로 인터뷰를 준비해 보겠습니다. 여기 첫 번째 질문이 있습니다.
okay so now let's prepare for an escrow interview and here we have the first question chargbt says what is the
23:19:04
WHERE와 HAVING의 차이점은 무엇인가요?
difference between where and having so now it is waiting for
23:19:07
여기서 WHERE는 데이터를 필터링합니다.
an answer we can say where filters data
23:19:12
집계 전에
before aggregation and
23:19:15
필터 데이터 사용
having filters data
23:19:18
집계 후 답변을 확인해 보겠습니다. 여기에서 매우 확실한 답변의 예를 제공하고 있지만, 일반적으로 저는 답변을 올바르게 했습니다.
after aggregation so let's check the answer so here it is giving me an example of a very solid answer but in general i have answers correctly
23:19:29
그래서 답변이 맞다고 합니다. 하지만 피드백에서는 면접관이 차이점에 대한 한 문장 이상의 더 많은 세부정보를 원할 수도 있다고 합니다.
So it says the answer is correct. But the feedback says here maybe the interviewer like needs more details, not only one sentence about the differences.
23:19:37
그래서 여기서는 저에게 더 많이 말하고 더 많은 세부정보를 제공하라고 격려하고 있습니다. 하지만 여전히 답변은 맞습니다.
So here it is like encouraging me to speak more and to give more details as an answer. But still, the answer is correct.
23:19:44
이제 다음 질문으로 넘어가겠습니다. 여기서 무엇이 있습니까? 내부 조인과 왼쪽 조인 간의 차이를 설명할 수 있습니까? 답을 알고 있기를 바랍니다.
So now let's go to the next question. What do you have here? Can you explain the differences between inner join and left join? So I hope you know the answer.
23:19:52
하지만 보시다시피, 매우 상호작용적이고 좋습니다. 그리고 이러한 질문들은 정말 관련성이 높다고 생각합니다.
But as you can see, it is very interactive and nice. And I think those questions are really relevant.
23:19:56
그래서 누군가를 인터뷰하고 있다면, 저는 이 사람에게 질문할 것입니다.
So if I'm interviewing someone, I'm going to go and ask this person
23:20:00
WHERE와 HAVING의 차이점, 그리고 조인 유형 간의 차이점은 무엇인지요? 정말 놀랍죠?
What is the difference between where and having and as well the differences between the joint types? So this is amazing, right?
23:20:07
인터뷰가 있다면, ChatGPT를 사용하여 스스로 준비하고 연습하는 것을 추천합니다. 인터뷰 전에 스스로 준비할 수 있습니다.
I really recommend you if you have like an interview, go and prepare yourself using chatgpt and you can go and practice and prepare yourself before going to the interview.
23:20:15
좋습니다. 그래서 이를 통해 SQL을 사용하여 코딩할 때 AI를 어떻게 활용하는지 배웠습니다.
All right, so with that, you have learned how I use AI in order to assist me while I'm coding using SQL.
23:20:21
이제 친구들, 우리는 전체 과정에서 가장 중요한 장에 도달했습니다. 여러분은 이제 SQL에 대해 많은 것을 배웠습니다.
And now my friends, we come to the most important chapter from the whole course. you have now learned a lot of things about SQL.
23:20:28
많은 고급 기술, 많은 함수, 데이터를 변환하는 방법, 데이터를 집계하는 방법을 배웠습니다.
A lot of advanced techniques, a lot of functions, how to transform data, how to aggregate data.
23:20:33
하지만 이제 여러분이 해야 할 일은 모든 것을 취하고 SQL 프로젝트에 적용하는 것입니다. 그리고 이러한 프로젝트는 단순한 프로젝트가 아닙니다.
But now what you have to do is to take everything and to apply it in SQL projects. And those projects are not only like easy projects.
23:20:40
산업에서 제가 하는 실제 프로젝트와 매우 유사한 프로젝트를 여러분을 위해 준비했습니다.
I bought projects for you that is very similar to the real project that I do in the industry.
23:20:44
그래서 여러분은 프로젝트를 수행하는 방법만 배우는 것이 아니라,
So you will not learn only like how to do project in
23:20:48
SQL에서, 그리고 주요 단계가 무엇인지, 우리가
SQL, but as well, what are the main steps and how we
23:20:51
실제 세계에서 프로젝트를 어떻게 구현하는지 배우게 됩니다. 여기에는 세 가지가 있습니다.
implement projects in real world and here i have for you three
23:20:54
프로젝트 데이터 웨어하우징, 데이터 탐색 및 고급 데이터 분석. 첫 번째 데이터 웨어하우징 프로젝트부터 시작하겠습니다. 이 프로젝트는 놀라울 수 있습니다. 그래서 깊이 들어가 보겠습니다.
projects data warehousing data exploration and advanced data analytics we're gonna start with the first one the data warehousing projects this one can be amazing so let's go and deep dive in that
23:21:09
좋습니다, 친구들. 이제 SQL을 사용하여 데이터 분석 프로젝트를 하고 싶다면,
all right my friends so now if you want to do data analytics projects using
23:21:12
세 가지 다른 유형의 프로젝트가 있습니다. 첫 번째 유형의 프로젝트는 데이터 웨어하우징입니다. 그것은 전부 어떻게 하는지에 관한 것입니다.
sql we have three different types the first type of projects you can do data warehousing it's all about how to
23:21:18
데이터를 조직하고 구조화하며 준비하는 것입니다.
organize structure and prepare your data for data
23:21:21
데이터 분석의 기초입니다. 모든 데이터 분석 프로젝트의 기초입니다.
analysis it is the foundations of any data analytics projects
23:21:25
다음 단계에서는 탐색적 데이터 분석을 수행할 수 있습니다.
and in the next step you can do exploratory data analysis
23:21:29
EDA에서 해야 할 모든 것은 데이터 세트에 대한 통찰력을 이해하고 다루는 것입니다.
eda and all what you have to do is to understand and cover
23:21:32
이러한 종류의 프로젝트에서 올바른 질문을 하고 답을 찾는 방법을 배울 수 있습니다.
insights about our data sets in this kind of project you
23:21:35
기본 SQL을 사용하여 SQL로 답을 찾는 방법을 배울 수 있습니다.
can learn how to ask the right questions and how to find
23:21:38
기본 SQL 기술을 사용하여 SQL로 답을 찾는 방법을 배울 수 있습니다.
the answer using sql by just using basic
23:21:41
고급 분석 프로젝트를 수행할 수 있으며, 비즈니스 질문에 답할 수 있습니다.
sql skills now moving on to the last stage where you
23:21:44
고급 SQL 기술을 사용하여 비즈니스 질문에 답할 수 있습니다.
can do advanced analytics projects where you're going use
23:21:47
여기에서는 고급 SQL 기술을 사용하여 실제 비즈니스 질문을 해결할 것입니다.
advanced SQL techniques in order to answer business questions like finding trends over time, comparing the performance, segmenting your data into different sections, and as well generate reports for your stack holders.
23:22:00
이제 우리가 할 일은 첫 번째 유형의 프로젝트인 SQL 데이터 웨어하우징을 시작하는 것입니다.
So here you will be solving real business questions using advanced SQL techniques.
23:22:04
먼저 ETL ELT 프로세스를 수행하는 방법을 배울 것입니다.
Now what we're gonna do, we're gonna start with the first type of projects, SQL data warehousing, where you will gain the following skills.
23:22:10
SQL을 사용하여 데이터를 준비하는 방법을 배울 것이며,
So first you will learn how to do ETL ELT processing using
23:22:14
데이터 아키텍처를 구축하는 방법과 데이터 통합을 수행하는 방법을 배울 것입니다.
SQL in order to prepare the data, you will learn as well how to build
23:22:17
여러 소스를 통합하는 방법과 데이터 로드 및 데이터 모델링을 수행하는 방법을 배울 것입니다.
data architecture how to do data integrations where we
23:22:20
여러 소스를 통합하는 방법과 데이터 로드 및 데이터 모델링을 수행하는 방법을 배울 것입니다.
can merge multiple sources together and as well how to do data
23:22:23
커피를 준비하고 프로젝트로 뛰어들어 봅시다.
load and data modeling so if i got you interested grab your
23:22:26
좋습니다, 친구들. 이제 도구와
coffee and let's jump to the projects all
23:22:32
멋진 것들에 대해 깊이 파고들기 전에
right my friends so now before we deep dive into the tools and
23:22:35
데이터 웨어하우스가 정확히 무엇인지, 왜 기업들이 이러한 데이터 관리 시스템을 구축하려고 하는지에 대한 좋은 이해가 필요합니다.
the cool stuff we have first to have good understanding about what
23:22:39
데이터 웨어하우스는 관리자의 의사 결정 프로세스를 지원하도록 설계된 주제 중심, 통합, 시간 변동, 비휘발성 데이터의 집합입니다.
is exactly data warehouse why the companies try to build such a data management system so now the question is what is it at our I will just use the definition of the father of the data warehouse built in one.
23:22:50
주제 중심 데이터 웨어하우스는 항상 판매, 고객, 재무 등과 같은 비즈니스 영역에 초점을 맞춥니다.
A data warehouse is subject oriented, integrated, time variant, and non-volatile collection of data designed to support the management's decision making process.
23:23:01
여러 소스 시스템을 통합하기 때문에 통합됩니다.
Okay, I know that might be confusing. Subject oriented, it means data warehouse is always focused on a business area like the sales, customers, finance, and so on.
23:23:10
하나의 소스뿐만 아니라 여러 소스를 위해 웨어하우스를 구축합니다.
Integrated because it goes and integrates multiple source systems.
23:23:14
시간 변동은 데이터를 유지할 수 있음을 의미합니다.
you build a warehouse not only for one source but for
23:23:17
여러 출처의 시간 변동성을 의미하며,
multiple sources time variance it means you can keep
23:23:20
데이터 웨어하우스 내부에 역사적 데이터를 보관할 수 있습니다.
historical data inside the data warehouse non-volatile
23:23:23
데이터가 데이터 웨어하우스에 들어가면
it means once the data enter the data warehouse it is
23:23:26
삭제되거나 수정되지 않으므로, 이것이 정의된
not deleted or modified so this is how bill in one
23:23:29
데이터 웨어하우스입니다. 이제 귀사의
defined data warehouse okay so now i'm gonna show you the scenario where your company don't have a real data management so now let's say that you have one system and you have like one data analyst has to go to this system
23:23:40
실제 데이터 관리가 없는 시나리오를 보여드리겠습니다.
and start collecting and extracting the data and then he gonna
23:23:43
하나의 시스템이 있고 데이터 분석가가 이 시스템에
spend days and sometimes weeks transforming the
23:23:47
데이터를 수집하고 추출하기 시작해야 합니다.
raw data into something meaningful then once they have
23:23:50
며칠 또는 때로는 몇 주를 데이터 변환에
the reports they're gonna go and share it and this data analyst is
23:23:53
소요하게 됩니다. 원시 데이터를 의미 있는 것으로
sharing the report using an excel and then you have like another
23:23:56
변환한 후, 보고서를 작성하고 공유합니다.
source of data and you have another data analyst that she is
23:23:59
이 데이터 분석가는 엑셀을 사용하여
doing maybe the same steps collecting the data spending a
23:24:03
보고서를 공유하고, 또 다른 데이터 분석가가
lot of time transforming the data and then share at the end like
23:24:06
있습니다. 그녀는 아마도 같은 단계를
a report and this time she is sharing the data using powerpoint
23:24:09
따르고 데이터를 수집하며 많은 시간을
and a third system and the same story but this time he
23:24:12
데이터 변환에 소요한 후, 마지막에
is sharing the data using maybe power bi so now if
23:24:15
보고서를 공유합니다. 이번에는 그녀가
the company works like this then there is a lot of issues first
23:24:19
파워포인트를 사용하여 데이터를 공유하고,
this process it take too way long i saw a lot
23:24:22
세 번째 시스템과 같은 이야기가 반복됩니다.
of scenarios where sometimes it takes weeks and even months
23:24:25
이번에는 그가 아마도 파워 BI를 사용하여
until the employee manually generating those reports
23:24:28
데이터를 공유하고 있습니다. 이제 만약
and of course what can happen for the users they are consuming
23:24:31
회사가 이렇게 운영된다면, 많은 문제가 발생합니다.
multiple reports with multiple state of the data
23:24:34
첫째, 이 과정은 너무 오래 걸립니다.
one report is 40 days old another one 10
23:24:37
저는 많은 시나리오를 보았습니다.
days and a third one is like five days so it's gonna be
23:24:40
때로는 몇 주, 심지어 몇 달이 걸립니다.
really hard to make a real decision based on this structure
23:24:43
수동 프로세스는 항상 느리고 스트레스를 주며
a manual process is always slow and stressful and
23:24:47
프로세스에 더 많은 직원을 참여시키면 할수록
the more employees you involved in the process the more you open
23:24:50
인간 오류와 물론 오류의 문을 열게 됩니다
the door for human errors and errors of course and reports
23:24:53
대량의 데이터를 처리하는 것이 문제입니다
leads to bad decisions and another issue of course is
23:24:57
하나의 출처가 방대한 양의 데이터를 생성하면
handling the big data if one of your sources generating like
23:25:01
데이터 수집이 어려워지고 어떤 경우에는
massive amount of data then the data analyst gonna struggle
23:25:04
더 이상 데이터를 얻는 것이 불가능할 수 있습니다
collecting the data and maybe in some scenarios it will not
23:25:07
전체 프로세스가 중단될 수 있으며 더 이상
be any more possible to get the data so the whole process
23:25:10
신선한 데이터를 생성할 수 없습니다
can breaks and you cannot generate any more fresh data for
23:25:13
특정 보고서에 대해 마지막으로 큰 문제는
specific reports and one last very big issue with that if one of your stack holders asks for an integrated report from multiple sources well good
23:25:23
여러 출처에서 통합된 보고서를 요청하는 것입니다
luck with that because merging all those data manually is
23:25:26
모든 데이터를 수동으로 병합하는 것은
very chaotic time consuming and full of risk so
23:25:29
매우 혼란스럽고 시간이 많이 걸리며 위험이 가득합니다
this is just a picture if a company is working without a
23:25:32
회사가 제대로 된 데이터 관리 없이 운영된다면
proper data management without a data leak data
23:25:36
데이터 유출이 발생할 수 있습니다
warehouse data leak houses so in order to make real
23:25:39
실제적이고 좋은 결정을 내리기 위해서는 데이터 관리가 필요합니다
and good decisions you need data management so
23:25:42
이제 데이터 웨어하우스의 시나리오에 대해 이야기해 보겠습니다
now let's talk about the scenario of a data warehouse so the first thing that's gonna happen is that you will not have your data team collecting manually the data you're gonna
23:25:51
가장 먼저 발생하는 일은 데이터 팀이 수동으로
have a very important component called etl
23:25:54
데이터를 수집하지 않는 것입니다
it stands for extract transform and load
23:25:57
매우 중요한 구성 요소인 ETL이 있습니다
it is a process that you do in order to extract the data
23:26:00
추출, 변환 및 로드를 의미합니다
from the sources and then apply multiple transformations on
23:26:03
데이터를 추출하기 위해 수행하는 프로세스입니다
those sources and at the end it loads the data to the
23:26:06
출처에서 데이터를 추출한 후 여러 변환을 적용합니다
data warehouse and this one can be the single point of truth
23:26:09
마지막에 데이터를 데이터 웨어하우스에 로드합니다
for analyzes and reporting and it is called data
23:26:13
이것은 진실의 단일 지점이 될 수 있습니다
warehouse so now what can happen all your reports can be consuming this single point of truth so that you
23:26:20
여러 보고서를 생성할 수 있으며
create your multiple reports and as well you can create
23:26:23
여러 출처에서 통합된 보고서를 생성할 수 있습니다.
integrated reports from multiple sources not
23:26:26
하나의 출처만이 아니라 오른쪽을 보면
only from one single source so now by looking to the right side
23:26:29
이미 정리된 것처럼 보이고 전체 과정이
it looks already organized right and the whole process is
23:26:33
완전히 자동화되어 수동 단계가 더 이상 없습니다.
completely automated there is no more manual steps
23:26:36
물론 이는 인적 오류를 줄이고
which of course it reduces the human error and
23:26:39
데이터를 소스에서 로드하여 몇 시간 또는 때로는 몇 분 내에 보고서를 생성할 수 있습니다.
as well it is pretty fast so usually you can load the data from
23:26:42
물론 큰 장점은 데이터 웨어하우스 자체가 완전히 통합되어 있다는 것입니다.
the sources until the reports in matter of hours or sometimes in minutes so there is no need to wait like weeks and months in order to refresh anything.
23:26:52
즉, 모든 출처를 한 곳에 모아 보고를 더 쉽게 할 수 있습니다. 통합된 것뿐만 아니라 이 웨어하우스에 역사도 구축할 수 있습니다.
And of course, the big advantage is that the data warehouse itself, it is completely integrated.
23:26:57
따라서 이제 역사적 데이터에 접근할 수 있는 가능성이 생겼습니다.
So that means it goes and bring all those sources together in one place, which makes it really easier for reporting and not only integrated, you can build into that warehouse as well history.
23:27:08
모든 보고서가 동일한 데이터 상태를 가지고 있다는 것이 놀랍습니다.
So we have now the possibility to access historical data.
23:27:11
모든 보고서가 동일한 상태를 가질 수 있으며, 때때로 하루 정도 오래된 것일 수 있습니다.
And what is also amazing is that all those reports having the same data status.
23:27:17
물론 클라우드 플랫폼에 현대적인 데이터 웨어하우스가 있다면, 대량의 데이터 소스를 쉽게 처리할 수 있습니다.
So all those reports can have the same status, maybe sometimes one day old or something.
23:27:21
따라서 소스 중 하나가 대량의 데이터를 제공하더라도 걱정할 필요가 없습니다.
And of course, if you have a modern data warehouse in cloud platforms, you can really easily handle any big data sources.
23:27:28
물론 데이터 웨어하우스를 구축하기 위해서는 다양한 유형의 개발자가 필요합니다.
So no need to panic if one of your sources is delivering massive amount of data.
23:27:33
보통 ATL 구성 요소와 데이터 웨어하우스를 구축하는 사람은 데이터 엔지니어입니다.
And of course, in order to build the data warehouse, you need different types of developers.
23:27:36
그들은 소스에 접근하고, ATL을 스크립트하고, 데이터 웨어하우스를 위한 데이터베이스를 구축하는 사람들입니다.
So usually the one that builds the ATL components and the data warehouse is the data engineer.
23:27:43
이제 다른 부분에 대해 책임이 있는 사람은 데이터 분석가입니다.
So they are the one that is accessing the sources, scripting the ATLs, and building the database for the data warehouse.
23:27:50
그들은 데이터 웨어하우스를 소비하고, 다양한 데이터 모델과 보고서를 구축하며, 이해관계자와 공유하는 사람들입니다.
And now for the other part, the one that is responsible for that is the data analyst.
23:27:55
그들은 보통 이해관계자와 연락하고 요구 사항을 이해하며, 데이터 웨어하우스를 기반으로 여러 보고서를 작성합니다.
They are the one that is consuming the data warehouse, building different data models and reports, and sharing it with the stackholders.
23:28:03
따라서 이제 이 두 가지 시나리오를 살펴보면, 이것이 바로 데이터 관리가 필요한 이유입니다.
So they are usually contacting the stackholders, understanding the requirements, and building multiple reports based on the data warehouse.
23:28:10
당신의 데이터 팀은 시간을 낭비하지 않고 데이터와 싸우지 않습니다.
So now if you have a look to those two scenarios, this is exactly why we need data management.
23:28:15
당신의 데이터 팀은 시간을 낭비하지 않고 데이터와 싸우고 있지 않습니다.
Your data team is not wasting time and fighting with the data.
23:28:20
그들은 이제 더 조직적이고 집중력이 높아졌으며 데이터 웨어하우스와 함께 전문적이고 신선한 보고서를 제공하여 회사가 빠르고 좋은 결정을 내릴 수 있도록 하고 있습니다.
They are now more organized and more focused and with like a data warehouse and you are delivering professional and fresh reports that your company can count on in order to make good and fast decisions.
23:28:32
그래서 데이터 웨어하우스와 같은 데이터 관리가 필요한 이유입니다. 데이터 웨어하우스를 바쁜 식당이라고 생각해 보세요.
So this is why you need a data management like a data warehouse. Think about data warehouse as a busy restaurant.
23:28:39
매일 다양한 공급업체가 신선한 재료, 채소, 향신료, 고기 등을 가져옵니다.
Every day, different suppliers bring in fresh ingredients, vegetables, spices, meat, you name it.
23:28:44
그들은 즉시 사용하지 않고 모든 것을 한 냄비에 던지지 않죠?
They don't just use it immediately and throw everything in one pot, right?
23:28:48
그들은 재료를 씻고, 손질하고, 정리하여 각 재료를 올바른 장소, 냉장고나 냉동고에 보관합니다.
They clean it, shop it, and organize everything and store each ingredient in the right place, fridge or freezer.
23:28:55
이것이 준비 단계입니다. 주문이 들어오면 준비된 재료를 빠르게 가져와 완벽한 요리를 만듭니다.
So this is the preparing phase. And when the order comes in, they quickly grab the prepared ingredients and create a perfect dish.
23:29:03
그리고 나서 식당 고객에게 제공합니다. 이 과정은 데이터 웨어하우스 프로세스와 정확히 같습니다.
And then serve it to the customers of the restaurant. And this process is exactly like the data warehouse process.
23:29:08
이것은 원재료인 데이터가 청소되고 정렬되며 저장되는 주방과 같습니다.
It is like the kitchen where the raw ingredients, your data, are cleaned, sorted, and stored.
23:29:14
보고서나 분석이 필요할 때, 필요한 대로 정확히 제공할 준비가 되어 있습니다.
And when you need a report or analyzes, it is ready to serve up exactly like what you need.
23:29:23
좋아요, 이제 ETL 구성 요소에 집중해 보겠습니다.
Okay, so now we're going to zoom in and focus on the component ETL.
23:29:26
이런 프로젝트를 구축하고 있다면, 거의 90%를 이 구성 요소인 ETL 구축에 사용할 것입니다.
If you are building such a project, you're going to spend almost 90% just building this component, the ETL.
23:29:33
그래서 이것은 데이터 웨어하우스의 핵심 요소입니다. ETL이 정확히 무엇인지 명확하게 이해하길 바랍니다.
So it is the core element of the data warehouse. and I want you to have a clear understanding what is exactly an ETL.
23:29:39
우리 데이터는 소스 시스템에 존재합니다.
So our data exists in a source system.
23:29:42
이제 우리가 하고 싶은 것은 소스에서 데이터를 가져와 타겟으로 이동하는 것입니다.
And now what we want to do is, is to get our data from the source and move it to the target.
23:29:47
소스와 타겟은 데이터베이스 테이블과 같을 수 있습니다. 이제 우리가 해야 할 첫 번째 단계는 소스에서 로드할 데이터를 지정하는 것입니다.
Source and target could be like database tables. So now the first step that we have to do is to specify which data we have to load from the source.
23:29:55
물론 모든 것을 로드하고 싶다고 말할 수 있지만, 점진적 로드를 하고 있다고 가정해 봅시다.
Of course, we can say that we want to load everything, but let's say that we are doing incremental loads.
23:30:01
그래서 우리는 소스에서 데이터의 하위 집합을 지정하여 준비하고 나중에 타겟에 로드할 것입니다.
So we're going to go and specify a subset of the data from the source in order to prepare it and load it later to the target.
23:30:07
이 ATL 프로세스의 이 단계를 추출이라고 부릅니다. 우리는 필요한 데이터를 식별하고 있습니다.
So this step in the ATL process, we call it extract. We are just identifying the data that we need.
23:30:13
우리는 그것을 꺼내고 아무것도 변경하지 않습니다. 소스 시스템과 1:1로 동일하게 됩니다.
We pull it out and we don't change anything. It's going to be like one to one like the source system.
23:30:18
따라서 추출은 소스에서 꺼내야 할 데이터를 식별하는 단 하나의 작업만 있습니다.
So the extract has only one task to identify the
23:30:21
소스에서 꺼내야 할 데이터를 식별하고,
data that you have to pull out from the source and to
23:30:24
아무것도 변경하지 않으므로 데이터를 전혀 조작하지 않을 것입니다.
not change anything so we will not manipulate the data at all
23:30:27
그것은 그대로 유지될 수 있으므로 이것이 ETL 프로세스의 첫 번째 단계입니다.
it can stay as it is so this is the first step in
23:30:30
이제 추출된 데이터를 가져가서
the etl process the extract now moving on to
23:30:33
2단계로 넘어가서 우리는 일부 조작과 변환을 할 것입니다.
the stage number two we're gonna take this extract data and we
23:30:37
데이터의 형태를 변경할 것이며 이 과정은 매우 힘든 작업입니다.
will do some manipulations transformations and
23:30:40
데이터 정리, 데이터 통합 및 많은 형식 지정과 데이터 정규화를 수행할 수 있습니다.
we're gonna change the shape of those data and this process is really heavy working we can do a lot of stuff like data cleansing data
23:30:48
데이터 통합과 많은 형식화 및 데이터 정규화
integration and a lot of formatting and data normalizations
23:30:51
이 단계에서 할 수 있는 많은 작업이 있습니다. 그래서 이것은
so a lot of stuff we can do in this step so this is the
23:30:54
atl 프로세스의 두 번째 단계인 변환입니다.
second step in the atl process the transformation we're
23:30:58
원본 데이터를 가져와서 재구성하고 변환할 것입니다.
gonna take the original data and reshape it transform
23:31:01
우리가 필요로 하는 정확한 형식으로 변환합니다.
it into exactly the format that we need into
23:31:04
새로운 형식과 우리가 분석 및
a new format and shapes that we need for analyzes and
23:31:07
보고를 위해 필요한 형태로 변환합니다. 이제 마지막 단계로
reporting now finally we get to the last step in the atl process
23:31:11
우리가 로드를 가지고 있습니다. 이 단계에서는
we have the load so in this step we're gonna take this
23:31:14
새로운 데이터를 가져와서 대상에 삽입할 것입니다.
new data and we're gonna insert it into the target
23:31:17
그래서 매우 간단합니다. 이 준비된 데이터를 가져올 것입니다.
so it is very simple we're gonna take this prepared data from
23:31:20
변환 단계에서 최종 목적지로 이동할 것입니다.
the transformation step and we're gonna move it into its final
23:31:23
목적지, 예를 들어 데이터 웨어하우스입니다.
destination the target like for example data warehouse so
23:31:27
이것이 etl의 요약입니다. 먼저 원시 데이터를
that's etl in a nutshell first extract the raw
23:31:30
추출한 다음 의미 있는 것으로 변환하고
data then transform it into something meaningful and
23:31:33
마지막으로 차이를 만들 수 있는 대상에 로드합니다.
finally load it to a target where it's gonna make a difference
23:31:36
그래서 이것이 etl을 의미합니다.
so that's it this is what we mean with the etl
23:31:39
실제 프로젝트에서는 단일 소스와 대상만 있는 것이 아닙니다.
process now in real projects we don't have like only
23:31:42
우리의 데이터 아키텍처는 여러 개의
source and targets our data architecture gonna have like multiple
23:31:46
계층을 가질 것입니다. 당신의 설계에 따라
layers depend on your design whether you are building a
23:31:49
창고 또는 데이터 레이크를 구축하는지에 따라 다릅니다.
warehouse or a data lake or a data warehouse and usually
23:31:52
이 모든 계층 간에 데이터를 로드하는 방법은 여러 가지가 있습니다.
there are like different ways on how to load the data between all
23:31:55
한 계층에서 다른 계층으로 데이터를 로드하기 위해
those layers and in order now to load the data from one layer
23:31:58
여러 가지 방법이 있습니다. 그래서 일반적으로
to another one there are like multiple ways on how to use
23:32:01
소스에서 첫 번째 계층으로 데이터를 로드하는 경우
the atl process so usually if you are loading the data from
23:32:04
소스에서 데이터를 추출하고 변환 없이 직접 첫 번째 계층에 로드합니다.
the source to the layer number one like only extract the data from the source and load it directly to the layer number one without doing any transformations
23:32:12
데이터를 있는 그대로 보고 싶기 때문입니다.
because i want to see the data as it is in the
23:32:15
첫 번째 레이어와 이제 레이어 1과 레이어
first layer and now between the layer number one and the layer number
23:32:18
2 사이에서 전체 ETL을 사용할 수 있습니다.
two you might go and use the full etl so
23:32:21
레이어 1에서 추출하고 변환한 후
we're gonna extract from the layer one transform it and
23:32:24
레이어 2로 로드합니다. 이를 통해 전체 프로세스를 사용하고 있습니다.
then load it to the layer number two so with that we are using
23:32:28
레이어 2에서 레이어 3으로 모든 데이터를 가져옵니다. 그래서 레이어 2를 변환한 후 레이어 3으로 로드합니다.
the whole process the etl and now between layer two and layer three we can do only transformation and then load so we don't have to deal with how to extract the data because it is maybe using the same technology
23:32:39
레이어 2에서 레이어 3으로 모든 데이터를 가져옵니다. 그래서 레이어 2를 변환한 후 레이어 3으로 로드합니다.
and we are taking all data from layer 2 to layer 3. So we transform the whole layer 2 and then load it to layer 3.
23:32:46
이제 3과 4 사이에서 L만 사용할 수 있습니다.
And now between 3 and 4, you can use only the L.
23:32:49
아마도 데이터 복제 및 재현과 같은 것일 수 있으며, 그 후 변환을 수행합니다.
So maybe it's something like duplicating and replicating the data and then you are doing the transformation.
23:32:55
새 레이어로 로드한 후 변환합니다. 물론 이것은 실제 시나리오는 아니며, 단지 보여주고 있습니다.
So you load to the new layer and then transform it. Of course this is not a real scenario, I'm just showing you that.
23:33:00
소스에서 대상로 이동하기 위해 항상 전체 ETL을 사용할 필요는 없습니다.
In order to move from source to a target, you don't have always to use a complete ETL.
23:33:06
데이터 아키텍처의 설계에 따라 ETL의 몇 가지 구성 요소만 사용할 수 있습니다.
depending on the design of your data architecture you might use only few components from the ETL.
23:33:11
그래서 이것이 실제 프로젝트에서 ETL이 어떻게 보이는지입니다.
Okay so this is how ETL looks like in real projects.
23:33:15
ETL에서 다양한 기술과 방법에 대한 개요를 보여드리고 싶습니다.
Okay so now I would like to show you an overview of the different techniques and methods in the ETLs.
23:33:21
프로젝트에 적용할 방법을 결정해야 하는 다양한 가능성이 있습니다.
We have wide range of possibilities where you have to make decisions on which one you want to apply to your projects.
23:33:26
먼저 추출부터 시작하겠습니다. 제가 보여주고 싶은 첫 번째 것은 다양한 추출 방법이 있다는 것입니다.
So let's start first with the extraction. The first thing that I want to show you is we have different methods of extraction.
23:33:33
소스 시스템으로 가서 데이터를 가져오거나
Either you are going to the source system and pulling the data
23:33:36
소스에서 데이터를 가져오거나 소스 시스템이 데이터를 푸시합니다.
from the source or the source system is pushing the data
23:33:39
데이터 웨어하우스로, 데이터 추출 방법의 두 가지 주요 방법입니다.
to the data warehouse so those are the two main methods on how
23:33:42
데이터를 추출하고 추출에는 두 가지 유형이 있습니다.
to extract data and then we have in the extraction two
23:33:45
전체 추출, 즉 모든 테이블의 모든 레코드입니다.
types we have a full extraction everything all the
23:33:49
매일 모든 데이터를 데이터 웨어하우스로 로드하거나
records from tables and every day we load all the data to
23:33:52
우리는 매일 새로운 변경 데이터를 식별하는 증분 추출을 수행합니다.
the data warehouse or we make more smarter one where we say
23:33:55
전체를 로드할 필요 없이 새로운 데이터만 추출합니다.
we're gonna do an incremental extraction where every day we're gonna identify only the new changing data so we don't have to load the whole
23:34:02
그런 다음 데이터 웨어하우스로 로드하고 데이터 추출에서 우리는
thing only the new data we go extract it and then
23:34:05
데이터 웨어하우스에 로드하고 데이터 추출에는
load it to the data warehouse and in data extraction we have
23:34:08
다양한 기법이 있으며 첫 번째는 수동으로 누군가가
different techniques the first one is like manually where someone has
23:34:11
소스 시스템에 접근하여 데이터를 수동으로 추출하는 것입니다.
to access a source system and extract the data manually
23:34:15
또는 데이터베이스에 연결하여
or we connect ourselves to a database and we have then
23:34:18
데이터를 추출하기 위한 쿼리 또는 파일이 있습니다.
a query in order to extract the data or we have a file
23:34:21
데이터 웨어하우스로 파싱해야 하며 다른 기법은
that we have to parse it to the data warehouse or another technique
23:34:24
API에 연결하여 호출을 수행하는 것입니다.
is to connect ourselves to api and do their calls
23:34:27
데이터를 추출하기 위해 또는 데이터가 사용 가능한 경우
in order to extract the data or if the data is available
23:34:30
카프카와 같은 스트리밍에서 이벤트 기반으로
in streaming like in kafka we can do event-based
23:34:33
데이터를 추출하기 위한 또 다른 방법은
streaming in order to extract the data another way is to use
23:34:37
변경 데이터 캡처(CDC)는
the change data capture cdc is as
23:34:40
스트리밍과 매우 유사하거나 다른 방법은
well something very similar to streaming or another way is
23:34:43
웹 스크래핑을 사용하여 코드를 실행하고
by using web scrapping where you have a code that's gonna run
23:34:46
웹에서 모든 정보를 추출하는 것입니다. 이것들은
and extract all the informations from the web so those are
23:34:49
추출에서 우리가 가진 다양한 기법과 유형입니다. 변환에 대해 이야기하면
the different techniques and types that we have in the extraction now if you are talking on the transformation there are wide range of different transformations that we can do on our data.
23:34:58
예를 들어 데이터 세트에 값을 추가하는 데이터 보강을 수행하는 것입니다.
Like for example, doing data enrichment, where we add values to our data sets.
23:35:04
또는 여러 소스를 통합하여 모든 것을 하나의 데이터 모델로 가져오는 것입니다.
Or we do a data integration, where we have multiple sources and we bring everything to one data model.
23:35:09
또는 기존의 열 공간에서 새로운 열을 파생합니다. 데이터 변환의 또 다른 유형은 데이터 정규화입니다.
Or we derive a new column space on already existing one. Another type of data transformations, we have the data normalization.
23:35:15
소스에는 코드와 같은 값이 있습니다. 그리고 이를 분석가가 더 친숙하게 사용할 수 있는 값으로 매핑합니다.
So the sources has values that are like a code. And you go and map it to more friendly values for the analyzers.
23:35:23
더 이해하기 쉽고 사용하기 쉬운 것입니다. 또 다른 변환은 비즈니스 규칙과 논리입니다.
which is more easier to understand and to use. Another transformation, we have the business rules and logic.
23:35:29
비즈니스에 따라 새로운 열을 만들기 위해 다양한 기준을 정의할 수 있습니다.
Depend on the business, you can define different criterias in order to build like new columns.
23:35:34
변환에 속하는 것은 데이터 집계입니다. 여기서 우리는 데이터를 다른 세분성으로 집계합니다.
And what belongs to transformations is the data aggregation. So here we aggregate the data to a different granularity.
23:35:40
그리고 데이터 정화라고 하는 변환 유형이 있습니다. 데이터를 정리하는 방법은 여러 가지가 있습니다.
And then we have type of transformation called data cleansing. There are many different ways on how to clean our data.
23:35:47
예를 들어 중복 제거, 데이터 필터링, 처리
For example, removing the duplicates, doing data filtering, handling
23:35:50
누락된 데이터 처리 및 유효하지 않은 값입니다.
the missing data handling invalid values
23:35:53
또는 원하지 않는 공백을 제거하고
or removing unwanted spaces casting the
23:35:56
데이터 유형과 이상치를 감지하는
data types and detecting the outliers and
23:35:59
다양한 데이터 정제 유형이 있습니다.
many more so we have different types of data cleansing that
23:36:03
우리 데이터 웨어하우스에서 수행할 수 있는
we can do in our data warehouse and this is very important
23:36:06
변환입니다. 보시다시피 다양한 변환 유형이 있습니다.
transformation so as you can see we have different types of transformations
23:36:09
데이터 웨어하우스에서 수행할 수 있는 변환입니다. 이제 로드로 넘어가겠습니다.
that we can do in our data warehouse now moving on to the load so what do we have over here we have different processing types so either we are doing patch processing or stream processing.
23:36:21
여기에서 우리는 다양한 처리 유형이 있습니다. 패치 처리 또는 스트림 처리 중 하나입니다.
Patch processing means we are loading the data warehouse in one big patch of data that can run and load the data warehouse.
23:36:28
패치 처리는 데이터 웨어하우스를 한 번에 큰 데이터 패치로 로드하는 것을 의미합니다.
So it is only one time job in order to refresh the content of the data warehouse and as well the reports.
23:36:34
데이터 웨어하우스의 내용을 새로 고치기 위한 일회성 작업입니다.
So that means we are scheduling the data warehouse in order to load it in the day once or twice.
23:36:39
즉, 우리는 데이터 웨어하우스를 하루에 한두 번 로드하도록 예약하고 있습니다.
And the other type we have the stream processing. So this means if there is like a change in the source system, we're going to process this change as soon as possible.
23:36:47
다른 유형은 스트림 처리입니다. 이는 소스 시스템에 변경 사항이 있을 경우
So we're going to process it through all the layers of the data warehouse once something changes from the source system.
23:36:52
변경 사항을 가능한 한 빨리 처리할 것임을 의미합니다.
So we are streaming the data in order to have real time data warehouse, which is very challenging things to do in data warehousing.
23:37:00
소스 시스템에서 변경 사항이 발생하면 모든 레이어를 통해 처리합니다.
And if you are talking about the loads, we have two methods. Either we are doing a full load or incremental load.
23:37:06
데이터 웨어하우스를 실시간으로 유지하기 위해 스트리밍하고 있습니다.
It's the same thing as extraction, right? So for the full load in databases, there are like different methods on how to do it.
23:37:12
로드에 대해 이야기하면 두 가지 방법이 있습니다.
Like for example, we truncate and then inserts.
23:37:15
전체 로드 또는 증분 로드입니다.
That means we make the table completely empty and then we insert everything from the scratch or another one. You are doing an update insert.
23:37:22
전체 로드는 데이터베이스에서 수행하는 방법이 다릅니다.
We call it upsert. So we can go and update all the records and then insert the new one.
23:37:27
예를 들어, 우리는 잘라내고 삽입합니다.
And another way is to drop, create and insert. So that means we drop the whole table and then we create it from scratch and then we insert the data.
23:37:35
즉, 테이블을 완전히 비우고 처음부터 모든 것을 삽입합니다.
It is very similar to the truncate, but here we are as well removing and dropping the whole table.
23:37:39
업데이트 삽입을 수행할 수도 있습니다.
So those are the different methods of full loads.
23:37:42
업데이트 또는 삽입 문을 수행할 것입니다.
the incremental load we can use as well the upserts so update
23:37:45
우리 테이블에 또는 소스가 로그와 같은 경우
and inserts so we're gonna do an update or insert statements
23:37:49
우리는 오직 삽입만 수행할 수 있습니다.
to our tables or if the source is something like a log
23:37:52
데이터를 테이블에 항상 추가할 수 있습니다.
we can do only inserts so we can go and append the
23:37:55
증분 로드를 수행하는 또 다른 방법은 병합하는 것입니다.
data always to the table without having to update anything another
23:37:59
증분 로드를 수행하는 방법은 병합을 하는 것이며, 여기서 매우 유사합니다.
way to do incremental load is to do a merge and here it is very similar
23:38:02
업서트와 유사하지만 삭제와 함께 업데이트도 포함됩니다.
to the upsert but as well with a delete so update
23:38:05
데이터를 테이블에 로드하는 방법에는 여러 가지가 있으며, 데이터 웨어하우징에서 한 가지 더 있습니다.
insert delete so those are the different methods on how to
23:38:08
우리는 느리게 변화하는 차원(SCD)이라고 부르는 것이 있습니다.
load the data to your tables and one more thing in data warehousing we
23:38:11
여기서는 테이블의 역사화에 관한 모든 것입니다.
have something called slowly changing dimensions so
23:38:14
역사화를 처리하는 방법에는 여러 가지가 있습니다.
here it's all about the historizations of your table and
23:38:18
역사화를 처리하는 방법은 여러 가지가 있습니다.
there are many different ways on how to handle the historizations
23:38:21
당신의 테이블에서 첫 번째 탭은 scd0입니다.
in your table the first tab is scd0 we say
23:38:24
즉, 아무것도 업데이트하지 않을 것이라는 의미입니다. 두 번째
there is no historizations and nothing should be changed at all
23:38:27
더 유명한 것은 SCD1입니다.
so that means you are not going to update anything the second
23:38:30
더 유명한 것은 SCD1입니다.
one which is more famous it is the scd1 you
23:38:34
기록을 소스 시스템의 새로운 정보로 덮어쓰고 있습니다.
are doing an overwrite so that means you are updating the
23:38:37
오래된 값을 덮어쓰고 있습니다. 그래서 우리는 업서트와 같은 작업을 하고 있습니다.
records with the new information from the source system by overwriting
23:38:40
업데이트와 삽입을 하지만 역사 기록을 잃게 됩니다.
the old value so we are doing something like the upsert so
23:38:43
우리는 SCD2를 가지고 있으며, 여기서는 역사화를 추가하고자 합니다.
update and inserts but you are losing of course history
23:38:47
테이블에 추가하는 것입니다. 그래서 우리는
another one we have the scd2 and here you want to add historizations
23:38:50
당신의 테이블로, 우리가 받는 각 변경 사항은
to your table so what we do each change that we get from
23:38:53
소스 시스템에서 새로운 레코드를 삽입하고 이전 데이터를 덮어쓰거나 삭제하지 않을 것입니다. 우리는 단지 그것을 비활성화하고 새로운 레코드는 활성 상태가 될 것입니다.
the source system that means we are inserting new records and we are not going to overwrite or delete the old data We are just going to make it inactive and the new record going to be active one.
23:39:04
데이터 웨어하우스에 데이터를 로드하는 동안 역사화하는 방법에는 여러 가지가 있습니다. 알겠죠.
So there are different methods on how to do historizations as well while you are loading the data to the data warehouse. All right.
23:39:11
따라서 데이터 관리 프로젝트에서 마주칠 수 있는 다양한 유형과 기술입니다.
So those are the different types and techniques that you might encounter in data management projects.
23:39:16
이제 우리가 프로젝트에서 사용할 유형이 무엇인지 빠르게 보여드리겠습니다.
So now I'm going to show you quickly which of those types we will be using in our projects.
23:39:20
여기에서 추출에 대해 이야기하면, 우리는 풀 추출을 하고 전체 또는 증분에 대해 이야기할 것입니다.
So now if we are talking about the extraction over here, we will be doing a pull extraction and about the full or incremental.
23:39:26
전체 추출이 될 것입니다. 그리고 기술에 대해서는, 우리는 파일을 데이터 웨어하우스로 파싱할 것입니다.
It's going to be a full extraction. And about the technique, we are going to be parsing files to the data warehouse.
23:39:33
이제 데이터 변환에 대해 이야기하겠습니다. 음, 이것은 모든 것을 다룰 것입니다.
And now about the data transformations. Well, this one, we will cover everything.
23:39:38
지금 보여드리는 모든 유형의 변환은 프로젝트의 일부가 될 것입니다.
All those types of transformations that I'm showing you now, it's going to be part of the project.
23:39:43
각 데이터 프로젝트에서 이러한 변환을 마주하게 될 것이라고 믿습니다.
Because I believe in each data project, you will be facing those transformations.
23:39:47
우리 프로젝트는 패치 처리가 될 것입니다.
Now, if you have a look to the load, our project is going to be patch processing.
23:39:51
로드 방법에 대해, 우리는 전체 로드를 수행할 것입니다.
And about the load methods, we will be doing a full load since we have full extraction. and it's going to be truncate and inserts.
23:39:58
이제 그에 대해 이야기해 보겠습니다.
And now about that.
23:40:00
역사화에 대해서는 SCD를 사용할 것입니다. 즉, 데이터 웨어하우스의 내용을 업데이트할 것입니다.
For historializations, we will be doing the SCD one. So that means we will be updating the content of the data warehouse.
23:40:06
그래서 이것들이 이번 프로젝트의 ETL 과정에서 사용할 다양한 기술과 유형입니다.
So those are the different techniques and types that we will be using in our ETL process for this project.
23:40:11
좋습니다. 이제 데이터 웨어하우스가 무엇인지 명확히 이해했으니 이론 부분은 끝났습니다.
All right, so with that, we have now clear understanding what is a data warehouse and we are done with the theory parts.
23:40:17
이제 다음 단계로, 프로젝트를 시작하겠습니다.
So now the next step, we're going to start with the projects.
23:40:20
먼저 해야 할 일은 프로젝트를 개발할 환경을 준비하는 것입니다. 그러니 시작해 봅시다.
The first thing that we have to do is to prepare our environment to develop the projects. So let's start with that.
23:40:31
좋습니다. 이제 설명에 있는 링크로 가겠습니다. 거기서 다운로드로 이동할 것입니다.
All right, so now we go to the link in the description. And from there, we're going to go to the downloads.
23:40:35
모든 과정과 프로젝트의 자료를 찾을 수 있습니다. 하지만 지금 필요한 것은 SQL 데이터 웨어하우스 프로젝트입니다.
And you can find all the materials of all courses and projects. But the one that we need now is the SQL Data Warehouse projects.
23:40:42
링크로 가서 여기 프로젝트에 필요한 여러 링크를 확인해 보겠습니다.
So let's go to the link. And here we have a bunch of links that we need for the projects.
23:40:46
모든 데이터와 파일을 얻기 위한 가장 중요한 링크는 이 링크입니다. 모든 프로젝트 파일을 다운로드하세요. 그러니 가서 해봅시다.
But the most important one to get all data and files is this one. Download all project files. So let's go and do that.
23:40:52
그 작업을 마치면 많은 파일이 들어 있는 zip 파일을 받게 됩니다. 그러니 가서 압축을 풀어봅시다.
And after you do that, you're going to get a zip file where you have there a lot of stuff. So let's go and extract it.
23:40:59
이제 그 안에 들어가면 여기에서 Git의 저장소 구조를 찾을 수 있습니다. 여기서 가장 중요한 것은 데이터 세트입니다.
Now inside it, if you go over here, you will find the repository structure from Git. And the most important one here is the data sets.
23:41:06
CRM과 ARP 두 가지 소스가 있습니다. 각 소스에는 세 개의 CSV 파일이 있습니다.
So you have two sources, the CRM and the ARP. And in each one of them, there are three CSV files.
23:41:12
이것들이 프로젝트의 데이터 세트입니다. 다른 것에 대해서는 걱정하지 마세요. 프로젝트 동안 설명할 것입니다.
So those are the data sets for the projects. For the other stuff, don't worry about it. We will be explaining that during the projects.
23:41:19
그러니 데이터를 가져와서 PC의 잃어버리지 않을 곳에 저장하세요. 좋습니다. 이제 다른 것은 무엇이 있나요?
So go and get the data and put it somewhere at your PC where you don't lose it. Okay, so now what else do we have?
23:41:25
여기 Git 저장소에 대한 링크가 있습니다. 이것은 제가 프로젝트를 통해 만든 저장소의 링크입니다.
We have here a link to the Git repository. So this is the link to my repository that I have created through the projects.
23:41:31
접근할 수 있지만 걱정하지 마세요. 프로젝트 동안 전체 구조를 설명할 수 있으며, 여러분은 자신의 저장소를 만들 것입니다.
So you can go and access it, but don't worry about it. We can explain the whole structure during the projects and you will be creating your own repository.
23:41:37
또한 노션에 대한 링크도 있습니다. 여기에서 프로젝트 관리를 하고 있습니다.
And as well, we have the link to the notion. Here we are doing the project management.
23:41:41
여기에서 우리가 수행할 SQL 프로젝트의 주요 단계와 주요 단계들을 찾을 수 있습니다.
Here you're going to find the main steps, the main phases of the SQL projects that we will do.
23:41:46
또한 프로젝트 동안 함께 수행할 모든 작업도 있습니다. 이제 프로젝트 도구에 대한 링크가 있습니다.
And as well, all the tasks that we will be doing together during the projects. And now we have links to the project tools.
23:41:54
아직 다운로드하지 않았다면 SQL Server Express를 다운로드하세요.
So if you don't have it already, go and download the SQL Server Express.
23:41:57
이것은 데이터베이스가 존재할 수 있는 PC에서 로컬로 실행할 수 있는 서버와 같습니다.
So it's like a server that can run locally at your PC where your database can live.
23:42:02
다운로드해야 할 또 다른 프로그램은 SQL Server Management Studio입니다. 데이터베이스와 상호작용하기 위한 클라이언트입니다.
Another one that you have to download is the SQL Server Management Studio. It is just a client in order to interact with the database.
23:42:08
거기서 모든 쿼리를 실행하고 GitHub와 Draw.io에 연결할 것입니다.
And there we're going to run all our queries and then link to the GitHub and as well link to the Draw.io.
23:42:14
아직 설치하지 않았다면 다운로드하세요. 무료이며 다이어그램을 그리기 위한 훌륭한 도구입니다.
If you don't have it already, go and download it. It is free and amazing tool in order to draw diagrams.
23:42:20
프로젝트를 통해 데이터 모델, 데이터 아키텍처, 데이터 계보를 그릴 것입니다.
So through the projects, we will be drawing data models, the data architecture, a data lineage.
23:42:25
이 도구를 사용하여 많은 작업을 할 것입니다. 그러니 다운로드하세요.
So a lot of stuff we'll be doing using this tool. So go and download it.
23:42:30
마지막으로 Notion에 대한 링크가 있습니다. 여기서 무료 계정을 만들 수 있습니다.
And the last thing it is nice to have, you have a link to the Notion where you can go and create, of course, free accounts.
23:42:36
프로젝트 계획을 세우고 프로젝트 단계 및 작업을 생성하여 저를 따라오세요.
If you want to build the project plan and as well, follow me by creating the project steps and the project tasks.
23:42:42
모든 링크가 있습니다. 그러니 모든 것을 다운로드하고 계정을 생성하세요.
OK, so that's all. Those are all the links for the projects. So go and download all those stuff, create the accounts.
23:42:49
준비가 되면 프로젝트를 계속 진행합니다. 모든 도구를 다운로드하고 계정을 만들었기를 바랍니다.
And once you are ready, then we continue with the projects. Alright, so now I hope that you have downloaded all the tools and created the accounts.
23:42:59
이제 사람들이 프로젝트를 진행하면서 거의 모두 건너뛰는 매우 중요한 단계로 넘어갈 시간입니다.
Now it's time to move to a very important step that almost all people skip while doing projects.
23:43:05
그것은 프로젝트 계획을 만드는 것입니다. 이를 위해 Notion 도구를 사용할 것입니다. Notion은 무료 도구입니다.
And that is by creating the project plan. And for that, we will be using the tool Notion. Notion is, of course, a free tool.
23:43:12
아이디어, 계획 및 자원을 한 곳에서 정리하는 데 도움이 됩니다.
And it can help you to organize your ideas, your plans, and resources all in one place.
23:43:18
저는 개인 프로젝트, 예를 들어 이 과정을 만드는 데 매우 집중적으로 사용합니다.
I use it very intensively for my private projects like for example creating this course.
23:43:22
프로젝트 계획을 만드는 것이 성공의 열쇠라고 말씀드릴 수 있습니다. 데이터 웨어하우스 프로젝트는 보통 매우 복잡합니다.
And I can tell you creating a project plan is the key to success. Creating a data warehouse project is usually very complex.
23:43:29
Gartner 보고서에 따르면 데이터 웨어하우스 프로젝트의 50% 이상이 실패합니다.
And according to Gartner reports over 50% of data warehouse projects fail.
23:43:34
복잡한 프로젝트에서 성공의 열쇠는 명확한 프로젝트 계획을 갖는 것입니다.
And my opinion about any complex projects the key to success is to have a clear project plan.
23:43:40
이 프로젝트 단계에서 우리는 대략적인 프로젝트 계획을 세울 것입니다.
So now at this phase of the project we're going to go and create a rough project plan.
23:43:45
현재로서는 데이터 아키텍처에 대한 명확한 이해가 없습니다.
because at the moment we don't have yet clear understanding about
23:43:48
새 페이지를 만들고 데이터 웨어하우스 프로젝트라고 부르겠습니다.
the data architecture so let's go okay so now let's create a
23:43:51
주요 단계와 단계들을 만들어야 합니다.
new page and let's call it data warehouse projects the first thing
23:43:54
이를 위해 테이블을 만들어야 합니다.
is that we have to go and create the main phases and
23:43:57
슬래시를 입력하고 그 다음에 입력하세요.
stages of the projects and for that we need a table
23:44:00
데이터베이스를 입력하고 데이터 웨어하우스 에픽스라는 이름을 붙이겠습니다.
so in order to do that hit slash and then type
23:44:03
마음에 들지 않으니 숨기겠습니다. 테이블에서 이름을 바꿀 수 있습니다.
database in line and then let's go and call it something like data warehouse epics and we're gonna go and hide it because i don't
23:44:11
예를 들어 프로젝트 에픽스와 같은 이름으로 바꿀 수 있습니다.
like it and then on the table we can go and rename it like
23:44:15
예를 들어 프로젝트, 에픽, 그런 것들
for example projects epics something like that
23:44:18
이제 우리가 할 일은 모든 큰 작업을 나열하는 것입니다.
and now what we're gonna do we're gonna go and list all the big tasks of
23:44:21
프로젝트에서 에픽은 일반적으로 큰 작업입니다.
the projects so an epic is usually like a large task that
23:44:24
해결하기 위해 많은 노력이 필요한 작업입니다.
needs a lot of efforts in order to solve it so you can call it epics
23:44:27
프로젝트의 단계나 원하는 대로
stages phases of the project whatever you want so
23:44:31
우리의 프로젝트 단계를 나열할 것입니다. 시작해봅시다.
we're gonna go and list our project steps so let's start with
23:44:34
요구 사항 분석, 데이터 아키텍처 설계, 프로젝트 초기화가 있습니다.
the requirements analyzes and then designing data architecture and another one we have the projects initialization.
23:44:44
작업의 작은 조각, 하위 작업을 위한 또 다른 테이블이 필요합니다.
So those are the three big tasks in the project first. And now what do we need?
23:44:48
슬래시를 눌러 테이블을 검색할 것입니다.
We need another table for the small chunks of the tasks, the subtasks. And we're going to do the same thing.
23:44:53
먼저 데이터 웨어하우스 작업이라고 부를 것입니다.
So we're going to go and hit slash and we're going to search for the table in line and we're going to do the same thing.
23:44:59
그런 다음 숨기고 여기서
so first we're going to call it data warehouse tasks and
23:45:02
이것을 프로젝트 작업이라고 이름을 바꿉니다.
then we're going to hide it and over here we're going to
23:45:05
이제 플러스 아이콘으로 가서 관계를 검색합니다.
rename it and say this is the project tasks so
23:45:08
클릭하고 양방향 관계라고 말합니다.
now what we're going to do we're going to go to the plus icon over here and then search for relation this one over here with the arrow and now we're going to search for the name of the first table so we called it data warehouse epics
23:45:20
새 테이블에 데이터 웨어하우스 에픽이라는 필드가 생겼습니다.
So let's go and click it and we're going to say as well two-way relation. So let's go and add the relation.
23:45:27
이것은 이 테이블에서 온 것이고, 아래 테이블에서 온 데이터 웨어하우스 작업이 있습니다.
So with that we got a field in the new table called data warehouse epics.
23:45:30
서로 연결된 것을 볼 수 있습니다. 이제 왼쪽으로 가져가겠습니다.
This comes from this table and as well we have here data warehouse tasks that comes from the below table.
23:45:36
예를 들어 데이터 아키텍처 설계를 선택해봅시다.
So as you can see we have linked them together. Now what I'm going to do I'm going to take this to the left side and then what we're going to do we're going to go and select one of those epics.
23:45:44
이 에픽을 여러 작업으로 나눌 것입니다.
Like for example let's take design the data architecture. And now what we're going to do, we're going to go and break down this epic into multiple tasks.
23:45:52
예를 들어 데이터 관리 접근 방식을 선택합니다.
Like, for example, choose data management approach. And then we have another task.
23:45:57
같은 에픽을 선택할 것입니다.
What we're going to do, we're going to go and select as well the same epic.
23:46:00
다음 단계는 레이어를 구상하고 설계하는 것입니다.
So maybe the next step is brainstorm and design the layers.
23:46:06
또 다른 에픽으로 가봅시다. 예를 들어 프로젝트 초기화입니다.
And then let's go to another epic, for example, the project initialization.
23:46:10
여기서 예를 들어, 레포를 만들고 구조를 준비합니다.
And we say over here, for example, create get repo, prepare the structure.
23:46:16
같은 에픽에서 또 하나를 만들 수 있습니다.
we can go and make another one in the same epic let's say
23:46:19
우리는 데이터베이스와 스키마를 생성할 것입니다.
we're going to go and create the database and the schemas
23:46:22
보시다시피, 저는 하위 작업을 정의하고 있습니다.
so as you can see i'm just defining the subtasks of
23:46:25
그 에픽의 하위 작업을 정의하고 있습니다. 이제 우리는 체크박스를 추가할 것입니다.
those epics so now what we can do we're going to go and add a checkbox
23:46:28
작업을 완료했는지 이해하기 위해 체크박스를 추가할 것입니다.
in order to understand whether we have done the task or not so
23:46:31
플러스를 클릭하고 체크박스를 검색합니다.
we go to the plus and search for check we need
23:46:35
체크박스를 만들 것이며, 정말 작게 만들 것입니다.
the checkbox and what we're going to do we're going to make it really small like this and with that each time we are done with the
23:46:41
작업을 완료했을 때 클릭하여 확인할 것입니다.
task we're gonna go and click on it just to make sure that we have
23:46:44
작업을 완료했을 때 클릭하여 확인합니다. 이제 하나 더 있습니다.
done the task now there is one more thing that is not really working nice
23:46:48
여기에서 긴 작업 목록이 있을 것입니다.
and that is here we're gonna have like a long list of tasks
23:46:51
정말 귀찮습니다. 그래서 우리는 플러스로 가서
and it's really annoying so what we're gonna do we're gonna go to the plus over
23:46:54
롤업을 검색할 것입니다. 자, 갑시다.
here and let's search for roll up so let's go
23:46:57
선택하고 관계를 선택해야 합니다.
and select it so now what we're gonna do we have to go and select the relationship
23:47:00
데이터 웨어하우스 작업이 될 것이며, 속성으로 가서 체크박스로 만들 것입니다.
it's gonna be the data warehouse task and after that we're gonna go to the property and make it as a checkbox so now as you can see in the first table we are saying
23:47:08
몇 개의 작업이 완료되었는지 보여주고 싶지 않습니다.
how many tasks is closed but i don't want to show it like this
23:47:11
계산으로 가서 백분율로 이동할 것입니다.
what you can do we're going to go to the calculation and to the percent
23:47:14
그런 다음 체크된 백분율을 확인하여 진행 상황을 볼 수 있습니다.
and then percent checked and with that we can see the progress
23:47:18
우리 프로젝트의 진행 상황을 확인할 수 있습니다.
of our project and now instead of the numbers we can
23:47:21
아주 멋진 막대를 만들 수 있습니다. 그래서 이름을
have really nice bar great so as well we can go and give
23:47:24
진행 상황으로 지정할 수 있습니다. 이제 데이터 웨어하우스 작업을 숨길 수 있습니다.
it a name like progress so that's it and we can
23:47:27
각 에픽에 대해 멋진 진행 막대가 생겼습니다.
go and hide the data warehouse tasks and now with that we have really
23:47:30
모든 작업을 완료하면 100%에 도달한 것을 볼 수 있습니다.
nice progress bar for each epic and if you close all the tasks
23:47:33
이것이 기본 구조입니다. 이제 몇 가지 장식을 추가할 수 있습니다.
of this this epic we can see that we have reached 100% so
23:47:36
더 보기 좋게 만들기 위해 이름을 바꿀 수 있습니다.
this is the main structure now we can go and add some cosmetics i
23:47:40
여기에서 작업으로 가서
rename stuff in order to make things look nicer like for
23:47:43
작업이라고 부를 수 있습니다.
example if i go to the tasks over here i can go and call
23:47:46
작업을 호출할 수 있습니다.
it tasks and as well go and change the icon
23:47:49
아이콘을 변경할 수 있습니다.
to something like this and if you'd like to have an icon
23:47:52
모든 에픽에 대해 할 일을 할 것입니다.
for all those epics what you're gonna do we're gonna go to the epic for example design data architecture and then if you hover on top of the title you can
23:48:00
아이콘을 추가할 수 있습니다.
see add an icon and you can go and pick any icon that you
23:48:03
여기 위에 정의했습니다.
want so for example this one and now as you can see we have
23:48:06
아래 테이블에 아이콘이 있습니다.
defined it here in the top and the icon gonna be as well in the
23:48:09
프로젝트 작업을 그룹화할 수 있습니다.
below table okay so now one more thing that we can do for the project
23:48:12
에픽별로 그룹화할 수 있습니다.
tasks is that we can go and group them by the epics
23:48:15
여기에서 정렬을 시작할 수 있습니다.
so if you go to the three dots and then we go to groups and then we can group up by the epics as you can see now we have like a section for each epic and you can go and sort the epics if you want.
23:48:27
작업을 확장하고 축소할 수 있습니다.
If you go over here, sort, then manual, and you can go over here and start sorting the epics as you want.
23:48:33
프로젝트 데이터 관리를 구축하는 좋은 방법입니다.
And with that, you can expand and minimize each task if you don't want to see always all tasks in one go.
23:48:39
전문 도구를 사용합니다.
So this is really nice way in order to build like data management for your projects.
23:48:43
개인 프로젝트는 이렇게 합니다.
Of course, in companies, we use professional tools in order to do projects like for example, Gyra.
23:48:48
항상 이렇게 하고 추천합니다.
But for private personal projects that I do, I
23:48:51
모든 프로젝트에 대해 이렇게 하세요.
always do it like this and i really recommend you to do it not
23:48:54
전체 프로젝트를 한 번에 보면 큰 그림을 볼 수 있습니다.
only for this project for any project that you are doing because if you see
23:48:57
작은 것들이 만족감을 줍니다.
the whole project in one go you can see the big picture and
23:49:00
작은 것들이 동기를 부여합니다.
closing tasks and doing it like this these small things
23:49:03
전체 프로젝트를 완성하게 됩니다.
can make you really satisfied and keeps you motivated to finish
23:49:07
몇 개의 아이콘을 추가했습니다.
the whole project and makes you proud okay friends
23:49:10
각 에픽에 더 많은 작업을 추가했습니다.
so now i just went and added few icons a rename
23:49:13
데이터 웨어하우스를 구축할 방법에 대한 세부정보입니다.
stuff and as well more tasks for each epic and this is gonna be our starting point in the project and once we have more informations we're gonna go and add more
23:49:21
시작할 때 분석하고 이해할 것입니다.
details on how exactly we're gonna build the data warehouse
23:49:24
요구 사항을 이해할 것입니다.
so at the start we're gonna go and analyze and understand the
23:49:27
데이터 아키텍처를 설계할 것입니다.
requirements and only after that we're gonna start designing
23:49:31
데이터 아키텍처와 여기에는 세 가지 작업이 있습니다.
the data architecture and here we have three tasks first
23:49:34
데이터 관리 접근 방식을 선택해야 하고 그 후에 우리는
we have to choose the data management approach and after that we're
23:49:37
브레인스토밍을 하고 데이터 웨어하우스의 레이어를 설계할 것입니다.
gonna do brainstorming and designing the layers of the data warehouse and at the end we're gonna go and draw a data architecture so with that we have clear understanding how the the data architecture looks like.
23:49:49
그 후에 우리는 다음 에픽으로 가서 프로젝트를 준비할 것입니다.
And after that, we're going to go to the next epic where we're going to start preparing our projects.
23:49:53
데이터 아키텍처를 명확히 이해한 후 첫 번째 작업은
So once we have a clear understanding of the data architecture, the first task here is to go and create detailed project tasks.
23:50:00
더 많은 에픽과 작업을 추가할 것입니다.
So we're gonna go and add more epics and more tasks
23:50:03
작업이 끝나면 명명 규칙을 만들 것입니다.
and once we are done then we're gonna go and create the naming conventions
23:50:06
프로젝트에 대한 규칙과 기준을 만들기 위해
for the projects just to make sure that we have rules and standards
23:50:10
전체 프로젝트에서 우리는 리포지토리를 만들 것입니다.
in the whole projects and next we're gonna go and create a repository
23:50:13
git에서 리포지토리 구조를 준비할 것입니다.
in the git and we're gonna prepare as well the structure of the repository so that we always commit our work there and then we can start with the first script where we can create a database and schemas so my friends
23:50:25
이것이 프로젝트의 초기 계획입니다.
this is the initial plan for the project. Now let's start with the first epic. We have the requirements analysis.
23:50:35
이제 첫 번째 에픽을 시작합시다.
Now analyzing the requirement, it is very important to understand which type of data warehouse you're going to go and build because there is like not only one standard on how to build it.
23:50:44
요구 사항을 분석하는 것이 매우 중요합니다.
And if you go blindly implementing the data warehouse, you might be doing a lot of stuff that is totally unnecessary and you will be burning a lot of time.
23:50:52
어떤 유형의 데이터 웨어하우스를 구축할지 이해해야 합니다.
So that's why you have to sit with the stakeholders with the department
23:50:56
무작정 데이터 웨어하우스를 구현하면 불필요한 작업을 할 수 있습니다.
and understand what we exactly have to build and depend
23:50:59
그래서 이해관계자와 함께 앉아야 합니다.
on the requirements you design the shape of the data
23:51:02
정확히 무엇을 구축해야 하는지 이해해야 합니다.
warehouse so now let's go and analyze the requirement of this project now
23:51:05
요구 사항에 따라 데이터의 형태를 설계합니다.
the whole project is split into two main sections the
23:51:08
이제 이 프로젝트의 요구 사항을 분석합시다.
first section we have to go and build a data warehouse so
23:51:12
전체 프로젝트는 두 개의 주요 섹션으로 나뉩니다.
this is a data engineering task and we will go and develop
23:51:15
첫 번째 섹션은 데이터 웨어하우스를 구축하는 것입니다.
etls and data warehouse and once we have done that we have to go and build analytics
23:51:21
이것은 데이터 엔지니어링 작업입니다.
and reporting business intelligence so we're gonna do data
23:51:24
우리는 ETL과 데이터 웨어하우스를 개발할 것입니다.
analysis but now first we will be focusing on the first part
23:51:28
그 후 분석과 비즈니스 인텔리전스를 구축해야 합니다.
building the data warehouse so what do we have here the statement is
23:51:31
데이터 분석에 집중할 것입니다.
very simple it says develop a modern data warehouse
23:51:34
판매 데이터를 통합하기 위해 SQL 서버 사용
using sql server to consolidate sales data
23:51:38
분석 보고서 및 정보에 기반한 의사결정을 가능하게 함
enabling analytical reporting and informed
23:51:41
그렇다면 사양이 있습니다. 첫 번째는 데이터 소스에 관한 것입니다.
decision making so this is the main statements and
23:51:44
두 개의 소스 시스템에서 데이터를 가져오라고 합니다. ERP
then we have specifications the first one is about the data sources it
23:51:48
및 CRM이며 CSV 파일로 제공됩니다.
says import data from two source systems erp
23:51:51
이제 두 번째 작업은 데이터 품질에 관한 것입니다.
and crm and they are provided as csv files
23:51:55
우리는 데이터 품질 문제를 정리하고 수정해야 합니다.
and now the second task is talking about the data quality we
23:51:58
데이터 분석기를 실행하기 전에 말이죠.
have to clean and fix data quality issues before
23:52:01
완벽한 원시 데이터는 없으며 항상 엉망입니다.
we do the data analyzers because let's be real there
23:52:04
그것을 정리해야 합니다. 이제 다음 작업은
is no raw data that is perfect is always messy
23:52:07
통합에 관한 것입니다. 두 개의 소스를 결합해야 합니다.
and we have to clean that up now the next task is talking about
23:52:10
하나의 사용자 친화적인 데이터로 통합해야 합니다.
the integration so it says we have to go and combine both
23:52:14
분석 및 보고를 위해 설계된 단일 데이터 모델로
of the sources into one single user-friendly
23:52:17
그렇다면 두 소스를 병합해야 합니다.
data model that is designed for analytics and
23:52:20
하나의 단일 데이터 모델로 병합해야 합니다.
reporting so that means we have to go and merge those two sources
23:52:23
여기 또 다른 사양이 있습니다. 최신 데이터에 집중하라고 합니다.
into one single data model and now we have here another
23:52:26
역사화할 필요가 없다는 것을 의미합니다.
specifications it says focus on the latest data
23:52:29
즉, 데이터베이스에 이력을 구축할 필요가 없으며
sets so there is no need for historization so that
23:52:32
데이터 모델의 명확한 문서를 제공해야 합니다.
means we don't have to go and build histories in the database and the final requirement is talking about the documentation so it says provide clear documentations of the data model so that means the last product of the data warehouse
23:52:44
비즈니스 사용자와 분석 팀을 지원하기 위해.
to support the business users and the analytical teams.
23:52:47
사용자에게 도움이 되는 매뉴얼을 생성해야 합니다.
So that means we have to generate a manual that can help the users that makes life easier for the consumers of our data.
23:52:54
이것은 매우 일반적인 요구 사항일 수 있지만
So as you can see, maybe this is very generic requirements, but it has a lot of information already for you.
23:52:59
SQL 서버 플랫폼을 사용해야 한다고 합니다.
So it's saying that we have to use the platform SQL server.
23:53:03
CSV 파일을 사용하는 두 개의 소스 시스템이 있습니다.
We have two source systems using the CSV files, and it sounds that we really have a bad data quality in the sources.
23:53:09
완전히 새로운 데이터 모델을 구축하는 데 집중해야 합니다.
And as well, it wants us to focus on building completely
23:53:13
보고를 위해 설계된 새로운 데이터 모델
new data model that is designed for reporting
23:53:16
그리고 역사화를 할 필요가 없다고 합니다.
and it says we don't have to do historization and it
23:53:19
시스템 문서화를 생성하는 것이 우리의 기대입니다.
is expected from us to generate documentations of the system
23:53:23
데이터 엔지니어링 부분에 대한 요구 사항입니다.
so these are the requirements for the data engineering part
23:53:26
우리가 가서 요구 사항을 충족하는 데이터 웨어하우스를 구축할 것입니다.
where we're going to go and build a data warehouse that fulfill
23:53:29
이 요구 사항을 분석했습니다.
these requirements all right so with that we have analyzed the requirements
23:53:33
우리는 이것을 마쳤으니 이제 닫고
and as well we have closed the first easiest break
23:53:36
여기서 또 다른 것을 열어야 합니다. 데이터 아키텍처를 설계해야 합니다.
so we are done with this let's go and close it and now let's
23:53:39
첫 번째 작업은 데이터 관리 방식을 선택하는 것입니다.
open another one here we have to design the data architecture
23:53:43
자, 이제 갑시다.
and the first task is to choose data management
23:53:46
접근하자, 이제 가자
approach so let's go now
23:53:51
데이터 아키텍처를 설계하는 것은 마치 집을 짓는 것과 같습니다.
designing the data architecture it is exactly like building
23:53:55
건설이 시작되기 전에 건축가는 집의 방들이 어떻게 연결될지, 집을 기능적이고 안전하며 멋지게 만들기 위한 계획과 청사진을 설계합니다.
a house so before construction starts an architect's gonna go and design a plan a blueprint for the house how the rooms will be connected how to make the house functional, safe, and wonderful.
23:54:07
건축가의 이 청사진이 없으면, 건축업자들은 불안정하고 비효율적이거나 아마도 거주할 수 없는 무언가를 만들 수 있습니다.
And without this blueprint from the architects, the builders might create something unstable, inefficient, or maybe unlivable.
23:54:13
데이터 프로젝트도 마찬가지입니다. 데이터 아키텍트는 집의 건축가와 같습니다.
The same goes for data projects. A data architect is like a house architect.
23:54:17
그들은 데이터가 어떻게 흐르고, 통합되며, 접근될지를 설계합니다.
They design how your data will flow, integrate, and be accessed.
23:54:22
그래서 데이터 아키텍트로서 우리는 데이터 웨어하우스가 기능할 뿐만 아니라 확장 가능하고 유지 관리가 용이하도록 합니다.
So as data architects, we make sure that the data warehouse is not only functioning, but also scalable and easy to maintain.
23:54:28
그리고 이것이 바로 우리가 지금 할 일입니다. 우리는 건축가의 역할을 맡아 데이터 웨어하우스의 아키텍처를 브레인스토밍하고 설계하기 시작할 것입니다.
And this is exactly what we will do now. We will play the rule of the architect and we will start brainstorming and designing the architecture of the data warehouse.
23:54:37
이제 데이터 아키텍처를 설계하기 위한 다양한 접근 방식을 이해하기 위해 스케치를 보여드리겠습니다.
So now I'm going to show you a sketch in order to understand what are the different approaches in order to design a data architecture.
23:54:43
이 프로젝트의 단계는 보통 저에게 매우 흥미롭습니다. 왜냐하면 이것이 데이터 프로젝트에서 제 주요 역할이기 때문입니다.
And this phase of the projects usually is very exciting for me because this is my main role in data projects.
23:54:49
저는 데이터 아키텍트이며, 우리는 프로젝트에 대한 최상의 설계를 찾기 위해 다양한 프로젝트에 대해 많은 논의를 합니다.
I am a data architect and I discuss a lot of different projects where we try to find out the best design for the projects.
23:54:56
좋습니다, 이제 시작합시다. 데이터 아키텍처를 구축하는 첫 번째 단계는 네 가지 주요 유형 중에서 선택하는 매우 중요한 결정을 내리는 것입니다.
Alright so now let's go. Now the first step of building a data architecture is to make a very important decision to choose between four major types.
23:55:08
첫 번째 접근 방식은 데이터 웨어하우스를 구축하는 것입니다. 이는 구조화된 데이터만 있는 경우에 매우 적합하며, 비즈니스가 보고 및 비즈니스 인텔리전스를 위한 견고한 기반을 구축하고자 할 때 유용합니다.
The first approach is to build a data warehouse. It is very suitable if you have only structured data and your business want to build solid foundations for reporting and business intelligence.
23:55:19
또 다른 접근 방식은 데이터 유출을 구축하는 것입니다. 이는 데이터 웨어하우스보다 훨씬 더 유연합니다.
And another approach is to build a data leak. This one is way more flexible
23:55:23
구조화된 데이터뿐만 아니라 저장할 수 있습니다.
than a data warehouse where you can store not only structured
23:55:26
구조화된 데이터뿐만 아니라 반구조화 및 비구조화 데이터를 저장할 수 있는 데이터 웨어하우스보다
data but as well semi and unstructured data
23:55:30
혼합된 유형의 데이터가 있을 경우 이 접근 방식을 일반적으로 사용합니다.
we usually use this approach if you have mixed types of data
23:55:33
데이터베이스 테이블, 로그, 이미지, 비디오와 같은
like database tables logs images videos and
23:55:36
보고뿐만 아니라 고급 분석이나 머신 러닝에도 집중하고 싶지만
your business want to focus not only on reporting but as well on
23:55:40
데이터 웨어하우스처럼 그렇게 조직화되어 있지 않으며, 너무 많은 비조직화된 데이터는
advanced analytics or machine learning but it's not
23:55:43
데이터 늪으로 변할 수 있습니다.
that organized like a data warehouse and data leaks if it's
23:55:46
너무 많은 비조직화된 데이터는 데이터 늪으로 변할 수 있으며
too much unorganized can turns into data swamp
23:55:49
이제 다음 접근 방식이 필요합니다. 그래서 다음
and this is where we need the next approach so the next
23:55:52
우리는 데이터 레이크 하우스를 구축할 수 있습니다. 그래서
one we can go and build data lake house so it
23:55:55
데이터 웨어하우스와 데이터 레이크의 혼합과 같습니다. 다양한 유형의 데이터를
is like a mix between data warehouse and data lake you
23:55:58
데이터 레이크에서 가져올 수 있는 유연성을 얻지만 여전히 구조화하고 조직화하고 싶습니다.
get the flexibility of having different types of data from
23:56:02
데이터 웨어하우스에서 하는 것처럼 데이터를 구조화하고 조직화하고 싶습니다. 그래서 이 두 단어를 혼합합니다.
the data lake but you still want to structure and organize your
23:56:05
데이터 웨어하우스에서 하는 것처럼 데이터를 혼합하여 두 단어를 하나로 만듭니다.
data like we do in the data warehouse so you mix those two words
23:56:08
이것은 아키텍처를 구축하는 매우 현대적인 방법이며, 현재 제가 가장 좋아하는 데이터 관리 시스템 구축 방법입니다. 최근의 접근 방식은 데이터 메쉬를 구축하는 것입니다. 이것은 조금 다릅니다.
into one and this is a very modern way on how to build that architect and this is currently my favorite way of building data management system now the last and very recent approach is to build data mesh So this is a little bit different.
23:56:20
중앙 집중식 데이터 관리 시스템을 갖는 대신, 데이터 메쉬의 아이디어는 분산화하는 것입니다.
Instead of having centralized data management system, the idea now in the data mesh is to make it decentralized.
23:56:26
중앙 집중식 데이터 관리 시스템을 가질 수 없습니다. 중앙 집중식이라고 하면 항상 병목 현상을 의미합니다.
You cannot have like one centralized data management system because always if you say centralized, then it means bottleneck.
23:56:33
대신 여러 부서와 여러 도메인이 있으며, 각 부서가 데이터 제품을 구축하고 이를 다른 부서와 공유합니다.
So instead you have multiple departments and multiple domains where each one of them is building a data product and sharing it with the others.
23:56:40
이제 이러한 접근 방식 중 하나를 선택해야 합니다. 이 프로젝트에서는 데이터 웨어하우스에 집중할 것입니다.
So now you have to go and pick one of those approaches. And in this project, we will be focusing on the data warehouse.
23:56:46
이제 질문은 데이터 웨어하우스를 어떻게 구축할 것인가입니다. 데이터 웨어하우스를 구축하는 방법에는 네 가지 다른 접근 방식이 있습니다.
So now the question is how to build the data warehouse? Well, there is as well four different approaches on how to build it.
23:56:52
첫 번째는 N1 접근 방식입니다. 다시 말해, 소스가 있고 첫 번째 레이어에서 원시 데이터가 도착하는 스테이징부터 시작합니다.
The first one is the N1 approach. So again, you have your sources and the first layer, you start with the staging where the raw data is landing.
23:57:00
그 다음 레이어에서는 데이터를 엔터프라이즈 데이터 웨어하우스라고 하는 곳에서 구성하며, 여기서 데이터를 제3 정규 형식을 사용하여 모델링합니다.
And then the next layer, you organize your data in something called enterprise data warehouse, where you go and model the data using the third normal format.
23:57:09
테이블을 구조화하고 정규화하는 방법에 관한 것입니다.
It's about like how to structure and normalize your tables.
23:57:12
여러 소스에서 새로운 통합 데이터 모델을 구축하고 있습니다.
So you are building a new integrated data model from
23:57:15
그런 다음 세 번째 레이어로 가면 데이터 마트라고 불리는 곳으로 갑니다.
the multiple sources and then we go to the third layer it's called
23:57:18
여기서 작은 하위 집합을 가져옵니다.
the data marts where you go and take like small subset of
23:57:21
데이터 웨어하우스를 설계하는 방법
the data warehouse and you design it in a way
23:57:24
보고용으로 소비될 준비가 된 방식으로
that is ready to be consumed from reporting and
23:57:27
예를 들어 고객과 같은 하나의 주제에만 집중합니다
it focus on only one topic like for example the customers
23:57:31
판매 또는 제품 후에
sales or products and after that you go
23:57:34
BI 도구인 Power BI 또는 Tableau를 연결합니다
and connect your bi tool like power bi or tableau to the
23:57:37
데이터 마트를 통해 세 가지 레이어를 준비합니다
data marts so with that you have three layers to prepare the
23:57:40
보고하기 전에 데이터를 준비합니다. 다음으로
data before reporting now moving on to the next one we have the
23:57:43
캠펠 접근 방식을 소개합니다. 그는 기업 데이터 웨어하우스를
kempel approach he says you know what building this enterprise
23:57:46
구축하는 것이 많은 시간을 낭비한다고 말합니다.
data warehouse it is wasting a lot of time so
23:57:50
우리가 할 수 있는 것은 스테이지 레이어에서 즉시
what we can do we can jump immediately from the stage layer
23:57:53
최종 데이터 마트로 점프하는 것입니다. 기업 데이터 웨어하우스를
to the final data marts because building this enterprise
23:57:56
구축하는 것은 큰 어려움이며 보통 많은 시간을 낭비합니다.
data warehouse it is a big struggle and usually waste a
23:57:59
그래서 그는 항상 당신이 데이터 마트를 빠르게 구축하는 데 집중하기를 원합니다.
lot of time so he always wants you to focus and building the
23:58:03
누구보다 빠른 접근 방식이지만 시간이 지나면 데이터 마트에서 혼란이 생길 수 있습니다.
data marts quickly as possible so it is faster approach
23:58:06
당신이 항상 큰 그림에 집중하지 않기 때문에
than anyone but with the time you might get chaos in the data marts
23:58:09
같은 변환과 통합을 반복할 수 있습니다.
because you are not always focusing in the big picture and you might be
23:58:13
서로 다른 데이터 마트에서 같은 변환과 통합을 반복할 수 있습니다.
repeating same transformations and integrations in
23:58:16
속도와 일관된 데이터 웨어하우스 간의 균형이 필요합니다.
different data marts so there is like trade-off between the speed
23:58:19
세 번째 접근 방식인 데이터 볼트를 소개합니다.
and consistent data warehouse now moving on to
23:58:22
우리는 여전히 스테이지와 데이터 마트를 가지고 있지만
the third approach we have the data vault so we still have the
23:58:25
중간에 중앙 데이터 웨어하우스가 필요하다고 말합니다.
stage and the data marts but it says we still need this
23:58:28
원시 볼트에는 원본 데이터가 있지만 비즈니스 볼트에는 데이터 마크를 준비하는 모든 비즈니스 규칙과 변환이 있습니다.
central data warehouse in the middle but this middle layer we're gonna bring more standards and rules so it It tells you to split this middle layer into two layers, the raw vault and the business vaults.
23:58:40
데이터 볼트는 마지막 접근 방식과 매우 유사하지만
In the raw vault, you have the original data, but in the business vault, you have all the business rules and transformations that prepares the data for the data marks.
23:58:48
중간 레이어에 더 많은 표준과 규칙을 가져옵니다.
So data vault, it is very similar to the end one, but it brings more standards and rules to the middle layer.
23:58:55
이제 네 번째 접근 방식을 추가할 것입니다.
Now I'm going to go and add a fourth one that I'm going to call it medallion architecture.
23:59:00
그리고 이것이 제가 가장 좋아하는 것입니다. 이해하기 쉽고 만들기 쉽습니다.
And this one is my favorite one because it is very easy to understand and to build.
23:59:05
그래서 세 가지 레이어, 즉 동, 은, 금을 만들 것이라고 합니다. 동 레이어는 무대와 매우 유사합니다.
So it says you're going to go and build three layers, bronze, silver, and gold. The bronze layer, it is very similar to the stage.
23:59:11
하지만 우리는 시간이 지나면서 무대 레이어가 매우 중요하다는 것을 이해했습니다. 원본 데이터를 그대로 유지하는 것이 추적성과 문제 해결에 많은 도움이 됩니다.
But we have understood with the time that the stage layer is very important because having the original data as it is, it's going to help a lot by traceability and finding issues.
23:59:21
다음 레이어는 은 레이어입니다. 여기서 우리는 변환과 데이터 정리를 수행하지만, 아직 비즈니스 규칙을 적용하지 않습니다.
Then the next layer, we have the silver layer. It is where we do transformations, data cleansing, but we don't apply yet any business rules.
23:59:28
이제 마지막 레이어인 금 레이어로 넘어갑니다. 데이터 마트와 매우 유사합니다.
Now moving on to the last layer, the gold layer. It is as well very similar to the data marts.
23:59:33
하지만 여기서는 보고용뿐만 아니라 머신 러닝, AI 및 다양한 목적을 위한 다양한 유형의 객체를 만들 수 있습니다.
But there we can build different type of objects, not only for reporting, but as well for machine learning, for AI, and for many different purposes.
23:59:41
그래서 이것들은 데이터 제품으로 공유하고 싶은 비즈니스 준비 객체와 같습니다.
So they are like business ready objects that you want to share as a data product.
23:59:46
그래서 이것들은 데이터 웨어하우스를 구축하기 위해 사용할 수 있는 네 가지 접근 방식입니다.
So those are the four approaches that you can use in order to build a data warehouse.
23:59:51
다시 말해, 데이터 아키텍처를 구축하고 있다면 어떤 접근 방식을 따를 것인지 지정해야 합니다.
So again, if you are building a data architecture, you have to specify which approach you want to follow.
23:59:56
처음에 우리는 우리 집에서 구축하고 싶다고 말했으며, 그런 다음 결정해야 합니다.
So at the start we said we want to build it at our house and then we have to decide
24:00:00
데이터 웨어하우스를 구축하는 방법에 대한 네 가지 접근 방식 중에서. 이번 프로젝트에서는 메달리온 아키텍처를 사용할 것입니다.
between those four approaches on how to build a data warehouse. And in this project, we will be using the Medallion architecture.
24:00:05
그래서 이것은 데이터 아키텍처를 구축하는 첫 번째 단계로서 답해야 할 매우 중요한 질문입니다.
So this is a very important question that you have to answer as the first step of building a data architecture.
24:00:11
좋습니다, 그래서 그로 인해 접근 방식을 결정했습니다. 이제 완료로 표시할 수 있습니다.
All right, so with that, you have decided on the approach. So we can go and mark it as done.
24:00:16
다음 단계는 데이터 웨어하우스의 레이어를 설계하는 것입니다.
The next step, we're going to go and design the layers of the data warehouse.
24:00:24
이제 각 레이어에 대한 100% 표준 방식과 규칙이 있는 것은 아닙니다.
Now, there is like not 100% standard way and rules for each layer.
24:00:29
데이터 아키텍트로서 해야 할 일은 각 레이어의 목적을 정확히 정의하는 것입니다. 그래서 우리는 동 레이어부터 시작합니다.
What you have to do as a data architect, you have to define exactly what is the purpose of each layer. So we start with the bronze layer.
24:00:37
그래서 우리는 원본 데이터가 그대로 저장될 것이라고 말합니다. 왜 그렇게 하는 걸까요?
So we say it's going to store raw and unprocessed data as it is from the sources. And why we are doing that?
24:00:43
추적성과 디버깅을 위해서입니다. 원시 데이터를 보관하는 레이어가 있다면, 원본 데이터가 그대로 있는 것이 매우 중요합니다.
It is for traceability and debugging. If you have a layer where you are keeping the raw data, it is very important to have the data as it is from the sources.
24:00:51
문제가 발생할 경우 특정 소스의 데이터를 조사하기 위해 항상 동 레이어로 돌아갈 수 있습니다.
Because we can go always back to the bronze layer and investigate the data of a specific source if something goes wrong.
24:00:58
그래서 주요 목표는 원시 데이터가 손대지 않은 상태로 유지되는 것입니다.
So the main objective is to have raw untouched data.
24:01:02
이것은 데이터 엔지니어가 문제의 근본 원인을 분석하는 데 도움이 될 것입니다. 이제 서버 레이어로 넘어갑니다.
That's going to help you as a data engineer by analyzing the root cause of issues. Now moving on to the server layer.
24:01:08
여기는 깨끗하고 표준화된 데이터를 저장할 레이어입니다.
It is the layer where we're going to store clean and standardized data.
24:01:12
그리고 여기서 우리는 최종 레이어를 위해 데이터를 준비하기 위한 기본 변환을 수행할 것입니다.
And this is the place where we're going to do basic transformations in order to prepare the data for the final layer.
24:01:18
이제 코드 레이어는 비즈니스 준비 데이터를 포함할 것입니다.
Now for the code layer, it's going to contain business-ready data.
24:01:21
그래서 여기서의 주요 목표는 비즈니스 사용자와 분석가가 보고서 및 분석을 구축할 수 있는 데이터를 제공하는 것입니다.
So the main goal here is to provide data that could be consumed by business users and analysts in order to build reporting and analytics.
24:01:29
따라서 여기서의 주요 목표는 비즈니스 사용자와 분석가가 보고서 및 분석을 구축할 수 있도록 데이터를 제공하는 것입니다.
So with that, we have defined the main goal for each layer. Now, next, what I would like to do is to define the object types.
24:01:36
데이터 웨어하우스와 데이터베이스에 대해 이야기하고 있으므로 일반적으로 두 가지 유형, 즉 테이블 또는 뷰가 있습니다.
And since we are talking about a data warehouse and database, we have here generally two types, either a table or a view.
24:01:42
우리는 동상 레이어와 은색 레이어에 테이블을 사용할 것입니다. 그러나 금 레이어는 뷰를 사용할 것입니다.
So we are going for the bronze layer and the silver layer with tables. But for the gold layer, we are going with the views.
24:01:48
최고의 관행은 데이터 웨어하우스의 마지막 레이어는 뷰를 사용하여 가상으로 만드는 것입니다.
So the best practice says for the last layer in your data warehouse, make it virtual using views.
24:01:53
이것은 많은 동적성과 물론 속도를 제공합니다.
it's gonna gives you a lot of dynamic and of course speed in order
24:01:57
이를 구축하기 위해 로드 프로세스를 만들 필요가 없기 때문에
to build it since we don't have to make a load process for it and
24:02:00
이 프로젝트에서는 전체 로드를 정의하기로 결정했습니다.
now the next step is that we're gonna go and define the load method so
24:02:03
잘라내고 삽입하는 방법이 더 빠르고
in this project i have decided to go with the full load using the method
24:02:06
훨씬 더 쉬우므로 동상 레이어에는 전체 로드를 사용할 것입니다.
of truncating and inserting it is just faster and
24:02:09
은색 레이어에도 전체 로드를 사용할 것입니다.
way easier so we're gonna say for the bronze layer we're gonna go with the full load and
24:02:12
뷰에는 로드가 필요하지 않습니다.
you have to specify as well for the silver layer as well we're gonna go with
24:02:15
테이블을 사용할 때마다 로드 프로세스를 정의해야 합니다.
the full load and of course for the views we don't need any load
24:02:19
전체 로드와 증분 로드로 로드 방법을 정의해야 합니다.
process so each time you decide to go with tables you have
24:02:22
이제 매우 흥미로운 부분인 데이터 변환으로 넘어갑니다.
to define the load methods with our full load incremental loads and
24:02:25
동상 레이어는 이 주제에 대해 가장 쉬운 것입니다.
so on now we come to the very interesting part the data transformations
24:02:28
변환이 없기 때문에
now for the bronze layer it is the easiest one about this topic
24:02:31
데이터를 건드리지 않겠다고 다짐해야 합니다.
because we don't have any transformations we have
24:02:34
조작하지 말고 아무것도 변경하지 마십시오.
to commit ourselves to not touch the data do
24:02:38
문제가 생기면 동상 레이어에서 그대로 남아 있습니다.
not manipulate it don't change anything so it's gonna stay as
24:02:41
이제 은색 레이어로 넘어갑니다.
it is if it comes bad it's gonna stay bad in the bronze layer
24:02:44
우리는 깨끗하고 표준화된 데이터를 만들어야 합니다.
and now we come to the silver layer where we have the heavy lifting as
24:02:47
그를 위해 다양한 유형의 변환이 필요합니다.
we committed in the objective we have to make clean and standardized
24:02:50
데이터 정화 및 데이터 표준화 작업을 해야 합니다.
data and for that we have different types of transformations
24:02:54
데이터 정규화, 새로운 열을 도출해야 합니다.
so we have to do data cleansing data standardizations
24:02:57
데이터 풍부화 작업도 해야 합니다.
data normalizations we have to go and derive new columns
24:03:00
데이터 보강이 필요하므로 여러 가지
and data enrichment so there are like bunch
24:03:03
변환 작업을 수행하여 데이터를 준비해야 합니다.
of transformation that we have to do in order to prepare the
24:03:06
데이터에 집중하여 데이터를 변환하는 것이 목표입니다.
data our focus here is to transform the data to
24:03:10
데이터를 깔끔하게 정리하고 기준에 맞추고 모든
make it clean and following standards and try to push all
24:03:13
비즈니스 변환을 다음 단계로 진행해야 합니다.
business transformations to the next layer so that means in
24:03:16
신의 계층에서 비즈니스 변환에 집중할 것입니다.
the god layer we will be focusing on business transformations
24:03:19
소비자와 사용 사례에 필요한
that is needed for the consumers for the use cases so
24:03:22
여기서 우리는 소스 시스템 간의 데이터 통합을 수행합니다.
what we do here we do data integrations between source system
24:03:26
데이터 집계를 수행하고 많은 비즈니스
we do data aggregations we apply a lot of business
24:03:29
논리와 규칙을 적용하여 데이터 모델을 구축합니다.
logics and rules and we build a data model that
24:03:32
예를 들어 비즈니스 인텔리전스를 위해 준비된
is ready for for example business intelligence so here we do
24:03:35
많은 비즈니스 변환을 수행하고 은색 계층에서
a lot of business transformations and in the silver layer
24:03:38
기본 데이터 변환을 수행하므로 여기서 정말
we do basic data transformations so it is really here
24:03:41
어떤 변환을 각 계층에서 수행할지 결정하는 것이 중요합니다.
very important to make the fine decisions what
24:03:45
그 규칙을 준수해야 하며 다음 측면은
type of transformations to be done in each layer and make
24:03:48
청동 계층과 은색 계층의 데이터 모델링에 관한 것입니다.
sure that you commit to those rules now the next aspect
24:03:51
소스 시스템에서 오는 데이터 모델을 깨지 않을 것입니다.
is about the data modeling in the bronze layer and the silver layer
24:03:54
소스 시스템이 다섯 개의 테이블을 제공하면
we will not break the data model that comes from the source system
24:03:57
여기서 다섯 개의 테이블이 있으며 은색 계층에서도
so if the source system deliver five tables we're gonna have
24:04:00
비정규화하거나 정규화하지 않거나 새로 만들지 않습니다.
here like five tables and as well in the silver layer we will not go
24:04:03
소스 시스템에서 오는 그대로 두고 데이터 모델을 구축할 것입니다.
and denormalize or normalize or like make
24:04:06
금색 계층에서 데이터 모델을 정의해야 합니다.
something new we're gonna leave it exactly like it comes from the source system because what we're gonna do we're gonna build the data model
24:04:13
따를 데이터 모델을 정의해야 하며 스타 스키마를 따르나요?
in the gold layer and here you have to define which data model
24:04:16
아니면 집계된 객체를 만들고 있나요?
you want to follow are you following the star schema the snowflake
24:04:19
모든 데이터 모델 유형 목록을 작성해야 합니다.
or are you just making aggregated objects so you have to
24:04:22
모든 데이터 모델 유형의 목록을 작성하세요.
go and make a list of all data models types that you're gonna follow
24:04:25
그 금 레이어에서 무엇을 지정할 수 있는지.
in that gold layer and at the end what you can specify in each layer
24:04:28
타겟 오디언스입니다. 이것은 매우 중요한 결정입니다.
is the target audience and this is of course a very important decision
24:04:31
브론즈 레이어에서는 어떤 최종 사용자에게도 접근을 허용하지 않아야 합니다.
in the bronze layer you don't want to give access to any end
24:04:35
데이터 엔지니어만 브론즈 레이어에 접근할 수 있도록 해야 합니다.
user it is really important to make sure that only data engineers
24:04:38
데이터 엔지니어는 물론 데이터 분석가와 데이터 과학자도 접근할 수 있어야 합니다.
access the bronze layer it makes no sense for data analysts or data scientists to go to the bad data because you have a better version for that in the silver layer.
24:04:48
하지만 원시 데이터 모델을 처리할 수 없는 비즈니스 사용자에게는 제공하지 않아야 합니다.
So in the silver layer, of course, the data engineers have to have an access to it and as well the data analysts and the data scientists and so on.
24:04:54
비즈니스 사용자에게는 더 나은 레이어를 제공할 수 있습니다. 그것이 금 레이어입니다.
But still, you don't give it to any business user that can't deal with the raw data model from the sources.
24:05:01
금 레이어는 데이터 분석가와 비즈니스 사용자에게 적합합니다.
Because for the business users, you can get a better layer for them. And that is the gold layer.
24:05:06
비즈니스 사용자는 서버 레이어의 기술적 지식이 깊지 않습니다.
So the gold layer, it is suitable for the data analyst and as well the business users.
24:05:11
여러 레이어를 설계할 때는 모든 주제를 논의하고 명확한 결정을 내려야 합니다.
Because usually the business users don't have a deep knowledge on the technicality of the server layer.
24:05:16
여러 레이어를 설계할 때는 모든 주제를 논의하고 명확한 결정을 내려야 합니다.
So if you are designing multiple layers, you have to discuss all those topics and make clear decisions for each layer. All right, my friends.
24:05:24
설계에 들어가기 전에 각 데이터 아키텍트가 알아야 할 비밀 원칙 개념을 말씀드리겠습니다.
So now before we proceed with the design, I want to tell you a secret principle concepts that each data architect must know.
24:05:31
그것은 관심사의 분리입니다. 그게 무엇인가요?
And that is the separation of concerns. So what is that?
24:05:35
아키텍처를 설계할 때 복잡한 시스템을 더 작은 독립적인 부분으로 나누어야 합니다.
As you are designing an architecture, you have to make sure to break down the complex system into smaller independent parts.
24:05:41
각 부분은 특정 작업에 책임이 있습니다. 여기서 마법이 시작됩니다.
And each part is responsible for a specific task. And here comes the magic.
24:05:46
아키텍처의 구성 요소는 중복되어서는 안 됩니다.
The component of your architecture must not be duplicated. So you cannot have two parts are doing the same thing.
24:05:53
모든 것을 혼합하지 않는 것이 중요합니다. 이는 큰 프로젝트에서 가장 큰 실수 중 하나입니다.
So the idea here is to not mix everything. And this is one of the biggest mistakes in any big projects.
24:06:00
거의 모든 곳에서 그런 것을 보았습니다. 좋은 데이터 아키텍트는 이 개념을 따릅니다.
And I have seen that almost everywhere. So a good data architect follow this concept, this principle.
24:06:06
예를 들어, 우리의 데이터 아키텍처를 보면 이미 그렇게 했습니다.
So for example, if you are looking to our data architecture, we have already done that.
24:06:10
각 레이어에 대해 고유한 작업 세트를 정의했습니다.
So we have defined a unique set of tasks for each layer. So for example, we have said in the silver layer, we do data cleansing.
24:06:18
금 레이어에서는 비즈니스 변환을 수행합니다.
But in the gold layer, we do business transformations. and
24:06:21
그렇게 하면 비즈니스 변환을 허용하지 않습니다.
with that you will not be allowing to do any business transformations
24:06:24
브론즈 레이어와 금 레이어에서도 마찬가지입니다.
in the silver layer and the same thing goes for the gold layer
24:06:27
금 레이어에서는 데이터 클렌징을 수행하지 않으므로 각 레이어는 고유한 작업을 가지고 있습니다.
you don't do in the gold layer any data cleansing so each layer
24:06:31
각 레이어는 고유한 작업을 가지고 있으며
has its own unique tasks and the same thing
24:06:34
브론즈 레이어와 실버 레이어에도 동일하게 적용됩니다.
goes for the bronze layer and the silver layer you do not allow to
24:06:37
소스 시스템에서 실버 레이어로 직접 데이터를 로드할 수 없습니다.
load data from the source systems directly to the silver
24:06:40
브론즈 레이어가 첫 번째 레이어로 결정되었기 때문에
layer because we have decided the landing layer the first layer is the bronze layer otherwise you will have like set of
24:06:47
브론즈 레이어에 먼저 로드되는 소스 시스템이 있습니다.
source systems that are loaded first to the bronze layer and
24:06:50
또 다른 세트는 레이어를 건너뛰고 실버로 갑니다.
another set is skipping the layer and going to the silver
24:06:53
그래서 우리는 두 개의 서로 다른 레이어에서 데이터 수집을 하고 있습니다.
and with that we have overlapping you are doing data ingestion
24:06:57
이런 사고방식으로 문제를 분리하면
in two different layers so my friends if you have this
24:07:00
최고의 데이터 아키텍트가 될 것입니다.
mindset separation of concerns i promise you you're gonna
24:07:03
데이터 아키텍처를 구축하는 방법에 대한 표준은 없습니다.
be a top data architect so think about it all right my friends so with that we have designed the layers of the data warehouse we can go and close it the next step we're gonna go to draw you and start drawing the data architecture.
24:07:19
데이터 아키텍처의 다양한 레이어를 보여줘야 합니다.
So there is like no one standard on how to build a data architecture. You can add your style and the way that you want.
24:07:25
이런 상자를 가져와서 조금 더 크게 만들어 보겠습니다.
So now the first thing that we have to show in that architecture is the different layers that we have. The first layer is the source system layer.
24:07:32
채우기를 제거하고 선을 점선으로 만들겠습니다.
So let's go and take a box like this and make it a little bit bigger. And I'm just gonna go and make the design.
24:07:38
그 후에 색상을 이렇게 변경할 것입니다.
So I'm gonna remove the fill and make the line dotted one.
24:07:41
회색으로, 이제 첫 번째 레이어를 위한 컨테이너가 생겼습니다.
and after that i'm gonna go and change maybe the color to something like this
24:07:44
그 위에 텍스트를 추가해야 합니다.
gray so now we have like a container for the first
24:07:47
또 다른 상자를 가져와서 그 안에 입력하겠습니다.
layer and then we have to go and add like a text on top of it so what
24:07:51
소스라고 입력하고 스타일을 적용하겠습니다.
i'm gonna do i'm gonna take another box let's go and type inside it
24:07:54
글꼴 크기를 24로 조정하고
sources and i'm gonna go and style it so i'm gonna go to the
24:07:57
선을 제거하고 조금 더 작게 만들어서 위에 올리겠습니다.
text and make it maybe 24 and then remove
24:08:00
이것이 첫 번째 레이어이며 데이터가 오는 곳입니다.
the lines like this make it a little bit smaller and put it on top so this is the first layer this is where the data come from
24:08:08
그런 다음 데이터가 데이터 웨어하우스 안으로 들어갑니다.
and then the data gonna go inside a data warehouse so i'm
24:08:11
이것을 복제하겠습니다. 이것은
just gonna go and duplicate this one this one is the
24:08:14
데이터 웨어하우스입니다.
data warehouse all
24:08:19
자, 이제 세 번째 레이어는 소비자가 될 것입니다.
right so now the third layer what is gonna be it's
24:08:22
소비자들이 이 데이터를 소비할 것입니다.
gonna be the consumers who will be consuming this data
24:08:25
이제 데이터 웨어하우스 안에 세 개의 레이어가 있을 것입니다.
warehouse so i'm gonna put another box and say this is the consume layer okay so those are the three containers now inside the data warehouse we We have decided to build it using the Medellin architecture.
24:08:37
이것은 브론즈 레이어입니다. 이제 디자인을 추가해야 합니다.
So we're going to have three layers inside the warehouse. So I'm going to take again another box. I'm going to call this one.
24:08:45
그리고 텍스트와 아마도 20 정도로 만들고 조금 더 작게 만들겠습니다.
This is the bronze layer. And now we have to go and put a design for it. So I'm going to go with this color over here.
24:08:50
그 아래에는 컴포넌트가 있을 것입니다. 이것은 컨테이너의 제목입니다.
And then the text and maybe something like 20. And then make it a little bit smaller. And just put it here.
24:08:57
안에 있는 텍스트를 제거하고 채우기를 제거합니다. 이 컨테이너는 브론즈 레이어용입니다.
And beneath that we're going to have the component. So this is just the title of a container. So I'm going to have it like this.
24:09:04
그리고 물론 색상을 회색으로 변경할 수 있습니다.
remove the text from inside it and remove the filling so this container is for the bronze layer let's go and duplicate it for the next one so this one gonna be the silver layer
24:09:17
은색이기 때문에 그리고 선들을 제거하고 채우기를 제거합니다.
and of course we can go and change the coloring to gray because
24:09:20
세 번째 레이어는 골드 레이어가 될 것입니다.
it is silver and as well the lines and remove the filling great and now maybe i'm gonna make the font as bold all right now the
24:09:29
그것을 위해 색상을 선택해야 합니다.
third layer gonna be the gold layer and
24:09:32
여기에는 노란색 같은 것이 있습니다. 컨테이너도 마찬가지입니다.
we have to go and pick a color for that so style and
24:09:36
채우기를 제거합니다. 이제 서로 다른
here we have like something like yellow the same thing for the container i
24:09:39
레이어를 보여주고 있습니다.
remove the filling so with that we are showing now the different
24:09:42
이제 이 컨테이너는 비어 있습니다.
layers inside our data warehouse now those containers are
24:09:46
각각의 내부로 들어가서 내용을 추가할 것입니다.
empty what we're gonna do we're gonna go inside each one of them and start adding
24:09:49
소스에서 서로 다른 유형의 소스 시스템을 명확히 하는 것이 중요합니다.
contents so now in the sources it is very important to make it clear what are the different types of source system that you you are connecting to the data warehouse
24:09:57
실제 프로젝트에는 여러 유형이 있습니다.
because a real project, there are like multiple types You might have a database API files Kafka and here it's important to show those different types in our projects We have folders and inside those folders.
24:10:08
CSV 파일이 있습니다. 이제 무엇을 해야 할까요?
We have CSV files So now what you have to do We have to make it clear in
24:10:11
이 레이어에서 프로젝트의 입력이 CSV 파일입니다.
this layer that the input for our project is CSV
24:10:14
더 많은 결과를 얻고 아이콘 중 하나를 선택합니다.
file So it really depends how you want to show that I'm gonna go over here and say maybe folder And then I'm gonna go and take the folder and put it here inside and then maybe search for file
24:10:25
이 아이콘으로 가서 더 작게 만들겠습니다.
more results and go pick one of those icons for example i'm
24:10:28
폴더 위에 추가합니다.
gonna go with this one over here so i'm gonna make it smaller and
24:10:31
소스가 데이터베이스가 아님을 분명히 합니다.
add it on top of the folder so with that we make it clear for everyone seeing
24:10:35
API가 아니며 폴더 안의 파일입니다.
the architecture that the sources is not a database
24:10:38
프로젝트에 관련된 소스 시스템을 보여주는 것이 중요합니다.
is not an api it is a file inside the folder
24:10:41
그래서 지금 여기서 매우 중요한 것은 프로젝트에 관련된 소스 시스템이 무엇인지 보여주는 것입니다. 그래서 여기서 우리가 할 일은 이름을 정하는 것입니다. 예를 들어
so now very important here to show is the source systems what are the sources that is involved in the project so here what we're gonna do we're gonna go and give it a name for example
24:10:50
우리는 이렇게 끌어온 crm이라는 소스가 있습니다.
we have one source called crm pulled like this and
24:10:53
아마 아이콘을 만들고 또 다른 소스를 가지고 있습니다.
maybe make the icon and we have another source called
24:10:56
erp입니다. 그래서 우리는 복사해서 여기 두겠습니다.
erp so we're gonna go and duplicate it put it over here
24:10:59
그리고 이름을 erp로 바꿉니다. 이제 모든 사람을 위한 것입니다.
and then rename it erp so now it is for everyone
24:11:02
명확하게 이 프로젝트에는 두 개의 소스가 있으며 사용되는 기술은
clear we have two sources for this project and the technology is used
24:11:05
단순히 파일입니다. 그래서 이제 우리가 할 수 있는 것은 이 상자 안에 설명을 추가하여 더 명확하게 만드는 것입니다. 그래서 제가 할 일은 설명을 나누기 위해 한 줄을 가져오는 것입니다.
is simply a file so now what we can do as well we can go and add some descriptions inside this box to make it more clear so what i'm gonna do i'm gonna take a line because i want to split the description
24:11:15
아이콘에서 이렇게 하고 회색으로 만들고
from the icons something like this and make it gray and
24:11:18
그 아래에 텍스트를 추가하고 우리는 말할 것입니다.
then below it we're gonna go and add some text and we're gonna say
24:11:21
csv 파일이며 다음 포인트는
is csv file and the next point
24:11:25
인터페이스는 단순히
and we can say the interface is simply
24:11:28
폴더 안의 파일이며 물론 추가할 수 있습니다.
files in folder and of course you can go
24:11:31
사양 및 설명에 대해
and add any specifications and explanation about
24:11:34
소스가 데이터베이스인 경우 데이터베이스 유형을 볼 수 있습니다.
the sources if it is a database you can see the type of the database
24:11:37
그리고 우리는 데이터 아키텍처에서 무엇을 명확하게 했는지
and so on so that we made it in the data architecture clear what
24:11:41
우리 데이터 웨어하우스의 소스가 무엇인지
are the sources of our data warehouse and now the next step what we're do
24:11:44
우리가 할 다음 단계는
we're gonna go and design the content of the bronze silver
24:11:47
브론즈, 실버 및 골드의 내용을 디자인하는 것입니다.
and gold so i'm gonna start by adding like an icon in each
24:11:50
그래서 각 컨테이너에 아이콘을 추가하는 것으로 시작하겠습니다.
container it is to show about that we are talking about database
24:11:53
이것은 우리가 데이터베이스에 대해 이야기하고 있음을 보여줍니다.
so what we're gonna do we're gonna go and search for database
24:11:57
그래서 우리가 할 일은 데이터베이스를 검색하는 것입니다.
and then more results more results i'm
24:12:00
그리고 더 많은 결과가 나올 것입니다.
gonna go with this icon over here so let's go and make it
24:12:03
여기서 이 아이콘으로 가서 더 크게 만들겠습니다.
bigger something like this maybe change the
24:12:06
이런 식으로 점의 색상을 변경할 수 있습니다.
color of dots so we're gonna have the bronze and as
24:12:09
브론즈와 실버, 골드가 있습니다. 이제 우리가 할 일은 이 레이어들 사이에 화살표를 추가하는 것입니다.
well here the silver and the gold so now what we're we're
24:12:13
이제 우리는 그 레이어들 사이에 화살표를 추가할 것입니다.
gonna do we're gonna go and add some arrows between those layers so
24:12:16
여기서 화살표를 검색할 수 있도록 가겠습니다.
we're gonna go over here so we can go and search for arrow and maybe
24:12:19
그 중 하나를 선택하고 여기에 놓겠습니다.
go and pick one of those let's go and put it here and we
24:12:22
그것에 대한 색상을 선택할 수 있습니다.
can go and pick a color for that maybe something like
24:12:25
이것을 조정하여 멋진 화살표를 만들 것입니다.
this and adjust it so now we're gonna have this nice arrow
24:12:28
이제 각 레이어에 대한 설명을 추가할 것입니다.
between all the layers just to explain the direction of our architecture right so we can read it from left to right and as well between the gold layer and the consume
24:12:38
데이터베이스 아래에 텍스트를 추가하겠습니다.
Okay, so now what I'm going to do next, we're going to go and add one statement about each layer, the main objective.
24:12:44
여기서 텍스트를 더 크게 만들겠습니다.
So let's go and grab a text and put it beneath the database. And we're going to say, for example, for the bronze layer, it's going to be the raw data.
24:12:51
다음은 은색 레이어에서 깨끗한 표준 데이터입니다.
Here we make the text bigger. So you are the raw data.
24:12:55
마지막으로 금색 레이어에서는 비즈니스 준비 데이터입니다.
And then the next one in the silver, you are clean standard data.
24:13:01
이로써 각 레이어의 목표를 명확히 합니다.
And then the last one for the gold, we can say business ready data.
24:13:07
아이콘 아래에 구분선을 추가할 것입니다.
so with that we make the objective clear for each layer now below
24:13:10
색상을 추가하고 그 아래에 추가할 것입니다.
all those icons what we're going to do we're going to have a separator again like
24:13:14
이 레이어의 가장 중요한 사양을 추가할 것입니다.
this make it like colored and beneath it we're going to add
24:13:17
각 레이어에 구분선을 추가하겠습니다.
the most important specifications of this layer so let's
24:13:20
그 아래에 텍스트가 필요합니다.
go and add those separators in each layer okay
24:13:24
브론즈 레이어의 객체 유형은 테이블입니다.
so now we need a text below it let's take this one here so
24:13:27
패치 처리를 하고 있습니다.
what is the object type of the broad layer it's going to be a table and we can go and add the load method we say this
24:13:35
스트리밍을 하지 않기 때문에 전체 로드입니다.
is patch processing since we are not
24:13:38
증분 로드를 하지 않기 때문에 여기서 말할 수 있습니다.
doing streaming we can say it is a full load we
24:13:41
트렁크와 삽입을 합니다.
are not doing incremental loads so we can say here
24:13:44
트렁크와 삽입 및
trunk and insert and
24:13:48
그런 다음 변환에 대한 섹션을 하나 더 추가할 수 있습니다.
then we add one more section maybe about the transformations so
24:13:51
변환이 없다고 말할 수 있습니다.
we can say no transformations and
24:13:54
데이터 모델에 대해 하나 더 추가할 건데, 우리는 없다고 말할 것입니다.
one more about the data model we're gonna say none as
24:13:58
이제 내가 할 일은 그 사양을 추가하는 것입니다.
is and now what i'm gonna do i'm gonna go and add those specifications
24:14:01
여기서 우리가 논의한 내용은
as well for the silver and gold so here what we have discussed the
24:14:04
객체 유형, 로드 프로세스, 변환 및
object type the load process the transformations and
24:14:08
데이터 모델을 깨뜨리는지 여부입니다.
whether we are breaking the data model or not the same thing
24:14:11
금 레이어에 대해 정말 멋진
for the gold layer so i can say with that we have really nice
24:14:14
데이터 웨어하우스의 레이어링이 있습니다.
layering of the data warehouse and what we are left is with the
24:14:17
여기 소비자들이 있으며 다양한 사용 사례를 추가할 수 있습니다.
consumers over here you can go and add the different use cases
24:14:20
데이터 웨어하우스에 접근할 수 있는 도구들입니다.
and tools that can access your data warehouse like for example
24:14:24
여기서 비즈니스 인텔리전스와 보고서를 추가하고 있습니다.
i'm adding here business intelligence and reporting maybe using
24:14:27
파워 BI 또는 태블로를 사용하여
power pi or tableau or you can say you can access my
24:14:30
내 데이터 웨어하우스에 접근하여 즉석 분석을 수행합니다.
data warehouse in order to do ad hoc analysis using the sql
24:14:33
SQL 쿼리를 사용하여 즉석 분석을 수행합니다.
queries and this is what we're going to focus on the projects after
24:14:37
우리가 데이터 웨어하우스를 구축한 후에 집중할 것입니다.
we build the data warehouse and as well you can offer it for
24:14:40
기계 학습 목적을 위해 제공할 수 있습니다.
machine learning purposes and of course it is really nice to add some icons
24:14:43
아키텍처에 아이콘을 추가하는 것이 좋습니다.
in your architecture and usually i use this nice websites called
24:14:46
이 멋진 웹사이트를 사용합니다.
flat icon it has really amazing icons that you can go and use it in your architecture now of course we can go and keep adding icons and stuff to explain the data architecture and as well the system.
24:14:56
플랫 아이콘은 정말 멋진 아이콘을 제공합니다.
Like for example, it is very important here to say which tools you are
24:15:00
이 데이터 웨어하우스를 구축하기 위해 사용하는 도구입니다.
using in order to build this data warehouse is it in the cloud are
24:15:03
Azure Databricks 또는 Snowflake를 사용하고 있습니다.
using azure databricks or maybe snowflake so
24:15:06
우리 프로젝트에 아이콘을 추가할 것입니다.
we're gonna go and add for our projects the icon of
24:15:09
우리는 이 데이터 웨어하우스를 완전히 SQL 서버에서 구축하고 있습니다.
sql server since we are building this data warehouse completely
24:15:12
현재로서는 매우 기쁩니다. 보시다시피 우리는
in the sql server so for now i'm really happy about it as you can see we
24:15:16
이제 계획이 있습니다. 좋아요, 여러분. 그래서 우리는 드로우를 사용하여 데이터 아키텍처를 설계했습니다. 그리고 이로써 우리는 이 에픽의 마지막 단계를 완료했습니다.
have now a plan right all right guys so with that we have designed the data architecture using the draw and with that we have done the last step in this epic
24:15:24
이제 데이터 아키텍처에 대한 디자인이 완료되었고, 이 에픽을 종료했다고 말할 수 있습니다. 이제 다음 단계로 넘어갑시다.
And now with that, we have a design for the data architecture and we can say we have closed this epic. Now let's go to the next one.
24:15:30
프로젝트를 준비하기 위한 첫 번째 단계를 시작하겠습니다. 여기서 첫 번째 작업은 상세한 프로젝트 계획을 만드는 것입니다.
We will start doing the first step to prepare our projects. And the first task here is to create a detailed project plan.
24:15:41
좋아요, 친구들. 이제 우리는 세 가지 레이어가 필요하다는 것이 분명해졌습니다.
All right, my friends, so now it's clear for us that we have three layers and we have to go and build them.
24:15:45
그래서 우리의 큰 에픽은 레이어 다음에 올 것입니다. 그래서 우리는 세 개의 에픽을 더 추가했습니다.
So that means our big epic is going to be after the layers. So we have added three more epic.
24:15:52
그래서 우리는 동층, 은층, 금층을 구축했습니다.
So we have build the bronze layer, build silver layer and gold layer.
24:15:55
그 후에 저는 프로젝트에서 따라야 할 다양한 작업을 정의하기 시작했습니다.
And after that, I went and started defining all the different tasks that we have to follow in the projects.
24:16:02
시작할 때 우리는 분석을 하고, 그 다음 코딩을 할 것입니다. 그리고 나서 테스트를 할 것입니다.
So at the start, we will be analyzing, then coding. And after that, we're going to go and do testing.
24:16:07
모든 것이 준비되면 우리는 커밋 작업을 할 것입니다. 마지막에는 작업을 깃 저장소에 커밋해야 합니다.
And once everything is ready, we're going to go and do commit stuff. And at the end, we have to commit our work in the get repo.
24:16:13
모든 에픽은 작업에서 같은 패턴을 따릅니다.
All those epics are following the same like pattern in the tasks.
24:16:17
이제 우리는 매우 상세한 프로젝트 구조를 가지고 있습니다.
So as you can see now, we have a very detailed project structure.
24:16:21
이제 데이터 웨어하우스를 구축하는 방법이 더 명확해졌습니다. 이 작업은 여기서 끝입니다.
And now things are more clear for us how we can build the data warehouse. So with that, we are done from this task.
24:16:28
이제 다음 작업은 프로젝트의 명명 규칙을 정의하는 것입니다.
And now the next task, we have to go and define the naming convention of the project.
24:16:37
좋아요. 이제 프로젝트의 이 단계에서 우리는 일반적으로 명명 규칙을 정의합니다. 그게 무엇인가요?
All right. So now at this phase of the projects, we usually define the naming conventions. So what's that?
24:16:41
프로젝트의 모든 것을 명명하기 위해 정의하는 규칙의 집합입니다.
It is set of rules that you define for naming everything in the projects,
24:16:47
데이터베이스 스키마 테이블이든
whether it is a database schema tables
24:16:50
저장 프로시저 폴더든 무엇이든
stored procedures folders anything and
24:16:53
프로젝트 초기 단계에서 그렇게 하지 않으면 혼란이 생길 수 있습니다.
if you don't do that at the early phase of the projects i promise
24:16:56
여러 개발자가 프로젝트에 참여하게 되고 각 개발자는
you chaos can happen because what can happen you will have
24:16:59
자신만의 스타일을 가지고 있습니다. 그래서 한 개발자는
different developers in your projects and each of those developers have
24:17:02
모든 것이 소문자로 되어 있고 언더스코어로 구분된 고객 차원 테이블을 명명할 수 있습니다.
their own style of course so one developer might name
24:17:06
제품 차원 테이블을 만들고 카멜 케이스를 사용할 수 있습니다.
a table dimension customers where everything is lowercase and between them underscore and you have another developer creating another table called dimension
24:17:14
단어 사이에 구분이 없고 첫 글자가 대문자로 시작합니다.
products but using the camel case so there is
24:17:17
그리고 아마도 dim_와 같은 접두사를 사용하는 다른 개발자가 있을 것입니다.
no separation between the words and the first character is capitalized
24:17:21
카테고리로 여기서 우리는 차원의 단축키를 가지고 있습니다.
and maybe another one using some prefixes like dim underscore
24:17:24
그래서 보시다시피 서로 다른 디자인과 스타일이 있습니다.
categories so we have here like a shortcut of the
24:17:27
프로젝트 중간에 문을 열어두면 어떤 일이 발생할 수 있습니다.
dimension so as you can see there are different designs and styles
24:17:30
모든 것이 일관성이 없다는 것을 알게 되고 모든 것을 다시 이름 짓는 큰 작업을 정의할 수 있습니다.
and if you leave the door open what can happen in the middle of the projects
24:17:33
문제가 발생할 수 있습니다. 모든 것이 일관성이 없다는 것을 알게 될 것입니다. 모든 것을 다시 이름 지을 큰 작업을 정의할 수 있습니다.
you will notice okay everything looks inconsistent and you can define a big task to go and rename everything
24:17:41
특정 역할을 따르기 때문에 이 모든 것을 낭비하는 대신
following a specific role so instead of wasting all this
24:17:44
이 단계에서 시간을 정하고 이름 규칙을 정의합니다.
time at this phase you go and define the naming conventions
24:17:47
그럼 이제 시작해 보겠습니다. 매우 중요한 결정입니다.
and let's go and do that so we will start with
24:17:50
어떤 이름 규칙을 따를 것인지에 대한 결정입니다. 전체 프로젝트에서
a very important decision and that is which naming
24:17:54
다양한 경우가 있습니다. 카멜 케이스, 파스칼 케이스
convention we're going to follow in the whole project so you have different
24:17:57
케밥 케이스와 스네이크 케이스와 같은 경우가 있습니다.
cases like the camel case the pascal case
24:18:00
이 프로젝트에서는 스네이크 케이스를 사용할 것입니다. 단어의 모든 글자는 소문자로 표시됩니다.
the kebab case and the snake case and
24:18:03
단어 사이의 구분은 언더스코어로 할 수 있습니다.
for this project we're going to go with the snake case where all the letters of a word going to be lowercase and the
24:18:10
예를 들어, 고객 정보라는 테이블 이름은
separation between words can be an underscore for
24:18:14
소문자로 작성되며, 정보도 소문자로 작성되고, 그 사이에
example a table name called customer info customer
24:18:17
언더스코어가 있습니다. 이것은 항상 세 번째 사항입니다.
is lower cased info is as well lower cased and between
24:18:20
데이터 프로젝트를 위해 결정해야 할 사항입니다. 두 번째 사항은
them an underscore so this is always the third thing that
24:18:23
언어를 결정하는 것입니다. 예를 들어, 저는 독일에서 일합니다.
you have to decide for your data projects the second thing is
24:18:26
항상 우리가 결정해야 할 사항이 있습니다.
to decide the language so for example i work in germany
24:18:29
독일어를 사용할지 영어를 사용할지 결정해야 합니다.
and there is always like a decision that we have to make whether
24:18:32
우리 프로젝트에서 사용할 언어를 결정해야 합니다. 매우 중요한
we use germany or english so we have to decide for our
24:18:35
일반 규칙은 예약어를 피하는 것입니다.
project which language we're use and a very important
24:18:39
따라서 예약어를 객체 이름으로 사용하지 마십시오.
general rule is that avoid reserved words
24:18:42
예를 들어, 테이블과 같은 예약어를 사용하지 마십시오.
so don't use a square reserved word as an object name
24:18:45
테이블 이름을 테이블로 주지 마십시오. 일반 원칙입니다.
like for example table don't give a table name as
24:18:48
예를 들어, 테이블 이름을 테이블로 주지 마십시오. 일반 원칙입니다.
a table so those are the general principles so those
24:18:52
전체 프로젝트에서 따라야 할 일반 규칙입니다.
are the general rules that you have to follow in the whole
24:18:55
이것은 테이블, 열, 저장 프로시저 등 모든 것에 적용됩니다.
project this applies for everything for tables columns
24:18:58
스크립트에서 제공하는 이름에 대한 규정이 있습니다. 여기에는 각 레이어에 대한 규칙 세트가 있습니다.
stored procedures any names that you are giving in your scripts now moving on we have specifications for the table names and here we have different set
24:19:06
규칙의 집합이 각 레이어에 대해 다릅니다.
of rules for each layer so here the rule says source
24:19:10
소스 시스템 엔터티라고 말하고 있습니다.
system underscore entity so we are saying all the
24:19:13
브론즈 레이어의 테이블은 소스 시스템 이름으로 시작해야 합니다.
tables in the bronze layer should start first with the source
24:19:16
예를 들어 crm 또는 arb와 같은 시스템 이름입니다.
system name like for example crm or arb and
24:19:20
그 후에 언더스코어가 있고 마지막에는
after that we have an underscore and then at the end we have
24:19:23
엔터티 이름 또는 테이블 이름이 있습니다.
the entity name or the table name so for example we have this table name crm underscore so that means this table comes
24:19:31
이 테이블 이름은 crm 언더스코어로 시작합니다.
from the source system CRM and then we have the table name, the entity name, customer info.
24:19:35
이 테이블은 CRM 소스 시스템에서 온 것입니다.
So this is the rule that we're going to follow in naming all tables in the bronze layer.
24:19:39
이것이 브론즈 레이어의 모든 테이블 이름 규칙입니다.
Then moving on to the silver layer, it is exactly like the bronze because we are not going to rename anything.
24:19:45
실버 레이어로 넘어가면 브론즈와 동일합니다.
We are not going to build any new data model. So the naming going to be one to one like the bronze.
24:19:51
우리는 새로운 데이터 모델을 만들지 않을 것입니다.
So it is exactly the same rules as the bronze.
24:19:54
골드 레이어로 가면 새로운 데이터 모델을 구축해야 합니다.
But if we go to the gold here, since we are building a new data model, we have to go
24:20:00
여러 소스를 통합하고 있기 때문에
and rename things. And since as well we are integrating multiple sources together,
24:20:04
테이블에서 소스 시스템 이름을 사용하지 않을 것입니다.
we will not be using the source system name in the tables. Because inside one table, you could have multiple sources.
24:20:11
모든 이름은 의미 있고 비즈니스에 맞는 이름이어야 합니다.
So the rule says all the names must be meaningful, business aligned names for the tables, starting with the category prefix.
24:20:18
여기서 규칙은 카테고리로 시작하고 언더스코어가 뒤따릅니다.
So here the rule says it starts with category, then underscore, and then entity. Now what is category?
24:20:24
코드 레이어에는 다양한 유형의 테이블이 있습니다.
We have in code layer different types of tables
24:20:27
팩트 테이블이라고 불리는 테이블을 만들 수 있습니다.
so we could build a table called a fact table another
24:20:30
하나는 차원일 수 있고 세 번째 유형은 집계일 수 있습니다.
one could be a dimension a third type could be an aggregation
24:20:34
또는 보고서가 될 수 있습니다.
or a report so we have different types of tables and
24:20:38
우리는 이러한 유형을 시작 부분에서 지정할 수 있습니다.
we can specify those types as a perfect at the start
24:20:41
예를 들어 효과 언더스코어라고 말하고 있습니다.
so for example we are saying here effect underscore
24:20:44
판매라는 테이블 이름이 있습니다.
sales so the category is a fact and
24:20:47
여기서 다양한 패턴의 테이블을 만들었습니다.
the table name called sales and here i just made like a table
24:20:50
차원으로 시작한다고 말합니다.
with different type of patterns so we could have a dimension
24:20:54
그래서 우리는 dim 언더스코어로 시작한다고 말합니다.
so we say it start with the dim underscore for
24:20:57
예를 들어 dim 고객 또는 제품과
example dim customers or products and
24:21:00
그런 다음 우리는 사실 테이블이라고 하는 또 다른 유형이 있습니다.
then we have another type called fact table so it starts with fact
24:21:03
언더스코어 또는 집계 테이블에서 첫 번째
underscore or aggregated table where we have the first
24:21:06
세 문자처럼 고객을 집계하는 것 또는
three characters like aggregating their customers or
24:21:09
월별 판매를 집계하는 것처럼, 보시다시피
the sales monthly so as you can see as you are creating a
24:21:12
명명 규칙을 만들 때 먼저 명확히 해야 합니다.
naming convention you have first to make it clear what is the
24:21:16
규칙의 각 부분을 설명하고 예를 들어 시작합니다.
rule describe each part of the rule and start giving examples so with that we make it clear for the whole team which names
24:21:23
따라야 할 이름에 대해 전체 팀이 명확히 이해할 수 있습니다.
they should follow so we talked here about the table naming
24:21:26
그런 다음 테이블 명명 규칙에 대해 이야기했습니다.
convention then you can as well go and make a naming convention for
24:21:29
그런 다음 열에 대한 명명 규칙을 만들 수 있습니다.
the columns like for example in the code layer we're gonna go and have
24:21:33
예를 들어 코드 레이어에서
surrogate keys so we can define it like this the surrogate
24:21:36
대체 키를 정의할 수 있습니다.
key should start with a table name and then underscore a
24:21:39
테이블 이름으로 시작하고 언더스코어를 추가해야 합니다.
key like for example we can call it customer underscore key it
24:21:42
예를 들어 고객 언더스코어 키라고 부를 수 있습니다.
is a surrogate key in the dimension customers the same thing for technical columns as a data engineer we might add
24:21:49
차원 고객에서 대체 키입니다.
our own columns to the tables that don't come from the source
24:21:52
원본에서 가져오지 않는 테이블에
system and those columns are the technical columns or sometimes we
24:21:55
우리 자신의 열을 추가할 수 있습니다.
call them metadata columns now in order to separate
24:21:59
메타데이터 열이라고 부릅니다.
them from the original columns that comes from
24:22:02
원본 열과 구분하기 위해
the source system we can have like a prefix for that like
24:22:05
접두사를 사용할 수 있습니다.
for example the rule says if you are building any technical or metadata
24:22:09
예를 들어 규칙에 따르면
columns that column should start with dwh
24:22:12
기술적 또는 메타데이터 열을 구축하는 경우
underscore and then that column name for example if
24:22:15
그 열은 dwh로 시작해야 합니다.
you want the metadata load date we can have dwh
24:22:18
언더스코어와 그 열 이름으로.
underscore load date so with that if anyone sees
24:22:21
그 열이 dwh로 시작하면 우리는 이를 이해합니다.
that column starts with dwh we understand this
24:22:25
데이터는 데이터 엔지니어로부터 오며 우리는 규칙을 계속 추가할 수 있습니다.
data comes from a data engineer and we can keep adding rules
24:22:28
예를 들어, 여기 저장 프로시저를 만들고 있다면
like for example the storage procedure over here if you are making an
24:22:31
etl 스크립트는 접두사 load로 시작해야 합니다.
etl script then it should start with the prefix load
24:22:34
언더스코어와 그 레이어, 예를 들어 브론즈를 로드하는 책임이 있는 저장 프로시저는 load_브론즈라고 불릴 것이고, 실버의 경우
underscore and then the layer for example the stored procedure that is responsible for loading the bronze gonna be called load underscore bronze and for the silver
24:22:44
load_실버입니다. 현재 이들이 규칙입니다.
load underscore silver so those are currently the rules
24:22:47
저장 프로시저를 위해서, 이것이 제가 보통 하는 방법입니다.
for the stored procedure so this is how i do it usually in
24:22:50
제 프로젝트에서, 자, 친구들, 그래서 우리는 확고한 명명 규칙을 가졌습니다.
my projects all right my friends so with that we have a solid naming
24:22:53
우리 프로젝트를 위한 규칙이 완료되었고 이제
conventions for our projects so this is done and now
24:22:56
다음 단계는 git으로 가서 새로운
the next step is that we're gonna go to git and you will create a brand
24:22:59
저장소를 만들 것입니다. 그리고 우리는 그 구조를 준비할 것입니다.
new repository and we're gonna prepare its structure
24:23:02
자, 이제 우리는 모든
so let's go all
24:23:07
프로젝트에서 중요한 단계로 넘어갑니다.
right so now we come to as well important step in any projects and
24:23:10
그것은 git 저장소를 만드는 것입니다. 만약 당신이
that's by creating the git repository so if you are new to
24:23:13
처음이라면 걱정하지 마세요. 생각보다 간단합니다.
get don't worry about it it is simpler than it sounds so it's
24:23:16
코드를 안전하게 보관할 수 있는 장소를 만드는 것입니다.
all about to have a safe place where you can put your codes that
24:23:19
당신이 개발하고 있는 코드에 대해 모든 것을 추적할 수 있는 가능성을 가집니다.
you are developing and you will have the possibility to track everything
24:23:22
코드에 발생한 일들을 추적할 수 있으며, 팀과 협업할 수 있습니다.
happened to their codes and as well you can use it in order to
24:23:26
무언가 잘못되면 항상 롤백할 수 있습니다. 프로젝트가 끝나면
collaborate with your team and if something goes wrong you can
24:23:29
저장소를 포트폴리오의 일부로 공유할 수 있습니다.
always roll back and the best part here once you are done with the project
24:23:32
잘 문서화된 git 저장소를 사용하여 데이터 웨어하우스를 구축한 것을 보여주는 것이 정말 놀라운 일입니다.
you can share your repository as a part of your portfolio and it is really amazing thing if you are applying for a job by showcasing your skills that you have built a
24:23:40
자, 이제 프로젝트의 저장소를 만들러 가봅시다.
data warehouse by using well-documented get repository
24:23:43
이제 우리는 계정 개요에 있습니다. 그래서
so now let's go and create the repository of the project
24:23:46
우리가 해야 할 첫 번째 일은 여기 저장소로 가는 것입니다.
now we are at the overview of our account so the
24:23:49
그리고 나서 우리는 이 녹색 버튼으로 가서 클릭할 것입니다.
first thing that we have to do is to go to the repositories over here
24:23:53
그리고 우리는 이 초록 버튼으로 가서 클릭할 것입니다.
and then we're going to go to this green button and click on
24:23:56
첫 번째로 해야 할 일은 저장소 이름을 지정하는 것입니다. sql 데이터 웨어하우스 프로젝트라고 부르겠습니다.
new the first thing that we have to do is to give the repository name so let's call it sql data warehouse project and then here we can go and give it a description
24:24:06
예를 들어, 현대 데이터 웨어하우스를 스킬 서버로 구축한다고 말하고 있습니다.
So for example, I'm saying building a modern data warehouse with a skill server.
24:24:10
다음 옵션은 공개 또는 비공개로 만들 것인지입니다. 저는 공개로 두겠습니다.
Now the next option, whether you want to make it public and private, I'm going to leave it as a public. And then let's go and add here a readme file.
24:24:18
그리고 여기에서 라이센스에 대해 MIT를 선택할 수 있습니다.
And then here about the license, we can go over here and select the MIT.
24:24:22
MIT 라이센스는 모든 사람이 코드를 사용하고 수정할 수 있는 자유를 줍니다.
MIT license gives everyone the freedom of using and modifying your code. Okay, so I think I'm happy with the setup.
24:24:29
저장소를 생성하겠습니다. 그리고 이제 우리는 새 저장소를 가졌습니다.
Let's go and create the repository. And with that, we have our brand new repository.
24:24:34
이제 제가 보통 하는 다음 단계는 저장소의 구조를 만드는 것입니다.
Now the next step that I usually do is to create the structure of the repository.
24:24:39
그리고 보통 저는 모든 프로젝트에서 같은 패턴을 따릅니다.
And usually I always follow the same patterns in any projects. So here we need few folders in order to put our files, right?
24:24:46
그래서 제가 보통 하는 것은 여기에서 파일 추가를 클릭하고 새 파일을 생성하여 구조를 만드는 것입니다.
So what I usually do, I go over here to add file, create a new file, and I start creating the structure over here.
24:24:52
첫 번째로 필요한 것은 데이터 세트입니다. 그런 다음 슬래시를 추가합니다.
So the first thing is that we need data sets, then slash, and with that, the repository can understand this is a folder, not a file.
24:24:59
그리고 여기에서 자리 표시자와 같은 것을 추가할 수 있습니다.
And then you can go and add anything like here placeholder, just an empty file.
24:25:05
이것은 폴더를 만드는 데 도움이 될 수 있습니다.
This just can help me to create the folders. So let's go and commit. So commit the changes.
24:25:10
그래서 문서와 자리 표시자를 만들고 변경 사항을 커밋하겠습니다.
And now if you go back to the main projects, you can see now we have a folder called datasets. So I'm going to go and keep creating stuff.
24:25:18
그래서 문서와 자리 표시자를 만들고 변경 사항을 커밋하겠습니다.
So I will go and create the documents, placeholder, commit the changes.
24:25:23
그리고 제가 보통 추가하는 마지막 것은
and then i'm gonna go and create the scripts placeholder
24:25:29
테스트와 같은 것입니다.
and the final one but i usually add is the
24:25:32
이런 식으로 테스트합니다.
tests something like this so
24:25:36
그것을 통해 이제 우리의 주요 폴더가 보입니다.
with that as you can see now we have the main folders of our
24:25:40
저는 보통 다음 단계로 넘어갑니다.
repository now what i usually do the next bit that i'm gonna go and
24:25:43
주요 README를 편집할 것입니다. 여기서도 볼 수 있습니다. 우리가 할 일은 README 안으로 들어가서 여기 편집 버튼을 클릭하고 글을 쓰기 시작하는 것입니다.
edit the main readme so you can see it over here as well so what we're gonna do we're gonna go inside the readme and then we're gonna go to the edit button here and we're gonna start writing
24:25:52
우리 프로젝트에 대한 주요 정보를 입력합니다. 이는 정말로 당신의 스타일에 따라 다릅니다.
the main information about our project this is really depend
24:25:55
원하는 것을 추가할 수 있습니다.
on your style so you can go and add whatever you want this
24:25:58
이것은 당신의 저장소의 주요 페이지입니다.
is the main page of your repository and
24:26:02
이제 파일 이름이 .md임을 알 수 있습니다.
now as you can see the file name here is dot md it
24:26:05
마크다운을 의미하며, 간단한
stands for markdown it is just an easy
24:26:08
텍스트 작성을 위한 친숙한 형식입니다. 문서화할 때
and friendly format in order to write a text so if you
24:26:11
텍스트를 작성하는 데 정말 좋은 형식으로, 구조화하고
have like documentations you are writing a text it is a really nice format in order to organize it structure it and it is very friendly so what i'm gonna do at the start i'm I'm going to give a few description about the project.
24:26:23
조직하는 데 매우 친숙합니다. 그래서 제가 시작할 때
So we have the main title and then we have like a welcome message and what this repository is about.
24:26:28
프로젝트에 대한 몇 가지 설명을 드리겠습니다.
And in the next section, maybe we can start with the project requirements.
24:26:31
그래서 우리는 주요 제목이 있고, 환영 메시지와 이 저장소에 대한
And then maybe at the end, you can say a few words about the licensing and a few words about you.
24:26:38
내용이 있습니다. 다음 섹션에서는 프로젝트 요구 사항을
So as you can see, it's like the homepage of the project and the repository. So once you are done, we're going to go and commit the changes.
24:26:45
시작할 수 있습니다.
And now if you go to the main page of the repository, you can
24:26:48
그리고 마지막에 라이선스에 대한 몇 마디와
see always the folder and files at the start and then
24:26:51
당신에 대한 몇 마디를 할 수 있습니다.
below it we can see the informations from the readme
24:26:54
그래서 보시다시피, 이것은 프로젝트와 저장소의 홈페이지와 같습니다.
so again here we have the welcome statement and then the
24:26:57
완료되면 변경 사항을 커밋할 것입니다.
project requirements and at the end we have the licensing and
24:27:00
이제 저장소의 메인 페이지로 가면
about me so my friends that's it we have now a
24:27:04
항상 폴더와 파일을 볼 수 있습니다.
repository and we have now the main structure of the projects and through the projects as we are building the data warehouse we're gonna go and commit all our work in this repository
24:27:13
그 아래에는 README의 정보가 있습니다.
nice right all right so with that we have now your
24:27:17
다시 말해, 여기에는 환영 문구가 있고,
repository ready and as we go in the project we will be adding
24:27:20
프로젝트 요구 사항과 마지막에는 라이선스와
stuff to it so this step is done and now the last
24:27:23
내 소개가 있습니다. 친구들, 이제 우리는
step finally we're gonna go to the sql server and
24:27:26
저장소를 가지고 있고, 프로젝트의 주요 구조를 가지고 있습니다.
we're gonna write our first scripts where we're gonna create a database and
24:27:30
데이터 웨어하우스를 구축하면서 이 저장소에 모든 작업을 커밋할 것입니다.
schemas all right now the first step is we have to go and create brand new database so now
24:27:39
좋죠? 자, 이제 당신의 저장소가 준비되었습니다.
order to do that first we have to switch to the database master
24:27:42
프로젝트를 진행하면서 추가할 것입니다.
so you can do it like this use master and
24:27:46
이 단계는 완료되었고, 마지막 단계는
semicolon and if you go and execute it now we are switched
24:27:49
SQL 서버로 가는 것입니다.
to the master database it is a system database in this code
24:27:52
첫 번째 스크립트를 작성하여 데이터베이스를 생성할 것입니다.
server where you can go and create other databases and you can
24:27:55
툴바에서 우리가 이제 마스터에 로그인했음을 확인할 수 있습니다.
see from the toolbar that we are now logged into the master
24:27:58
데이터베이스 이제 다음 단계는 새로운 데이터베이스를 생성하는 것입니다.
database now the next step we have to go and create our new
24:28:01
데이터베이스 그래서 우리는 데이터베이스를 생성하겠다고 말할 것입니다.
database so we're gonna say create database and
24:28:05
원하는 대로 이름을 지을 수 있으니 저는 데이터 웨어하우스로 하겠습니다.
you can call it whatever you want so i'm gonna go with data warehouse
24:28:08
세미콜론, 이제 실행해봅시다.
semicolon let's go and execute
24:28:11
그것으로 우리는 데이터베이스를 생성했습니다. 확인해봅시다.
it and with that we have created our database let's go and check
24:28:14
객체 탐색기에서 그것을 새로 고치면 확인할 수 있습니다.
it from the object explorer let's go and refresh and you can
24:28:17
우리의 새로운 데이터 웨어하우스를 볼 수 있습니다. 이것이 우리의 새로운 데이터베이스입니다. 멋져요.
see our new data warehouse this is our new database awesome
24:28:21
지금 다음 단계로 넘어가서 새로운 데이터베이스로 전환할 것입니다.
right now to the next step we're gonna go and switch to the
24:28:24
새 데이터베이스 그래서 우리는 데이터를 사용하겠다고 말할 것입니다.
new database so we're gonna say use data
24:28:27
웨어하우스와 세미콜론, 이제 그것으로 전환해봅시다. 이제 우리는 데이터 웨어하우스 데이터베이스에 로그인했습니다. 이제 이 데이터 웨어하우스 안에서 작업을 시작할 수 있습니다.
warehouse and semicolon so let's go and switch to it and you can see now we are logged into the data warehouse database and And now we can go and start building stuff inside this data warehouse.
24:28:39
이제 제가 보통 하는 첫 번째 단계는 스키마를 생성하는 것입니다. 스키마란 무엇일까요? 생각해보세요.
So now the first step that I usually do is I go and start creating the schemas. So what is schema? Think about it.
24:28:44
스키마는 물건을 정리하는 데 도움이 되는 폴더나 컨테이너와 같습니다.
It's like a folder or a container that helps you to keep things organized.
24:28:49
이제 우리가 아키텍처에서 결정한 대로 세 가지 레이어가 있습니다. 브론즈, 실버, 골드.
So now as we decided in the architecture, we have three layers, bronze, silver, gold.
24:28:53
이제 각 레이어에 대해 스키마를 생성할 것입니다. 그러니 시작해봅시다.
And now we're going to go and create for each layer a schema. So let's go and do that.
24:28:58
첫 번째로 시작할 것입니다. 스키마를 생성합니다. 첫 번째는 브론즈입니다. 이렇게 해봅시다.
We're going to start with the first one, create schema. And the first one is a bronze. So let's do it like this.
24:29:05
그리고 세미콜론, 이제 첫 번째 스키마를 생성해봅시다.
and a semicolon let's go and create the first
24:29:08
좋습니다. 새로운 스키마가 생겼습니다. 이제 데이터베이스로 가봅시다.
schema nice so we have a new schema let's go to our
24:29:11
그런 다음 스키마를 확인하기 위해 보안으로 가서
database and then in order to check the schemas we go to the
24:29:14
여기에서 스키마로 가면, 보시다시피 우리는 프로스가 있습니다. 찾을 수 없다면 새로 고쳐야 합니다.
security and then to the schemas over here and as
24:29:17
전체 스키마를 새로 고치면 새로운 스키마를 찾을 수 있습니다.
you can see we have the pros and if you don't find it you have to go and refresh
24:29:20
좋습니다. 이제 첫 번째 스키마가 생겼습니다. 이제 우리가 할 일은
the whole schemas and then you will find the new schema
24:29:23
다른 것들도 생성하는 것입니다. 그래서 저는 그냥 복제할 것입니다. 다음은 실버가 될 것이고, 세 번째는 골드가 될 것입니다. 그러니 두 개를 함께 실행해봅시다.
great so now we have the first schema now what we're gonna do we're
24:29:26
오류가 발생할 것입니다. 그 이유는 사이에 go가 없기 때문입니다. 각 명령 후에 go를 추가합시다.
gonna go and create the others too so i'm just gonna go and duplicate it so the next one gonna be the silver and the third one gonna be the gold so So let's go and execute those two together.
24:29:37
이제 실버와 골드를 강조 표시하고 실행하면 작동할 것입니다. SQL에서 go는 구분자와 같습니다.
We will get an error and that's because we are not having the go in between. So after each command, let's have a go.
24:29:44
이제 은과 금을 강조하고 실행하면 작동할 것입니다. SQL의 go는 구분자와 같습니다.
And now if I highlight the silver and gold and then execute, it will be working. The go in SQL, it is like separator.
24:29:51
SQL에 첫 번째 명령을 완전히 실행한 후 다음으로 넘어가라고 지시합니다. 그래서 단순한 구분자입니다.
So it tells SQL, first execute completely the first command before go to the next one. So it is just separator.
24:29:59
이제 스키마를 새로 고치고 금과 은이 있는 것을 볼 수 있습니다. 이제 데이터베이스가 생겼고 세 가지 레이어가 있으며 각 레이어를 개별적으로 개발할 수 있습니다.
Now let's go to our schemas refresh and now we can see as well we have the gold and the silver so with us we have now a database we have the three layers and we can start developing each layer individually
24:30:15
이제 작업을 커밋하러 가겠습니다. 스크립트와 코드이므로 여기 스크립트 폴더로 가서 새 파일을 추가하겠습니다.
okay so now let's go and commit our work in the kit so now since it is a script and code we're We're going to go to the folder scripts over here and then we're going to go and add a new file.
24:30:24
파일 이름을 init database.sql로 하겠습니다. 이제 코드를 여기에 붙여넣겠습니다.
Let's call it init database.sql. And now we're going to go and paste our code over here.
24:30:30
이제 몇 가지 수정을 했습니다. 예를 들어, 데이터베이스를 생성하기 전에 데이터베이스가 존재하는지 확인해야 합니다.
So now I have done a few modifications. Like for example, before we create the database, we have to check whether the database exists.
24:30:37
데이터베이스를 재생성하는 경우 중요한 단계입니다.
This is an important step if you are recreating the database.
24:30:41
그렇지 않으면 SQL에서 데이터베이스가 이미 존재한다고 오류가 발생합니다.
Otherwise, if you don't do that, you will get an error where SQL is going to say the database already exists.
24:30:46
먼저 데이터베이스가 존재하는지 확인한 다음 삭제합니다. 몇 가지 주석을 추가했습니다.
So first it is checking whether the database exists, then it drops it. I have added a few comments.
24:30:52
여기서 데이터 웨어하우스를 생성하고 스키마를 생성한다고 말하고 있습니다. 이제 매우 중요한 단계가 있습니다.
Like here we are saying, creating the data warehouse, creating the schemas. And now we have a very important step.
24:30:57
각 스크립트의 시작 부분에 헤더 주석을 추가해야 합니다.
We have to go and add a header comment at the start of each script.
24:31:01
솔직히 말해서, 지금부터 3개월 후에는 이 스크립트의 모든 세부 사항을 기억하지 못할 것입니다.
To be honest, after three months from now, you will not be remembering all the details of this script.
24:31:07
이런 주석을 추가하는 것은 나중에 이 스크립트를 다시 방문할 때 메모지와 같습니다.
And adding a comment like this, it is like a sticky note for you later once you visit this script again.
24:31:12
팀의 다른 개발자에게도 매우 중요합니다.
And it is as well very important for the other developers in the team.
24:31:16
스크립트를 열 때마다 첫 번째 질문은 이 스크립트의 목적이 무엇인지입니다.
Because each time you open scripts, the first question gonna be, what is the purpose of this script?
24:31:21
파일을 열면 첫 번째 질문은 이 스크립트의 목적이 무엇인지입니다.
Because if you or anyone in the team open the file, the first question gonna be, what is the purpose of this script?
24:31:28
우리가 이 작업을 하는 이유는 무엇인가요? 여기서 이 스크립트는 데이터베이스가 이미 존재하는지 확인한 후 새로운 데이터 웨어하우스를 생성한다고 말하고 있습니다.
Why we are doing this stuff? So as you can see here, we have a comment saying, this script creates a new data warehouse after checking if it already exists.
24:31:36
데이터베이스가 존재하면 삭제하고 다시 생성합니다.
If the database exists, it's gonna drop it and recreate it.
24:31:39
그리고 추가로 세 가지 스키마, 브론즈, 실버, 골드를 생성합니다.
And additionally, it's gonna go and create three schemas, bronze, silver, gold.
24:31:43
이 스크립트가 무엇인지 명확하게 해줍니다.
so that it gives clarity what this script is about
24:31:47
모두의 삶을 더 쉽게 만들어줍니다. 두 번째 이유는
and it makes everyone life easier now the second
24:31:50
추가하는 것이 매우 중요하다는 것입니다. 경고를 추가할 수 있습니다.
reason why this is very important to add is that you can
24:31:53
특히 이 스크립트에 대해 이러한 메모를 추가하는 것이 매우 중요합니다.
add warnings and especially for this script it
24:31:56
이 스크립트를 실행하면 전체 데이터베이스가 파괴됩니다.
is very important to add these notes because if you run this
24:31:59
누군가 이 스크립트를 열고 실행한다고 상상해 보세요. 관리자가 이 스크립트를 열고 데이터베이스에서 실행하면 모든 것이 파괴될 것입니다.
script what's gonna happen it's gonna go and destroy the whole database
24:32:02
상상해보세요, 누군가 이 스크립트를 열고 실행하는 상황을
imagine someone open this script and run it imagine an admin open this script and run it in your database everything gonna be destroyed and
24:32:11
모든 데이터가 손실되고 이는 재앙이 될 수 있습니다
all the data will be lost and this can be a disaster
24:32:14
백업이 없다면, 그래서 우리는 멋진 헤더 주석을 추가했습니다
if you don't have any backup so with that we have nice header comment
24:32:17
코드에 몇 가지 주석을 추가했습니다
and we have added few comments in our codes and
24:32:20
이제 우리는 코드를 커밋할 준비가 되었습니다
now we are ready to commit our code so let's go and
24:32:24
커밋하고 이제 우리의 스크립트가
commit it and now we have our scripts in the
24:32:27
git에 있으며, 물론 수정 사항이 있다면
git as well and of course if you are doing any modifications make
24:32:30
변경 사항을 git에 업데이트하는 것을 잊지 마세요
sure to update the changes in the git okay my friends so with that we have an empty database and schemas and we are done with this task and as well we are
24:32:39
이제 우리는 전체 프로젝트를 완료했습니다
done with the whole epic so we have completed the project initialization
24:32:43
재미있는 부분으로 넘어가겠습니다
and now we're gonna go to the interesting stuff we will go
24:32:46
청동 레이어를 구축하는 것입니다
and build the bronze layer so now the first task is to
24:32:49
소스 시스템을 분석하는 것입니다
analyze the source systems so let's go all
24:32:55
먼저 분석을 수행합니다
right so now the big question is how to build the bronze layer so
24:32:59
코드를 즉시 작성하지 않고
first thing first we do analyzing as you are developing
24:33:02
소스 시스템을 이해해야 합니다
anything you don't immediately start writing a code so before we start coding the bronze layer what we usually do is we have to
24:33:09
소스 시스템 전문가와 인터뷰를 합니다
understand the source system so what i usually do i make
24:33:12
그들에게 많은 질문을 합니다
an interview with the source system experts and ask them many
24:33:15
연결할 소스 시스템의 특성을 이해합니다
many questions in order to understand the
24:33:18
데이터 웨어하우스와 연결할 소스 시스템을 이해합니다
nature of the source system that i'm connecting to the data
24:33:21
코딩을 시작하고 주요 초점은 데이터
warehouse and once you know the source systems then we can
24:33:24
수집을 수행하는 것입니다
start coding and the main focus here is to do the data
24:33:27
소스에서 데이터로 로드하는 방법을 찾아야 합니다
ingestion so that means we have to find a way on how
24:33:31
데이터 웨어하우스로 로드하는 방법을 찾아야 합니다
to load the data from the source into the data
24:33:34
소스와 우리의 목표 시스템 간의 다리를 구축하는 것입니다
warehouse so it's like we are building a bridge between the source
24:33:37
코드가 준비되면 다음 단계는 데이터 작업을 수행하는 것입니다
and our target system the data warehouse and once
24:33:40
코드가 준비되면 다음 단계는 데이터를 처리해야 합니다.
we have the code ready the next step is we have to do data
24:33:43
여기서 품질 관리를 해야 하며, 이는 매우 중요합니다.
validation so here comes the quality control it is very
24:33:46
브론즈 레이어에서 데이터 완전성을 확인하는 것이 중요합니다.
important in the bronze layer to check the data completeness so
24:33:49
즉, 소스 시스템과 브론즈 레이어 간의 레코드 수를 비교해야 합니다.
that means we have to compare the number of records between the
24:33:53
데이터가 중간에 손실되지 않도록 확인하고, 또 다른 검사는 스키마 확인입니다.
source system and the bronze layer just to make sure we are not losing any data in between and another check that we will be doing is the schema checks and that's to make sure that the data is placed on the right position.
24:34:05
데이터가 올바른 위치에 배치되었는지 확인하는 것입니다.
And finally, we don't have to forget about documentation and committing our work in the Git.
24:34:10
마지막으로 문서화와 Git에 작업을 커밋하는 것을 잊지 말아야 합니다.
So this is the process that we're going to follow to build the bronze layer.
24:34:13
이것이 우리가 브론즈 레이어를 구축하기 위해 따를 프로세스입니다.
All right, my friends, so now before connecting any source systems to our data warehouse, we have to make a very important step is to understand the sources.
24:34:25
좋아요, 친구들, 이제 데이터 웨어하우스에 소스 시스템을 연결하기 전에
So how I usually do it, I set up a meeting with the source systems experts in order to interview them, to ask them a lot of
24:34:32
소스를 이해하는 것이 매우 중요한 단계입니다.
stuff about the source and gaining this knowledge is very important
24:34:35
그래서 제가 보통 하는 방법은 소스 시스템 전문가와 회의를 설정하는 것입니다.
because asking the right question will help you to design
24:34:38
그들을 인터뷰하고 많은 질문을 하려고 합니다.
the correct scripts in order to extract the data and
24:34:41
소스에 대한 정보를 얻는 것이 매우 중요합니다.
to avoid a lot of mistakes and challenges and now i'm going to show
24:34:44
올바른 질문을 하면 데이터 추출을 위한 올바른 스크립트를 설계하는 데 도움이 됩니다.
you the most common questions that i usually ask before connecting
24:34:48
많은 실수와 문제를 피할 수 있습니다.
anything okay so we start first by understanding the
24:34:51
이제 제가 보통 연결하기 전에 묻는 가장 일반적인 질문들을 보여드리겠습니다.
business context and the ownership so i would like to understand the
24:34:54
먼저 비즈니스 맥락과 소유권을 이해하는 것부터 시작합니다.
story behind the data i would like to understand who is responsible for
24:34:57
데이터 뒤에 있는 이야기를 이해하고 싶습니다.
the data which it departments and so on and then it's
24:35:00
누가 데이터에 책임이 있는지 이해하고 싶습니다.
nice to understand as well what business process it supports
24:35:03
어떤 IT 부서인지 등입니다.
does it support the customer transactions the
24:35:06
그런 다음 어떤 비즈니스 프로세스를 지원하는지 이해하는 것이 좋습니다.
supply chain logistics or maybe finance reporting so
24:35:10
고객 거래, 공급망 물류 또는 재무 보고를 지원하는지요.
with that you're gonna understand the importance of your data and then i ask
24:35:13
그것으로 데이터의 중요성을 이해하게 될 것입니다.
about the system and data documentation so having
24:35:16
그런 다음 시스템 및 데이터 문서화에 대해 묻습니다.
the commentations from the source is your learning materials about your
24:35:20
소스에서의 주석은 데이터에 대한 학습 자료입니다.
data and it's gonna saves you a lot of time later when
24:35:23
당신이 작업하고 새로운 데이터 모델을 설계할 때 많은 시간을 절약할 수 있습니다.
you are working and designing maybe new data models and
24:35:26
항상 데이터 모델을 이해하고 싶습니다.
as well i would like always to understand the data model for
24:35:29
소스 시스템과 열에 대한 설명이 있는지 확인하고 싶습니다.
the source system and if they have like descriptions of the columns
24:35:33
테이블을 함께 조인하는 방법을 이해하는 데 많은 도움이 됩니다.
and the tables it's gonna be nice to have the data catalog this can
24:35:36
그렇게 하면 데이터의 기초를 확고히 할 수 있습니다.
helps me a lot in the data warehouse how i'm gonna go and join the
24:35:39
비즈니스 맥락, 프로세스 및 데이터 소유권에 대한 확고한 기초를 제공합니다.
tables together so with that you get a solid foundations about
24:35:42
데이터를 추출하기 위해 사용할 기술을 이해한 후, 더 기술적인 질문으로 깊이 들어가겠습니다.
the business context the processes and the ownership of the data and now in the next step we're gonna start talking about the technicality So I would like to understand the architecture and as well the technology stack.
24:35:53
소스 시스템이 데이터를 어떻게 저장하는지에 대한 질문입니다.
So the first question that I usually ask is how the source system is storing the data?
24:35:58
온프레미스에서 SQL 서버 또는 오라클에 데이터가 있습니까? 아니면 Azure, AWS와 같은 클라우드에 있습니까?
Do we have the data on the on-prem like in SQL Server or Oracle? Or is it in the clouds like Azure, AWS and so on?
24:36:05
그 후 통합 기능에 대해 논의할 수 있습니다. 데이터를 어떻게 가져올 것인가요?
And then once we understand that, then we can discuss what are the integration capabilities? Like how I'm going to go and get the data?
24:36:11
소스 시스템이 API를 제공합니까? 아니면 파일 추출만 있습니까?
Do the source system offer APIs, maybe Kafka, or they have only like file extractions?
24:36:17
그런 다음 데이터베이스에 직접 연결을 제공할 것입니다.
or they're going to give you like a direct connection to the database.
24:36:21
데이터를 추출하기 위해 사용할 기술을 이해한 후, 소스 시스템에서 데이터를 추출하는 방법을 이해할 수 있습니다.
So once you understand the technology that you're going to use in order to extract the data, then we're going to deep dive into more technical questions.
24:36:28
전문가와 논의해야 할 첫 번째 사항은 증분 로드를 할 수 있는지 또는 전체 로드를 할 수 있는지입니다.
And here we can understand how to extract the data from the source system and then load it into the data warehouse.
24:36:34
그 후 데이터 범위와 역사화에 대해 논의할 것입니다. 모든 데이터가 필요합니까?
So the first thing that we have to discuss with the experts, can we do an incremental load or a full load?
24:36:39
10년의 데이터만 필요합니까? 소스 시스템에 이미 역사 데이터가 있습니까?
And then after that, we're going to discuss the data scope, the historizations. Do we need all data?
24:36:45
추출의 예상 크기에 대해 논의할 것입니다. 메가바이트, 기가바이트, 테라바이트에 대해 이야기하고 있습니까?
Do we need only maybe 10 years of the data? Are there histories already in the source system or should we build it in the data warehouse and so on.
24:36:53
소스 시스템에 연결할 수 있는 적절한 도구와 플랫폼이 있는지 이해하는 것이 중요합니다.
And then we're going to go and discuss what is the expected size of the extracts. Are we talking here about megabytes, gigabytes, terabytes?
24:37:01
데이터 볼륨 제한이 있는지 이해하려고 합니다.
And this is very important to understand whether we have the right tools and platform to connect the source system.
24:37:07
오래된 소스 시스템이 성능에 어려움을 겪을 수 있습니다.
And then I try to understand whether there are any data volume limitations.
24:37:11
대량의 데이터를 추출하는 ETL이 있다면 소스 시스템의 성능이 저하될 수 있습니다.
Like if you have some old source systems, they might struggle a lot with performance and so on.
24:37:15
추출에 대한 제한 사항과 성능에 영향을 미칠 수 있는 다른 측면을 이해해야 합니다.
So if you have like an ETL that is extracting large amount of data, you might bring the performance down of the source system.
24:37:22
데이터베이스에 접근할 수 있다면, 데이터베이스 성능을 저하시키지 않도록 책임을 져야 합니다.
So that's why you have to try to understand whether there are any limitations for your extracts and as well other aspects that might impact the performance of the source system.
24:37:31
매우 중요한 질문은 인증 및 권한 부여에 대해 묻는 것입니다.
This is very important. If they give you an access to the database, you have to be responsible that you are not bringing the performance of the database down.
24:37:39
소스 시스템의 데이터에 접근하기 위해 어떤 토큰, 키, 비밀번호가 필요한지 물어보세요.
And of course, very important question is to ask about the authentication and the authorization.
24:37:44
소스 시스템에서 데이터를 어떻게 접근할 것인지에 대한 질문입니다. 토큰, 키, 비밀번호 등이 필요합니까?
like how are you going to go and access the data in the source system? Do you need any tokens, keys, passwords, and so on?
24:37:50
새로운 소스 시스템을 데이터 웨어하우스에 연결할 때 해야 할 질문들입니다.
So those are the questions that you have to ask if you are connecting a new source system to the data warehouse.
24:37:55
그 질문들에 대한 답변을 얻으면 소스를 데이터 웨어하우스에 연결하는 다음 단계로 진행할 수 있습니다.
And once you have the answers for those questions, you can proceed with the next steps to connect the sources to the data warehouse.
24:38:02
좋습니다, 여러분. 이제 데이터 웨어하우스에 연결하고자 하는 새로운 소스 시스템을 분석하는 방법을 배웠습니다.
All right, my friends. So with that, you have learned how to analyze a new source systems that you want to connect to your data warehouse.
24:38:09
이 단계는 완료되었습니다. 이제 코딩으로 돌아가서 CSV 파일에서 브론즈 레이어로 데이터를 수집하는 스크립트를 작성할 것입니다.
So this step is done. And now we're going to go back to coding, where we're going to write scripts in order to do the data ingestion from the CSV files to the bronze layer.
24:38:21
브론즈 레이어의 사양을 다시 살펴보겠습니다. 소스에서 데이터 웨어하우스로 데이터를 로드해야 합니다.
And let's have a quick look again to our bronze layer specifications. So we just have to load the data from the sources to the data warehouse.
24:38:29
브론즈 레이어에 테이블을 구축할 것입니다. 전체 로드를 수행할 것입니다. 즉, 데이터를 잘라내고 삽입하는 것입니다.
We're going to build tables in the bronze layer. We are doing a full load. So that means we are truncating and then inserting the data.
24:38:35
브론즈 레이어에서는 데이터 변환이 전혀 없습니다. 데이터 모델도 생성하지 않을 것입니다.
There will be no data transformations at all in the bronze layer. And as well, we will not be creating any data model.
24:38:41
이것이 브론즈 레이어의 사양입니다.
So this is the specifications of the bronze layer.
24:38:45
브론즈 레이어의 DDL 스크립트를 생성하기 위해서는 들어오는 데이터의 메타데이터, 구조, 스키마를 이해해야 합니다.
All right, now in order to create the DDL script for the bronze layer, creating the tables of the bronze, we have to understand the metadata, the structure, the schema of the incoming data.
24:38:55
소스 시스템의 기술 전문가에게 이 정보를 문의하거나, 들어오는 데이터를 탐색하여 테이블 구조를 정의할 수 있습니다.
And either you ask the technical experts from the source system about these informations, or you can go and explore the incoming data and try to define the structure of your tables.
24:39:05
이제 우리가 할 일은 첫 번째 소스 시스템인 CRM에서 시작하는 것입니다.
So now what we're going to do, we're going to start with the first source system, the CRM.
24:39:08
그 안으로 들어가서 첫 번째 테이블인 고객 정보를 시작하겠습니다.
So let's go inside it and we're going to start with the first table, the customer info.
24:39:13
파일을 열고 내부 데이터를 확인하면 헤더 정보가 있습니다.
Now, if you open the file and check the data inside it, you see we have a
24:39:16
헤더 정보가 매우 좋습니다. 이제 소스에서 오는 열 이름을 알 수 있고, 내용을 통해 데이터 유형을 정의할 수 있습니다.
header information and that is very good because now we have the names of the columns that are coming from the source and from the content, you can define, of course, the data types.
24:39:26
그럼 이제 시작하겠습니다. 먼저 테이블을 생성하겠다고 말하고 레이어를 정의해야 합니다.
So let's go and do that. First, we're going to say create table and then we have to define the layer.
24:39:31
브론즈 레이어가 될 것이며, 매우 중요하게도 명명 규칙을 따라야 합니다. 소스 시스템의 이름으로 시작합니다.
It's going to be the bronze and now very important, we have to follow the naming convention. So we start with the name of the source system.
24:39:37
CRM 언더스코어가 될 것이고, 그 다음 소스 시스템의 테이블 이름이 올 것입니다. 즉, cost 언더스코어 info가 될 것입니다.
It is the CRM underscore. And then after that, the table name from the source system. So it's going to be that cost underscore info.
24:39:44
이것이 브론즈 레이어의 첫 번째 테이블 이름입니다. 다음 단계는 열을 정의하는 것입니다.
So this is the name of our first table in the bronze layer. And then the next step we have to go and define, of course, the columns.
24:39:51
브론즈 레이어의 열 이름은 소스 시스템과 정확히 일대일로 일치할 것입니다.
And again, the column names in the bronze layer are going to be one to one, exactly like the source system.
24:39:56
첫 번째는 ID가 될 것이고, 데이터 유형은 정수입니다.
So the first one going to be the ID and I will go with the data.
24:40:00
그 다음은 키가 될 수 있으며, 데이터 유형은 변형 문자이고 길이는 50으로 하겠습니다.
type integer then the next one can be the key n var char and the length and we'll go with 50.
24:40:14
마지막은 생성 날짜가 될 것이며,
and the last one gonna be the create date it's
24:40:17
날짜가 될 것이고, 모든 열을 다루었습니다.
gonna be a date so with that we have covered all the columns
24:40:20
소스 시스템에서 사용할 수 있는 것들이므로 확인해 보겠습니다.
available from the source system so let's go and check and
24:40:23
네, 마지막 항목은 생성 날짜입니다. 그래서 첫 번째
yes the last one is the create date so that's it for the first
24:40:26
테이블입니다. 이제 세미콜론을 추가하고 실행해 보겠습니다.
table now a semicolon of course at the end let's go and execute
24:40:30
이제 객체 탐색기로 이동하여 새로 고침합니다.
it and now we're going to go to the object explorer over here refresh
24:40:33
그리고 데이터 안에 첫 번째 테이블을 볼 수 있습니다.
and we can see the first table inside our data
24:40:36
창고가 놀랍죠? 이제 다음 단계는
warehouse amazing right so now next what you have to do is
24:40:39
각 시스템에 대한 DDL 문을 생성하는 것입니다.
to go and create a ddl statement for each
24:40:43
두 시스템에 대한 파일로 CRM을 위해
file for those two systems so for the crm
24:40:46
세 개의 DDL이 필요하고 다른 시스템에도
we need three ddls and as well for the other system
24:40:49
ERP에 대해서도 세 개의 DDL을 생성해야 합니다.
the erp we have as well to create three ddls
24:40:52
세 개의 파일에 대해 마지막에는 동급으로
for the three files so at the ends we can have in the bronze
24:40:55
여섯 개의 테이블과 여섯 개의 세부 사항이 있습니다.
dire six tables six details so
24:40:58
이제 비디오를 일시 정지하고 세부 사항을 생성하세요. 저도 같은 작업을 할 것입니다.
now pause the video go create those details i will be doing the same
24:41:02
그리고 곧 뵙겠습니다.
as well and we will see you soon all
24:41:05
좋습니다.
right
24:41:09
이제 모든 세부 사항을 생성했기를 바랍니다. 제가 보여드리겠습니다.
so now i hope you have created all those details i'm going to show you what i
24:41:12
방금 생성한 내용은 소스 CRM의 두 번째 테이블로, 제품 정보가 있고 세 번째는 판매 세부 정보입니다. 이제 두 번째 시스템으로 가서
have just created so the second table in the source crm we have the product informations and the third one is the sales details then we We go to the second system and here we make sure that we are following the naming convention.
24:41:25
이름 규칙을 따르고 있는지 확인합니다.
So first the source system, ERB, and then the table name. So the second system was really easy.
24:41:30
소스 시스템, ERP, 그리고 테이블 이름입니다. 두 번째 시스템은 정말 쉬웠습니다.
You can see we have only here like two columns and for the customers like only three and for the categories only four columns. All right.
24:41:38
여기에는 두 개의 열만 있고 고객은 세 개, 카테고리는 네 개의 열만 있습니다. 알겠습니다.
So after defining those stuff, of course, we have to go and execute them. So let's go and do that.
24:41:43
그런 다음 이러한 내용을 정의한 후, 물론 실행해야 합니다. 그러니 가서 실행해 보겠습니다.
And then we go to the object explorer over here. Refresh the tables.
24:41:46
그런 다음 여기 객체 탐색기로 이동하여 테이블을 새로 고칩니다.
And with that, you can see we have six empty tables in the bronze layer.
24:41:51
그렇게 하면 브론즈 레이어에 여섯 개의 빈 테이블이 있습니다.
And with that, we have all the tables from the two source systems inside our database. But still, we don't have any data.
24:41:57
그리고 그렇게 하면 두 소스 시스템의 모든 테이블이 데이터베이스 안에 있습니다. 하지만 아직 데이터는 없습니다.
And you can see our naming convention is really nice. You see, the first three tables comes from the CRM source system.
24:42:04
우리의 이름 규칙이 정말 좋습니다. 첫 세 개의 테이블은 CRM 소스 시스템에서 왔습니다.
And then the other three comes from the ERP. So we can see in the bronze layer, the things are really splitted nicely.
24:42:10
그리고 나머지 세 개는 ERP에서 왔습니다. 브론즈 레이어에서 모든 것이 잘 분리되어 있습니다.
And you can identify quickly which table belong to which source system.
24:42:14
이제 DDL 스크립트에 추가하는 다른 것이 있습니다. 테이블을 생성하기 전에 테이블이 존재하는지 확인하는 것입니다.
Now, there is something else that I usually add to the DDL script is to check whether the table exists before creating.
24:42:21
예를 들어, 특정 필드의 이름을 바꾸거나 데이터 유형을 변경하고 싶다고 가정해 보겠습니다.
So, for example, let's say that you are renaming or you would like to change the data type of specific field.
24:42:26
이 쿼리를 실행하면 오류가 발생합니다. 데이터베이스가 이미 이 테이블이 있다고 말할 것입니다.
If you just go and run this query, you will get an error because the database is going to say we have already this table.
24:42:32
다른 데이터베이스에서는 테이블을 생성하거나 교체할 수 있습니다. 그러나 SQL 서버에서는 TSQL 논리를 작성해야 합니다.
So, in other databases, you can say create or replace table. But in the SQL server, you have to go and build a TSQL logic.
24:42:38
매우 간단합니다. 먼저 데이터베이스에 객체가 존재하는지 확인해야 합니다.
So, it is very simple. First, we have to go and check whether the object exists in the database.
24:42:44
객체 ID가 있으면 테이블 이름을 지정해야 합니다.
So we say if object ID and then we have to go and specify the table name.
24:42:49
여기서 전체 내용을 복사하고 테이블 이름과 정확히 같은 이름을 사용해야 합니다.
So let's go and copy the whole thing over here and make sure you get exactly the same name as the table name.
24:42:56
공백이 보입니다. 이를 제거하겠습니다. 그런 다음 객체 유형을 정의할 것입니다. U는 사용자 정의를 의미합니다.
So there you see like space. I'm just going to go and remove it. And then we're going to go and define the object type. So it's going to be the U. It stands for user.
24:43:03
사용자 정의 테이블입니다. 이 테이블이 null이 아니면 데이터베이스가 이 객체를 찾았다는 의미입니다.
It is the user defined tables. So if this table is not null, so that means the database did find this object in the database.
24:43:10
무슨 일이 발생할 수 있을까요? 우리는 삭제하라고 말합니다.
So what can happen? we say go
24:43:13
테이블을 삭제하고 전체
and drop the table so the whole
24:43:16
다시 한 번 그 일을 하고 세미콜론을 추가하면 다시
thing again and semicolon so again if
24:43:19
데이터베이스에 테이블이 존재하고 null이 아니면
the table exists in the database is not null then
24:43:23
테이블을 삭제하고 그 후에 다시 생성하러 가세요.
go and drop the table and after that go and create
24:43:26
그러니 이제 전체를 강조 표시하고
it so now if you go and highlight the whole thing and
24:43:29
그 후 실행하면 작동할 것입니다. 먼저 테이블이 존재하면 삭제하고, 그 다음에 처음부터 테이블을 생성하세요. 이제 해야 할 일은 가서
then execute it it will be working so first drop the table if it exists then go and create the table from scratch now what you have to do is to go and
24:43:38
우리 데이터베이스 내에서 어떤 테이블을 생성하기 전에 이 검사를 추가하는 것입니다.
add this check before creating any table inside our database.
24:43:42
그래서 다음 테이블에 대해서도 같은 일이 될 것입니다. 저는 각 테이블에 대해 이러한 모든 검사를 추가했습니다.
So it's going to be the same thing for the next table and so on. I went and added all those checks for each table.
24:43:49
그리고 만약 제가 전체를 실행하면 어떻게 될까요? 작동할 것입니다.
And what can happen if I go and execute the whole thing? It's going to work.
24:43:53
그래서 이를 통해 저는 처음부터 동급의 모든 테이블을 재생성하고 있습니다.
So with that, I'm recreating all the tables in the bronze layer from the scratch.
24:44:02
이제 소스 데이터 웨어하우스에서 데이터를 로드하기 위해 사용할 방법은 대량 삽입입니다.
Now, the method that we're going to use in order to load the data from the source the data warehouse is the bulk inserts.
24:44:08
대량 삽입은 csv 파일이나 텍스트 파일과 같은 파일에서 데이터베이스로 대량의 데이터를 매우 빠르게 로드하는 방법입니다.
The bulk insert is a method of loading massive amount of data very quickly from files like csv files or maybe a text file directly into a database.
24:44:19
전통적인 일반 삽입과는 다릅니다.
It's not like the classical normal inserts where it's
24:44:22
데이터를 한 행씩 삽입하는 것이 아니라 대신 대량
going to go and insert the data row by row but instead the bulk
24:44:25
삽입은 한 번에 모든 데이터를 데이터베이스에 로드하는 하나의 작업입니다. 그것이 대량 삽입의 특징입니다.
insert is one operation that's going to load all the data in one go into the database and that's what makes it
24:44:31
매우 빠르므로 이 방법을 사용해 보겠습니다.
very fast so let's go and use this method okay so now let's
24:44:34
첫 번째 테이블을 로드하기 위해 스크립트를 작성하기 시작합시다.
start writing the script in order to load the first table
24:44:38
소스 CRM에서 테이블을 로드할 것입니다.
in the source crm so we're going to go and load the table
24:44:41
CSV 파일에서 고객 정보를 데이터베이스 테이블로
customer info from the csv file to the
24:44:44
가져오는 구문은 매우 간단합니다. 시작하겠습니다.
database table so the syntax is very simple we're going to start to
24:44:47
대량 삽입이라고 말할 것입니다. 이해하기 쉽습니다.
saying bulk insert so that is clear understand
24:44:50
우리는 일반 삽입이 아니라 대량 삽입을 하고 있습니다.
we are doing not a normal insert we are doing a bulk insert and
24:44:54
그런 다음 테이블 이름을 지정해야 합니다. 그것은 bronze.crm cost info입니다.
then we have to go and specify the table name so it is bronze dot crm cost info so now Now
24:45:01
이 테이블에 로드하려는 파일의 전체 위치를 지정해야 합니다.
we have to specify the full location of the file that
24:45:04
파일이 저장된 경로를 가져와야 합니다.
we are trying to load in this table so now what we have
24:45:07
전체 경로를 복사한 다음 추가할 것입니다.
to do is to go and get the path where the file is stored
24:45:11
대량 삽입에 데이터가 존재하는 위치를 정확히 지정해야 합니다.
so i'm gonna go and copy the whole path and then add it to
24:45:14
소스 CRM에서 데이터가 존재하는 위치를 지정해야 합니다.
the bulk insert exactly like where the data exists so for me it is in c sql data warehouse project datasets
24:45:21
파일 이름을 지정해야 합니다. cost_info가 될 것입니다.
in the source crm and then i have to specify
24:45:25
파일 이름은 cost_info.csv가 될 것입니다.
the file name so it's going to be the cost underscore info
24:45:28
파일의 경로를 정확히 가져와야 합니다.
dot csv you have to get it exactly like
24:45:31
경로 다음에는 WITH 절로 넘어갑니다.
the path of your files otherwise it will not be working so after
24:45:35
SQL 서버에 파일을 처리하는 방법을 알려줘야 합니다.
the path now we come to the with clause now we
24:45:38
여기 사양이 있습니다. 정의할 수 있는 많은 내용이 있습니다.
have to tell the sql server how to handle our file
24:45:41
가장 중요한 것은 원시 헤더입니다. 파일의 내용이
so here comes the specifications there is a lot of stuff that we can define so let's start with the very important one is the raw header now if you
24:45:49
항상 첫 번째 행에는 헤더 정보가 포함됩니다.
the content of our files you can see always the
24:45:52
파일의 첫 번째 행에는 헤더 정보가 포함됩니다.
first row includes the header information of
24:45:55
그 정보는 실제 데이터가 아니라 열 이름입니다.
the file so those informations are actually not the
24:45:58
실제 데이터는 두 번째 행부터 시작합니다.
data it's just the column names the actual data starts
24:46:02
데이터베이스에 이 정보를 알려야 합니다.
from the second row and we have to tell the database
24:46:05
이 정보를 데이터베이스에 전달해야 하므로 첫 번째 행이라고 말할 것입니다.
about this information so we're gonna say first row
24:46:09
실제로는 두 번째 행이므로
is actually the second row so with that
24:46:12
우리는 SQL에 파일의 첫 번째 행을 건너뛰라고 지시하고 있습니다.
we are telling sql to skip the first row in the file
24:46:15
우리는 이미 정의했기 때문에 이러한 정보를 로드할 필요가 없습니다.
we don't need to load those informations because we have already defined
24:46:18
우리 테이블의 구조이므로 이것이 첫 번째 사양입니다.
the structure of our table so this is the first
24:46:21
다음 사양은 매우 중요하며
specifications the next one which is as well very important and
24:46:25
CSV 파일을 로드할 때 필드 간의 구분자입니다.
loading any csv file is the separator between
24:46:28
필드 간의 구분자로, 실제로는
fields the delimiter between fields so it really depends
24:46:31
소스에서 가져오는 파일 구조에 따라 다릅니다.
on the file structure that you are getting from the source as you can see
24:46:34
모든 값은 쉼표로 분리됩니다.
all those values are splitted with a comma
24:46:38
우리는 이 쉼표를 파일 구분자 또는
and we call this comma as a file separator or a
24:46:41
구분자로 부르며, 다양한 CSV를 보았습니다.
delimiter and i saw a lot of different csv's like sometimes they
24:46:44
때때로 세미콜론이나 파이프 또는 해시와 같은 특수 문자를 사용합니다.
use a semicolon or a pipe or special character like
24:46:47
값이 어떻게 분리되는지 이해해야 합니다.
a hash and so on so you have to understand how the values
24:46:50
이 파일에서는 쉼표로 분리됩니다.
are splitted and in this file it's splitted by the comma
24:46:53
우리는 SQL에 이 정보를 전달해야 하며, 매우 중요합니다.
and we have to tell sql about this info it's very important
24:46:56
그래서 필드 종료자를 말할 수 있습니다.
so we can say field terminator and then
24:46:59
우리는 그것이 쉼표라고 말할 것이며, 기본적으로
we're gonna say it is the comma and basically those
24:47:02
이 두 가지 정보는 SQL이 CSV 파일을 읽을 수 있도록 매우 중요합니다.
two informations are very important for sql in order to be able to read your csv file now there are like many different
24:47:09
예를 들어 블록과 같은 다양한 옵션을 추가할 수 있습니다.
options that you can go and add for example tape
24:47:12
성능을 개선하기 위한 옵션입니다.
block it is an option in order to improve the performance where
24:47:15
전체 테이블을 잠그는 동안
you are locking the entire table during
24:47:19
ISQL이 데이터를 로드하는 동안
loading it so as isql is loading the data to
24:47:22
이 테이블을 잠그게 됩니다.
this table it's gonna go and lock the whole table so
24:47:25
지금은 여기까지입니다. 세미콜론을 추가하고
that's it for now i'm just gonna go and add the semicolon and let's
24:47:28
이제 파일에서 데이터를 우리의 브론즈 테이블에 삽입하겠습니다.
go and insert the data from the file inside our bronze table
24:47:31
이제 실행해 보겠습니다. 이제 ISQL이 약
let's execute it and now you can see isql did insert around
24:47:34
80,000개의 행을 우리의 테이블에 삽입했습니다. 잘 작동하고 있습니다.
80 000 rows inside our table so it is working
24:47:37
우리는 파일을 데이터베이스에 로드했습니다. 하지만 이제는
we just loaded the file into our database but now it is
24:47:40
스크립트를 작성하는 것만으로는 충분하지 않습니다. 테스트해야 합니다.
not enough to just write the script you have to test the
24:47:43
브론즈 테이블의 품질을, 특히 파일 작업을 할 때는
quality of your bronze table especially if you are working
24:47:46
파일과 함께 작업할 때는 간단한 선택을 해보겠습니다.
with files so let's go and just do a simple select
24:47:49
그래서 우리의 새로운 테이블에서
so from our new table and
24:47:54
실행해 보겠습니다. 이제 제가 확인하는 첫 번째 사항은 각 열에 데이터가 있는지입니다. 네, 보시다시피 데이터가 있습니다. 그리고 두 번째 사항은
let's run it so now the first thing that i check is do we have data like in each column well yes as you can see we have data and the second thing is
24:48:03
데이터가 올바른 열에 있는지입니다. 이것은 매우
do we have the data in the correct column this is very
24:48:06
중요합니다. 파일에서 데이터베이스로 데이터를 로드할 때
critical as you are loading the data from a file to a database
24:48:09
데이터가 올바른 열에 있는지입니다. 예를 들어 여기서
do we have the data in the correct column so for example here
24:48:12
우리는 첫 번째 이름이 있습니다. 물론 이건 말이 됩니다. 그리고 여기에는 성이 있습니다.
we have the first name which of course makes sense and here we have the last
24:48:15
하지만 발생할 수 있는 일은, 이러한 실수는 자주 발생합니다.
name but what could happen and this mistakes happens a
24:48:18
첫 번째 이름 정보가 키 안에 들어가고
lot is that you find the first name informations inside
24:48:22
마찬가지로 성 안에 첫 번째 이름이 있고 상태가 성 안에 있는 경우입니다. 그래서 데이터가
the key and as well you see the last name inside the first name and the status inside the last name so there is like
24:48:29
이동하는 것입니다. 이러한 데이터 엔지니어링 실수는
shifting of the data and this data engineering mistake
24:48:32
CSV 파일로 작업할 때 매우 흔합니다.
is very common if you are working with csv files and
24:48:35
이런 일이 발생하는 이유는 여러 가지가 있습니다. 아마도
there are like different reasons why it happens maybe the definition of
24:48:38
테이블 정의가 잘못되었거나 구분자가
your table is wrong or the failed separator is
24:48:41
잘못되었을 수 있습니다. 아마도 쉼표가 아니라 다른 것일 수도 있습니다. 또는
wrong maybe it's not a comma it's something else or the
24:48:44
구분자가 나쁜 구분자일 수 있습니다. 왜냐하면 때때로
separator is a bad separator because sometimes maybe
24:48:47
키나 첫 번째 이름에 쉼표가 있을 수 있고
in the keys or in the first name there is a comma and
24:48:50
SQL이 데이터를 올바르게 분할할 수 없기 때문입니다. 그래서 CSV 파일의 품질이 좋지 않습니다.
the sql is not able to split the data correctly so the quality of the csv file is not really good
24:48:56
그리고 당신이 원하는 데이터를 얻지 못하는 이유는 여러 가지가 있습니다.
and there are many different reasons why you are not getting the
24:48:59
데이터가 올바른 열에 있지 않지만 지금은 모든 것이 괜찮아 보입니다.
data in the correct column but for now everything looks fine
24:49:02
우리에게 다음 단계는 내가 가서
for us and the next step is that i go and count the
24:49:05
이 테이블 안의 행을 세는 것입니다. 그러니 가서 선택해 봅시다.
rows inside this table so let's go and select
24:49:09
그것을 통해 우리는 18,493이 있다는 것을 알 수 있습니다.
that so we can see we have 18 493
24:49:12
이제 우리가 할 수 있는 것은 csv 파일로 가서
and now what we can do we can go to our csv file and
24:49:15
이 파일 안에 몇 개의 행이 있는지 확인하는 것입니다. 보시다시피 18,494개가 있습니다. 거의 다 왔습니다. 파일 안에 하나의 추가 행이 있는 것은 헤더 때문입니다.
check how many rows do we have inside this file and as you can see we have 18 494 we We are almost there, there is like one extra row inside the file and that's because of the header.
24:49:27
첫 번째 헤더 정보는 우리 테이블에 로드되지 않았습니다. 그래서 항상 우리 테이블에는 원본 파일보다 하나 적은 행이 있을 것입니다.
The first header information is not loaded inside our table and that's why always in our tables we're gonna have one less row than the original files.
24:49:36
모든 것이 잘 보이고 이 단계를 올바르게 수행했습니다.
So everything looks nice and we have done this step correctly.
24:49:39
이제 다시 실행하면 무슨 일이 일어날까요? 우리는 브론즈 레이어 안에 중복이 생길 것입니다.
Now if I go and run it again what's gonna happen, we will get duplicates inside the bronze layer.
24:49:45
따라서 이제 우리는 같은 테이블 안에 파일을 두 번 로드했습니다. 이는 실제로 올바르지 않습니다.
So now we have loaded the file like twice inside the same table which is not really correct.
24:49:51
우리가 논의한 방법은 먼저 테이블을 비우고, 그 다음 로드하고, 잘라내고, 삽입하는 것입니다.
The method that we have discussed is first to make the table empty and then load, truncate and then insert.
24:49:58
이를 위해 대량 삽입 전에 우리가 할 것은
In order to do that, before the bulk inserts, what we're gonna do
24:50:01
테이블을 잘라내겠다고 말할 것입니다.
we're gonna say truncate table and
24:50:04
그런 다음 우리의 테이블이 있을 것이고, 그것이
then we're gonna have our table and that's
24:50:07
세미콜론으로 끝납니다. 그래서 지금 우리가 하는 것은 먼저
it with a semicolon so now what we are doing is first
24:50:11
테이블을 비우고, 그 다음 처음부터 로드하는 것입니다. 파일의 전체 내용을 테이블 안에 로드하고, 이것을 전체 로드라고 부릅니다.
we are making the table empty and then we start loading from the scratch we are loading the whole content of the file inside the table and this is what we call full load.
24:50:21
이제 모든 것을 함께 표시하고 실행해 보겠습니다.
So now let's go and mark everything together and execute.
24:50:24
다시 말하지만, 테이블의 내용을 확인하면 18,000개의 행만 있음을 알 수 있습니다.
And again, if you go and check the content of the table, you can see we have only 18,000 rows.
24:50:30
다시 실행해 보겠습니다. 브론즈 레이어의 개수를 보면 여전히 18,000이 있습니다.
Let's go and run it again. The count of the bronze layer, you can see we still have the 18,000.
24:50:36
따라서 이제 이 스크립트를 실행할 때마다 우리는 파일에서 데이터베이스 테이블로 고객 정보를 새로 고치고 있습니다.
So each time you run this script now, we are refreshing the table customer info from the file into the database table.
24:50:43
브론즈 레이어 테이블을 새로 고치고 있습니다. 즉, 파일에 변경 사항이 있으면 테이블에 로드됩니다.
So we are refreshing the bronze layer table. So that means if there is like now any changes in the file, it will be loaded to the table.
24:50:51
이것이 테이블을 잘라내고 삽입을 수행하여 브론즈 레이어에서 전체 로드를 수행하는 방법입니다.
So this is how we do a full load in the bronze layer by truncating the table and then doing the inserts.
24:50:57
이제 물론 우리가 해야 할 것은 비디오를 일시 중지하고 모든 여섯 개 파일에 대해 동일한 스크립트를 작성하는 것입니다.
And now of course what we have to do is to pause the video and go and write the same script for all six files.
24:51:04
그러니 가서 그렇게 해봅시다. 알겠습니다, 돌아왔습니다.
So let's go and do that. Okay, back.
24:51:11
여러분도 이 모든 스크립트를 작성했기를 바랍니다. 그래서 저는
So I hope that you have as well written all those scripts. So I have
24:51:14
세 개의 테이블을 사용하여 첫 번째 소스 시스템을 로드합니다.
the three tables in order to load the first source system and
24:51:18
그런 다음 세 개의 섹션을 사용하여 두 번째 소스 시스템을 로드합니다.
then three sections in order to load the second source system and
24:51:21
스크립트를 작성할 때 올바른 경로를 확인해야 합니다.
as i'm writing those scripts make sure to have the correct path so for
24:51:25
두 번째 소스 시스템의 경우 다른 경로로 변경해야 합니다.
the second source system you have to go and change the path for the other
24:51:28
폴더와 동전 레이어의 테이블 이름을 잊지 마세요.
folder and as well don't forget the table name on the bronze layer
24:51:31
파일 이름과 다릅니다. 항상 소스 시스템 이름으로 시작합니다.
is different from the file name because we start always with the source system name with the files we don't have that so i think i have everything
24:51:39
모든 것이 준비되었으니 전체를 실행해 보겠습니다.
is ready so let's go and execute the whole thing
24:51:42
모든 것이 잘 작동하니 메시지를 확인해 보겠습니다.
perfect awesome so everything is working let
24:51:45
각 테이블에 삽입된 행 수를 확인할 수 있습니다.
me check the messages so we can see from the message how
24:51:48
각 테이블을 확인하고 내용을 점검하는 작업입니다.
many rows are inserted in each table and now of course
24:51:51
그래서
the task is to go through each table and check the content
24:51:55
그래서
so
24:51:59
이제 인쇄 레이어를 로드하기 위한 정말 좋은 스크립트가 생겼고, 우리는 이 스크립트를 매일 사용할 것입니다.
that means now we have really nice script in order to load the print layer and we will use this script in daily basis
24:52:06
매일 새로운 콘텐츠를 얻기 위해 실행해야 합니다.
every day we have to run it in order to get a new content
24:52:10
데이터 웨어하우스에, 그리고 이전에 배운 것처럼 만약 당신이
to the data warehouse and as you learned before if you have like
24:52:13
자주 사용되는 SQL 스크립트를 가지고 있다면
a script of sql that is frequently used
24:52:16
우리가 할 수 있는 것은 그 스크립트에서 저장 프로시저를 만드는 것입니다.
what we can do we can go and create a stored procedure
24:52:19
그럼 이제 그렇게 해봅시다. 아주 간단할 것입니다.
from those scripts so let's go and do that it's
24:52:22
여기에서 'create or'라고 말할 것입니다.
going to be very simple we're going to go over here and say create or
24:52:25
프로시저를 변경해야 하고 이제 우리는
alter procedure and now we have to define
24:52:29
저장 프로시저의 이름을 정의해야 합니다. 나는 그것을 스키마에 넣을 것입니다.
the name of the sold procedure i'm going to go and put it in the schema
24:52:32
브론즈 레이어에 속하므로 브론즈로.
bronze because it belongs to the bronze layer so
24:52:35
그런 다음 우리는 명명 규칙을 따를 것입니다. 소스 프로시저는
then we're gonna go and follow the naming convention the source procedure
24:52:38
load 언더스코어로 시작하고 그 다음에 브론즈 레이어입니다.
starts with load underscore and then the bronze layer so
24:52:42
이름에 대한 것은 이렇고, 그리고 매우 중요하게 우리는 정의해야 합니다.
that's it about the name and then very important we have to define the
24:52:45
우리 기술 진술의 시작과 끝을 정의해야 합니다.
begin and as well the end of our skill statements
24:52:48
여기 시작이 있고 끝으로 가봅시다.
so here is the begin and let's go to the end and
24:52:51
모든 것을 강조하고 탭으로 한 번 눌러서 읽기 쉽게 만듭니다.
say this is the ends and then let's go highlight
24:52:55
저장 프로시저를 생성해 보겠습니다.
everything in between and give it one push with tab so that it is easier to read so now next what we're gonna do we can go and execute it So let's go and create this stored procedure.
24:53:04
저장 프로시저를 확인하려면 데이터베이스로 가야 합니다.
And now if you want to go and check your stored procedure, you go to the database and then we have here a folder called programmability.
24:53:10
저장 프로시저가 있습니다. 새 저장 프로시저를 확인해 보세요.
And then inside we have stored procedure. So if you go and refresh, you will see our new stored procedure. Let's go and test it.
24:53:16
새 쿼리를 작성하겠습니다. bronze.load bronze를 실행해 보겠습니다.
So I'm going to go and have a new query. And what we're going to do, we can say execute bronze dot load bronze.
24:53:23
실행해 보겠습니다. 이제 브론즈 레이어가 완전히 로드되었습니다.
So let's go and execute it. And with that, we have just loaded completely that bronze layer.
24:53:29
SQL이 파일에서 브론즈 레이어로 모든 데이터를 삽입했습니다.
So as you can see, SQL did go and insert all the data from the files to the bronze layer.
24:53:34
스크립트를 매번 실행하는 것보다 훨씬 쉽습니다.
It is way easier than each time running those scripts, of course. All right.
24:53:38
출력 메시지가 많은 정보를 포함하지 않습니다.
So now the next step is that as you can see, the output message, it is really not having a lot of information.
24:53:43
ETL 결과 프로시저의 메시지가 명확하지 않습니다.
The message of your ETL result procedure, it will not be really clear.
24:53:48
ETL 스크립트를 작성할 때 메시지에 주의해야 합니다.
So that's why if you are writing an ETL script, always take care of the messaging of your code. So let me show you a nice design.
24:53:55
시작 프로시저로 돌아가겠습니다. 메시지를 나눌 수 있습니다.
Let's go back to our start procedure. So now what we can do, we can go and divide the message based on our code.
24:54:02
메시지를 시작해 보겠습니다. 예를 들어, print를 사용합니다.
So now we can start with the message, for example, over here, let's say print.
24:54:05
이 저장 프로시저로 무엇을 하고 있는지 말합니다.
And we say what we are doing with this stored procedure, we are loading the bronze layer.
24:54:11
구분 기호를 추가해 보겠습니다. 시작과 끝에 '='를 추가합니다.
So this is the main message, the most important one. And we can go and play with the separators like this. So we can say print.
24:54:17
시작 부분에 멋진 메시지를 추가합니다.
And now we can go and add some nice separators, like for example, the equals at the start and at the end, just to have like a section.
24:54:24
코드가 두 섹션으로 나뉘어 있음을 알 수 있습니다.
So this is just a nice message at the start. So now by looking to our code, we can see that our code is split into two sections.
24:54:31
첫 번째 섹션은 CRM에서 모든 테이블을 로드합니다.
The first section, we are loading all the tables from the source system CRM.
24:54:35
두 번째 섹션은 ERP에서 테이블을 로드합니다.
And the second section is loading the tables from the ERP. So we can split the prints by the source system.
24:54:41
CRM 테이블을 로드한다고 출력하겠습니다.
So let's go and do that. So we're going to say print and we're going to say loading CRM tables.
24:54:48
첫 번째 섹션을 위해 멋진 구분 기호를 추가합니다.
This is for the first section. And then we can go and add some nice separators like the one. Let's take the minus.
24:54:56
각 출력에 세미콜론을 추가하는 것을 잊지 마세요.
And of course, don't forget to add semicolons like me. So we
24:54:59
여기서도 세미콜론을 추가할 수 있습니다.
can have semicolon for each print the
24:55:03
여기서도 똑같은 걸 복사할 거예요.
same thing over here i'll go and copy the whole thing because
24:55:06
시작 부분과 끝 부분에 이를 넣을 거예요.
we're gonna have it at the start and as well at the end let's go
24:55:09
두 번째 섹션을 위해 전체를 복사할 거예요.
copy the whole thing for the second section so for
24:55:12
여기서 erp가 시작되고,
the erp it starts over here and we can have
24:55:15
이렇게 하고 로딩 erp라고 부를 거예요.
it like this and we're gonna call it loading erp so with
24:55:18
출력에서 시스템 간의 구분이 잘 보일 거예요.
that in the output we can see nice separation between
24:55:21
각 소스 시스템을 로딩하고 다음 단계로 가요.
loading each source system now we go to the next step where
24:55:25
각 작업에 대해 출력을 추가할 거예요.
we go and add like a print for each action so for
24:55:28
여기서 테이블을 잘라내고 있어요.
example here we are truncating the table so
24:55:31
출력을 추가하고 두 개의 화살표를 더할 수 있어요.
we say print and now what we can do we can go and add two arrows
24:55:34
우리가 하고 있는 일을 보여줄 거예요.
and we say what we are doing so we are truncating the
24:55:38
테이블 이름을 메시지에 추가할 수 있어요.
table and then we can go and add the table name in
24:55:41
첫 번째 작업을 수행하고 있어요.
the message as well so this is the first action that we are doing
24:55:44
데이터를 삽입하는 출력을 추가할 수 있어요.
and we can go and add another print for inserting the
24:55:47
테이블 이름을 추가할 거예요.
data so we can say inserting data
24:55:50
출력에서 SQL이 무엇을 하는지 이해할 수 있어요.
into and then we have the table name
24:55:53
모든 다른 테이블에 대해 반복할 거예요.
so with that in the output we can understand what sql is doing
24:55:57
모든 출력을 추가했어요.
so let's go and repeat this for all other tables okay
24:56:00
마지막에 세미콜론을 잊지 마세요.
so i just added all those prints and don't forget the semicolon
24:56:03
출력을 확인하고 실행해 볼 거예요.
at the end so i would say let's go and execute it and check the output so let's go and do that but then maybe at the start
24:56:10
빠른 출력을 위해 저장된 프로시저를 실행할 거예요.
just to have quick output execute our stored
24:56:13
이제 결과를 확인해 보세요.
procedure like this so let's see now
24:56:17
출력이 더 정리되어 있는 걸 볼 수 있어요.
if you check the output you can see things are more organized than
24:56:20
시작할 때 데이터를 읽고 있어요.
before so at the start we are reading okay we are loading the
24:56:23
이제 소스 시스템 crm을 로딩하고 있어요.
bronze layer now first we are loading the source system crm
24:56:26
그리고 두 번째 섹션은 ERP를 위한 것이며, 우리는
and then the second section is for the erp and we can
24:56:29
작업을 볼 수 있습니다. 그래서 우리는 각 테이블에 대해 잘라내기, 삽입, 잘라내기, 삽입을 하고 있으며, 두 번째 소스에 대해서도 동일한 작업을 합니다. 보시다시피, 이것은 멋지고
see the actions so we are truncating inserting truncating inserting for each table and as well the same thing for the second source so as you can see it is nice and
24:56:38
미적인 것이지만, 디버깅할 때 매우 중요합니다.
cosmetic but it's very important as you are debugging and
24:56:41
오류에 대해 이야기하자면, 우리는 가서 처리해야 합니다.
errors and speaking of errors we have to go and handle
24:56:44
시작 절차에서 오류를 처리해야 하므로, 가서
the errors in our start procedure so let's go and
24:56:47
그것을 수행합시다. 우리가 가장 먼저 할 일입니다. 시작하자고 말합니다.
do that it's going to be the first thing that we do we say begin
24:56:50
시도하고, 그런 다음 스크립트의 끝으로 갑니다.
try and then we go to the end of our script
24:56:54
마지막 끝 전에 우리는 말합니다.
and we say before the last end we say
24:56:57
그리고 시도한 후에 우리가 추가해야 할 다음 사항은
and try and then the next thing we have to add the
24:57:00
catch입니다. 그래서 우리는 시작하고 catch를 말할 것입니다.
catch so we're going say begin catch and
24:57:03
그리고 catch, 이제 먼저 가서 우리의
and catch so now first let's go and organize our
24:57:07
코드를 정리합시다. 전체 코드를 가져올 것입니다.
code i'm gonna take the whole code and
24:57:10
한 번 더 밀어주고, 시작도 마찬가지입니다.
give it one more push and as well the begin
24:57:13
그래서 더 조직적입니다. 아시다시피,
try so it is more organized and as you know the
24:57:16
try와 catch는 가서 try를 실행합니다.
try and catch is going to go and execute the try and
24:57:20
스크립트를 실행하는 동안 오류가 발생하면 두 번째 섹션이 실행됩니다. catch는 SQL이 try를 실행하는 데 실패할 경우에만 실행됩니다.
if there is like any errors during executing this script the second section is going to be executed so the catch will be executed only if the SQL failed to run the try.
24:57:31
이제 우리가 해야 할 일은 SQL에 대해 오류가 발생했을 때 무엇을 할지 정의하는 것입니다.
So now what we have to do is to go and define for SQL what to do if there is like an error in your code.
24:57:36
여기서 우리는 여러 가지 작업을 수행할 수 있습니다. 예를 들어, 로깅 테이블을 생성하고 이 테이블에 메시지를 추가할 수 있습니다.
And here we can do multiple stuff like maybe creating a logging tables and add the messages inside this table.
24:57:42
또는 출력에 멋진 메시지를 추가할 수 있습니다. 예를 들어, 여기서 다시 섹션을 추가할 수 있습니다.
Or we can go and add some nice messaging to the output. Like for example, we can go and add like a section again over here.
24:57:49
그래서 다시 몇 개의 등호를 추가하고, 여기서 반복하고 그 사이에 내용을 추가할 수 있습니다.
So again, some equals and we can go and repeat it over here and then add some content in between.
24:57:56
그래서 우리는 브론즈 레이어를 로드하는 동안 오류가 발생했다고 말하는 것으로 시작할 수 있습니다.
So we can start with something like to say error accord during loading bronze layer.
24:58:04
그리고 나서 우리는 여러 가지를 추가할 수 있습니다. 예를 들어, 오류 메시지를 추가할 수 있습니다.
And then we can go and add many stuff like for example we can go and add the error message.
24:58:11
여기서 우리는 오류 메시지 함수를 호출할 수 있습니다.
And here we can go and call the function error message.
24:58:16
그리고 우리는 또한 오류 번호를 추가할 수 있습니다. 그래서 오류 번호입니다.
And we can go and add as well for example the error number. So error number.
24:58:21
그리고 물론 이 출력은 숫자로 될 수 있지만, 여기 오류 메시지는
and of course the output of this can be in number but the error message here
24:58:25
텍스트이므로 데이터 유형을 변경해야 합니다.
is a text so we have to go and change the data type
24:58:28
varchar로 캐스트를 수행할 것입니다.
so we're going to do a cast as in varchar
24:58:31
이와 같이 많은 함수가 있습니다.
like this and then there is like many functions that you
24:58:34
출력에 추가할 수 있습니다. 예를 들어 오류 상태와 같은.
can add to the output like for example the error state
24:58:38
이럴 경우 발생할 수 있는 상황을 설계할 수 있습니다.
and so on so you can design what can happen if there
24:58:41
etl에서 오류가 발생할 경우 매우 중요합니다.
is an error in the etl now what else is very important
24:58:44
각 etl 프로세스에서 각 단계의 소요 시간을 추가해야 합니다.
in each etl process is to add the duration of each like step so for example i would like to understand how long it takes to load this table over here.
24:58:54
이 테이블을 로드하는 데 얼마나 걸리는지 이해하고 싶습니다.
But looking to the output, I don't have any information how long it's taking to load my tables.
24:58:59
출력을 보면 테이블 로드에 걸리는 시간을 알 수 없습니다.
And this is very important because as you are building like
24:59:02
이것은 매우 중요합니다. 큰 데이터 웨어하우스를 구축할 때
a big data warehouse, the ETL process is going to take a long time and you would like to understand where is the issue, where is the bottleneck, which table is consuming a lot of time to be loaded.
24:59:12
문제가 어디에 있는지, 병목 현상이 어디인지 이해하고 싶습니다.
So that's why we have to add those informations as well to the output or even maybe to protocol it in a table.
24:59:18
따라서 이러한 정보를 출력에 추가해야 합니다.
So let's go and add as well this step. So we're going to go to the start.
24:59:21
이 단계도 추가하겠습니다. 시작으로 가겠습니다.
And now in order to calculate the duration, you need the starting time and the end time.
24:59:26
지속 시간을 계산하려면 시작 시간과 종료 시간이 필요합니다.
So we have to understand when we started loaded and when we ended loading the table.
24:59:31
테이블 로드를 시작한 시점과 종료 시점을 이해해야 합니다.
So now the first thing is we have to go and declare the variables. So we can say declare. And then let's make one called start time.
24:59:39
변수를 선언해야 합니다. 시작 시간을 선언하겠습니다.
And the data type of this is going to be the date time. I need exactly the second when it started. And then another one for the end time.
24:59:46
이 데이터 유형은 날짜 및 시간입니다.
So another variable, end time and as well the same thing, date time.
24:59:50
시작된 정확한 초가 필요합니다.
So with that, we have declared the variables and the next step is to go and use them.
24:59:54
종료 시간도 필요합니다.
So now let's go to the first table to the customer info and add the start.
25:00:00
또 다른 변수, 종료 시간입니다.
is set start time equal
25:00:03
이제 변수를 선언했으니 사용할 차례입니다.
to get date so we will get the exact time
25:00:06
고객 정보의 첫 번째 테이블로 가서 시작을 추가하겠습니다.
when we start loading this table and then let's
25:00:09
시작 시간을 설정합니다.
go and copy the whole thing and go to the end of loading over
25:00:12
정확한 시간을 가져옵니다.
here so we're gonna say set this time
25:00:15
이 테이블을 로드할 때의 시간을 가져옵니다.
the end time equal as well to the get date so
25:00:19
이제 우리는 로딩을 시작할 때의 값이 있습니다.
with that now we have the values of when we start loading
25:00:22
이 테이블과 테이블 로딩이 완료될 때의 값입니다.
this table and when we completed loading the table and
25:00:25
이제 다음 단계는 지속 시간을 출력해야 합니다.
now the next step is we have to go and print the duration
25:00:28
그 정보를 출력할 수 있습니다.
those informations so over here we can go and say print and
25:00:32
다시 같은 디자인으로 두 개의 화살표를 가질 수 있습니다.
we can go and have as again the same design so two arrows
25:00:35
그리고 우리는 간단하게 로드 지속 시간을 말할 수 있습니다.
and we can say very simply load duration and
25:00:38
그런 다음 두 배의 점과 공백을 추가해야 합니다.
then double points and space and now what we have to do is
25:00:42
지속 시간을 계산해야 하며, 이를 사용하여 할 수 있습니다.
to calculate the duration and we can do that using the
25:00:45
날짜와 시간 함수인 날짜 차이를 사용하여
date and time function date diff in order to find
25:00:48
두 날짜 간의 간격을 찾기 위해서입니다.
the interval between two dates so we're going to say
25:00:51
여기서 더하기를 하고, 그런 다음 리프를 사용합니다.
plus over here and then use the leaf and here we have
25:00:54
세 가지 인수를 정의해야 합니다. 첫 번째는 단위입니다.
to define three arguments first one is the unit so you can
25:00:57
초, 분, 시간 등을 정의할 수 있습니다.
define second minute hours and so on so we're going to go with the
25:01:00
그런 다음 간격의 시작을 찾을 수 있습니다.
second and then we can find the start of the interval it's
25:01:03
시작 시간이 될 것이고, 마지막 인수는 끝이 될 것입니다.
going to be the start time and then the last argument is going to be the end
25:01:07
경계의 끝 시간이 될 것입니다.
of the boundary it's going to be the end time and
25:01:10
물론 이 출력은 숫자로 나타납니다.
now of course the output of this is going to be in number that's why we have to
25:01:13
그래서 우리는 캐스팅해야 합니다.
go and cast it so we're going to say cast as
25:01:16
nvarchar로 캐스팅하고 이렇게 닫을 것입니다.
nvarchar and then we're going to close it like this
25:01:19
그리고 끝에 공백을 추가할 것입니다.
and maybe at the ends we're gonna say plus space
25:01:22
아름다운 메시지를 만들기 위해서입니다.
seconds in order to have a nice message so again
25:01:25
우리가 한 것은 두 개의 변수를 선언한 것입니다.
what we have done we have declared the two variables and we are using
25:01:29
시작할 때 현재 날짜와 시간을 가져옵니다.
them at the start we are getting the current date
25:01:32
테이블 로딩이 끝날 때 현재 날짜와 시간을 가져옵니다.
and time and at the end of loading the table we are getting the
25:01:35
그들 간의 차이를 찾아 로드 지속 시간을 얻습니다.
current date and time and then we are finding the differences
25:01:38
그들 사이의 차이를 찾아서 로드 지속 시간을 얻기 위해 이 정보를 출력하고 있습니다.
between them in order to get the load duration and in this case we are just printing this information and now we can go of course and add some nice separator between
25:01:47
각 테이블 사이에 멋진 구분자를 추가할 수 있습니다.
each table so i'm gonna go and do it like this just
25:01:50
몇 가지 마이너스가 있습니다. 이제 해야 할 일은
few minuses not a lot of stuff so now what we have to do is to
25:01:54
각 테이블에 이 메커니즘을 추가하는 것입니다.
go and add this mechanism for each table
25:01:57
etl의 속도를 측정하기 위해
in order to measure the speed of the etl for
25:02:00
각 테이블에 대한 모든 구성을 추가했습니다.
each one of them okay so now i have added all those configurations for each table
25:02:10
이제 전체를 실행해 보겠습니다.
and let's go and run the whole thing now so let's
25:02:14
저장 프로시저를 편집하겠습니다.
go and edit the stored procedure this and we're
25:02:17
이제 실행할 준비가 되었습니다.
gonna go and run it so let's go and execute so
25:02:21
로드 지속 시간에 대한 추가 정보가 있습니다.
now as you can see we have here one more info about the load durations
25:02:24
여기서 우리는 제로 초를 확인할 수 있습니다.
and it is everywhere i can see we have
25:02:27
정보를 로드하는 데 매우 빠르기 때문입니다.
zero seconds and that's because it is super fast of
25:02:30
서버와 네트워킹이 다릅니다.
loading those informations we are doing everything locally at pc so loading the data from files to database is gonna be mega fast but of course in real projects
25:02:38
테이블에 수백만 개의 도로가 있습니다.
you have like different servers and networking between them and
25:02:42
지속 시간이 제로 초가 아닐 것입니다.
you have millions of roads in the tables of course the duration
25:02:45
이제 얼마나 걸리는지 쉽게 알 수 있습니다.
gonna be not like zero seconds things gonna be slower
25:02:48
각 테이블을 로드하는 데 걸리는 시간입니다.
and now you can see easily how long it takes to
25:02:51
전체 브론즈 레이어를 로드하는 데 걸리는 시간입니다.
load each of your tables and now of course what is very interesting
25:02:54
얼마나 걸리는지를 이해하는 것입니다.
is to understand how long it takes to
25:02:57
전체 청동 레이어를 로드하므로 이제 귀하의 작업은 전체 패치에 대한 정보를 끝에 인쇄하는 것입니다. 청동 레이어를 로드하는 데 얼마나 걸렸는지.
load the whole bronze layer so now your task is as well to print at the ends information about the whole patch how long it took to load the bronze layer.
25:03:07
좋아요, 이제 끝났기를 바랍니다.
Okay, I hope we are done.
25:03:14
이렇게 했으니 두 개의 새로운 변수를 정의해야 합니다. 배치의 시작 시간과 배치의 종료 시간입니다.
Now I have done it like this, we have to define two new variables. So the start time of the batch and the end time of the batch.
25:03:21
시작 절차의 첫 번째 단계는 첫 번째 변수에 대한 날짜와 시간 정보를 가져오는 것입니다.
And the first step in the start procedure is to get the date and time informations for the first variable.
25:03:27
정확히 마지막에, 시작 절차에서 우리가 하는 마지막 일은 날짜와 시간을 가져오는 것입니다.
And exactly at the end, the last thing that we do in the start procedure, we're going to go and get the date and time
25:03:34
종료 시간에 대한 형성입니다. 그래서 다시 말합니다.
on formations for the end time so we say again
25:03:37
패치의 날짜를 설정하고 가져옵니다.
set and get date for the patch in time and then all
25:03:40
메시지를 인쇄하러 가야 합니다.
what you have to do is to go and print a message so we are saying
25:03:43
브론즈 레이어 로딩이 완료되었습니다.
loading bronze layer is completed and then we are printing
25:03:46
총 로드 기간과 날짜 차이를 계산합니다.
total load duration and the same thing with a date different between
25:03:50
초를 계산하고 전체를 실행합니다.
the patch start time and the end time and we are calculating
25:03:53
절차를 시작하고 실행합니다.
the seconds and so on so now what you have to do is to go and execute the whole thing so let's go and refresh the definition of
25:04:01
출력에서 마지막 메시지로 이동합니다.
start procedure and then let's go and execute it so
25:04:04
브랜치 레이어 로딩이 완료되었습니다.
in the output we have to go to the last message and
25:04:07
총 로드 기간은 0초입니다.
we can see loading branch layer is completed and the total
25:04:10
실행 시간이 1초 미만입니다.
load duration is as well zero seconds because the
25:04:13
ETL 구축에 대한 감을 잡고 있습니다.
execution time is less than one second so
25:04:16
데이터 엔지니어링은 전부가 아닙니다.
with that you are getting now a feeling about how to build an etl
25:04:19
데이터를 로드하는 방법이 아니라 전체 파이프라인을 설계하는 것입니다.
process so as you can see the data engineering is not all
25:04:23
오류가 발생할 경우를 대비하고 각 단계를 인쇄합니다.
about how to load the data it's how to engineer the whole pipeline how to measure the speed of loading the data what can
25:04:29
ETL 프로세스를 정리합니다.
happen if there is like an error and to print each step
25:04:33
출력에서 정리하고 로그를 남깁니다.
in your etl process and make everything organized
25:04:36
디버깅과 성능 최적화를 쉽게 만듭니다.
and cleared in the output and maybe in the logging just
25:04:39
품질 측정을 추가할 수 있습니다.
to make debugging and optimizing the performance way easier
25:04:43
ETL 스크립트에 많은 것을 추가할 수 있습니다.
and there is like a lot of things that we can add we can add the quality measures
25:04:46
다음 단계로 돌아가서 데이터 흐름 다이어그램을 그립니다.
and stuff so we can add many stuff to our etl scripts to make our data warehouse professional all right my friends so with that we have developed a code in order to load the bronze layer and we have tested that as well.
25:04:58
데이터 흐름 다이어그램을 그릴 것입니다.
And now in the next step we're going to go back to draw you because we want to draw a diagram about the data flow so let's go
25:05:09
데이터 흐름을 매핑하기 위해 간단한 시각화를 그립니다.
so now what is a data flow diagram we're going to draw a simple visual in
25:05:12
데이터가 어디서 오는지 명확히 합니다.
order to map the flow of your data where it comes
25:05:16
데이터 계보라는 것을 만듭니다.
from and where it ends up so we want just to make clear how the data flows through different layers of your projects and that's helped us to create
25:05:24
문제를 분석할 때 특히 유용합니다.
something called the data lineage and this is really nice
25:05:27
특히 문제를 분석할 때
especially if you are analyzing an issue so if you have like
25:05:30
여러 계층이 있고 실제 데이터 계보가 없으면
multiple layers and you don't have a real data lineage or
25:05:33
흐름을 이해하기가 정말 어려울 것입니다.
flow it's going to be really hard to analyze the scripts in
25:05:36
데이터의 출처를 이해하기 위해 이
order to understand the origin of the data and having this
25:05:40
다이어그램은 문제를 찾는 과정을 개선할 것입니다.
diagram going to improve the process of finding issues so now let's go and create one okay so now back to draw your own and we're going to go and build the flow diagram so we're going to
25:05:49
우선 소스 시스템부터 시작합시다.
start first with the source system so let's
25:05:52
레이어를 만들고 채우기 점선을 제거할 것입니다.
build the layer i'm gonna go and remove the fill dotted and
25:05:56
그런 다음 '소스'라고 적힌 상자를 추가할 것입니다.
then we're gonna go and add like a box saying sources
25:05:59
여기 위에 놓고 크기를
and we're gonna put it over here increase the
25:06:02
24로 늘리고 선 없이
size 24 and as well without any
25:06:06
소스 안에는 무엇이 있을까요?
lines now what do we have inside the sources we have
25:06:09
폴더와 파일이 있습니다. 폴더 아이콘을 찾아볼까요?
like folder and files so let's go and search for a folder icon i'm gonna go and take this one over
25:06:15
당신은 CRM이라고 말할 수 있습니다.
and say you are the CRM and we can as well
25:06:18
크기를 늘리고 또 다른 소스가 있습니다.
increase the size and we have another source we
25:06:21
우리는 ERP가 있습니다.
have the ERP okay so
25:06:24
이것이 첫 번째 레이어입니다.
this is the first layer let's go and now have
25:06:28
이제 브론즈 레이어를 만들겠습니다.
the bronze layer so we're gonna go and grab another box
25:06:31
상자를 하나 더 잡고 색상을 이렇게 만들겠습니다.
and we're gonna go and make the coloring like this and
25:06:34
자동 대신 해치 패턴을 사용할 수 있습니다.
instead of auto maybe take the hatch maybe something like this whatever you know so rounded and then we can go and put on top
25:06:42
브론즈 레이어라고 말할 수 있습니다.
of it like the title so we can say you
25:06:46
글꼴 크기도 늘리세요.
are the bronze layer and increase as
25:06:49
각 테이블에 대한 상자를 추가할 것입니다.
well the size of the fonts so now what you're going to do we're going
25:06:52
브론즈 레이어에 판매 세부정보가 있습니다.
to go and add boxes for each table that we have in the
25:06:55
조금 더 작게 만들 수 있습니다.
bronze layer so for example we have the sales details
25:06:58
그리고 두 개의 다른 테이블이 있습니다.
we can go and make it a little bit smaller maybe 16
25:07:01
그리고 굵게 표시하지 않고 CRM에서 고객 정보와 제품 정보를 포함한 다른 두 개의 테이블이 있습니다.
and not bold and we have other two tables from the crm we have the customer info and as well the product info.
25:07:11
그래서 이것이 CRM에서 가져온 세 개의 테이블입니다.
So those are the three tables that comes from the CRM.
25:07:15
이제 우리가 할 것은 소스 CRM과 이 세 개의 테이블을 연결하는 것입니다.
And now what we're going to do, we're going to go and connect now the source CRM with those three tables.
25:07:20
우리가 할 것은 폴더로 가서 폴더에서 청동 레이어로 화살표를 만드는 것입니다.
So what we're going to do, we're going to go to the folder and start making arrows from the folder to the bronze layer like this.
25:07:27
이제 ERP 소스에 대해서도 동일한 작업을 해야 합니다.
And now we have to do the same thing for the ERP source.
25:07:31
보시다시피 데이터 흐름 다이어그램은 두 레이어 간의 데이터 계보를 한 그림으로 보여줍니다.
So as you can see, the data flow diagram shows us in one picture, the data lineage between the two layers.
25:07:37
여기서 이 세 개의 테이블이 실제로 CRM에서 오는 것을 쉽게 볼 수 있습니다.
So here can see easily those three tables actually comes
25:07:40
그리고 청동 레이어의 세 개의 테이블은 ERP에서 오는 것입니다. 이해합니다.
from the crm and as well those three tables in the bronze
25:07:43
테이블이 많으면 큰 실수가 될 것입니다. 하지만
layer are coming from the erp i understand if we have
25:07:46
작거나 중간 규모의 데이터 웨어하우스를 구축하면
like a lot of tables it's gonna be a huge miss but if
25:07:50
이 다이어그램이 모든 것을 이해하는 데 정말 쉽게 만들어 줄 것입니다.
you have like small or medium data warehouse building those
25:07:53
모든 것이 소스에서 데이터 웨어하우스의 다양한 레이어로 흐르는 방식을 이해하는 데 도움이 됩니다.
diagrams gonna make things really easier to understand how
25:07:56
이 단계는 완료되었고 마지막 단계는 우리의 코드를 git 저장소에 커밋하는 것입니다.
everything is flowing from the sources into the different layers in your data warehouse all right so with that we have the first version of the data flow
25:08:05
좋습니다, 이제 우리의 작업을 커밋하러 가겠습니다. 스크립트이므로 스크립트 폴더로 가겠습니다.
So this step is done and the final step is to commit our code in the get repo.
25:08:14
그래서 아마도 각 레이어에 대한 폴더를 만드는 것이 의미가 있을 것입니다. 이제 청동 폴더를 만들기 시작하겠습니다.
Okay, so now let's go and commit our work. Since it is script, we're going to go to the folder scripts and here we can have like scripts for the bronze, silver and gold.
25:08:22
그래서 새로운 파일을 만들고 청동이라고 말할 것입니다.
That's why maybe it makes sense to create a folder for each layer. So let's go and start creating the bronze folder.
25:08:28
슬래시를 추가하고 그 다음에 DDL 스크립트를 가질 수 있습니다.
So I'm going to go and create a new file and then I'm going to say bronze
25:08:31
청동 레이어 .sql의 DDL 스크립트를 가질 수 있습니다.
slash and then we can have the ddl script of the
25:08:34
우리가 만든 DDL 코드를 붙여넣겠습니다.
bronze layer dot sql so now i'm gonna go and
25:08:37
그 여섯 개의 테이블과 일반적으로 시작할 때 주석이 있습니다.
paste the ddl codes that we have created so
25:08:40
이 스크립트의 목적을 설명하는 주석이 있습니다.
those six tables and as usual at the start we have a
25:08:43
이 스크립트는 청동 스키마에 테이블을 생성한다고 말하고 있습니다.
comment where we are explaining the purpose of this script so
25:08:46
스크립트를 실행하면 DDL 구조를 재정의하게 됩니다.
we are saying this script creates tables in the bronze schema and
25:08:50
청동 테이블의 DDL 구조를 재정의하게 됩니다.
by running the script you are redefining the ddl structure
25:08:53
그렇게 하겠습니다. 이제 변경 사항을 커밋하겠습니다.
of the bronze tables so let's have it like that
25:08:56
변경 사항을 모두 커밋할 거예요
and i'm gonna go and commit the changes all
25:08:59
스크립트 안에 폴더가 있습니다
right so now as you can see inside the scripts we have a folder
25:09:02
브론즈라는 이름의 폴더 안에 ddl이 있습니다
called bronze and inside it we have the ddl
25:09:05
브론즈 레이어를 위한 스크립트입니다
script for the bronze layer and as well in the bronze layer we're gonna go
25:09:08
저장 프로시저를 추가할 거예요
and put our storage procedure so we're gonna go and create a
25:09:11
새 파일을 만들고 proc load bronze라고 부르겠습니다.
new file let's call it proc load bronze
25:09:15
.sql을 입력한 후 스크립트를 붙여넣겠습니다.
dot sql and then let's go and paste our scripts
25:09:18
그리고 항상 그렇듯이 설명을 시작 부분에 넣습니다.
and as usual i put it at the start an explanation
25:09:22
이 검은색 절차에 대해 말하자면, 우리는 이 시작 절차가
about the sword procedure so we are saying this start procedure gonna
25:09:25
csv 파일에서 데이터를 로드할 것이라고 말하고 있습니다.
go and load the data from the csv files into the
25:09:28
브론즈 스키마에 데이터를 로드할 수 있도록 먼저 테이블을 잘라낼 수 있습니다.
bronze schema so it can go and truncate first the tables
25:09:31
그런 다음 대량 삽입을 수행하고, 이
and then do a bulk insert and about the parameters this
25:09:35
소스 절차는 어떤 매개변수도 받지 않으며 값을 반환하지 않습니다.
source procedure does not accept any parameter or return any values
25:09:38
여기에서 실행하는 방법에 대한 간단한 예가 있습니다. 자,
and here a quick example how to execute it all right so
25:09:41
저는 그게 마음에 드니 이제 가서
i think i'm happy with that so let's go and
25:09:45
커밋하겠습니다. 좋아요, 친구들, 그래서 그걸로
commit it all right my friends so with that
25:09:48
코드를 git에 커밋했습니다. 그리고 그걸로
we have committed our code into the git and with that we
25:09:51
브론즈 레이어 구축이 완료되었습니다. 그래서 전체 서사시가
are done building the bronze layer so the whole epic is
25:09:54
완료되었습니다. 이제 우리는 다음 단계로 넘어갈 것입니다. 이번 단계는 브론즈 레이어보다 더 고급이 될 것입니다. 왜냐하면
done now we're gonna go to the next one this one gonna be more advanced than the bronze layer because there will be a lot of
25:10:00
데이터 정리에 많은 어려움이 있을 것이기 때문입니다. 그래서 우리는 첫 번째 작업을 시작할 것입니다. 여기서 우리는 소스 시스템의 데이터를 분석하고 탐색할 것입니다. 자, 시작합시다.
struggle with cleaning the data and so on so we're gonna start with the first task where we're gonna analyze and explore the data in the source systems so let's go
25:10:12
좋아요, 이제 큰 질문을 시작하겠습니다. 실버 레이어를 어떻게 구축할까요?
okay so now we're gonna start with the big question how to build the silver
25:10:15
프로세스는 무엇인가요? 자, 항상 그렇듯이 첫 번째로 해야 할 일은 분석하는 것입니다. 이제 실버 레이어를 구축하기 전에
layer what is the process okay as usual first things first we have to analyze and now the task before building
25:10:22
무엇이든지 데이터를 탐색해야 합니다.
anything in the silver layer we have to go and explore the data
25:10:25
우리의 소스의 내용을 이해하기 위해서입니다. 한 번
in order to understand the content of our sources once
25:10:28
그것을 얻으면 우리는 코딩을 시작할 것입니다.
we have it what we're gonna do we will be starting coding and
25:10:31
여기서 우리가 할 변환은 데이터 정제입니다.
here the transformation that we're gonna do is data cleansing this
25:10:34
이 과정은 보통 정말 오랜 시간이 걸리며, 저는 보통
is usually process that takes really long time and i usually
25:10:37
세 단계로 진행합니다. 첫 번째 단계는 먼저
do it in three steps the first step is to check first
25:10:41
브론즈 레이어에서 우리가 가진 데이터 품질 문제를 확인하는 것입니다. 데이터 변환을 작성하기 전에 문제를 이해해야 하며, 그때서야 데이터 변환을 작성하기 시작합니다.
the data quality issues that we have in the bronze layer so before writing any data transformations first we have to understand what are the issues and only then i start writing data transformations
25:10:52
브론즈에서 우리가 가진 모든 품질 문제를 해결하기 위해서입니다.
in order to fix all those quality issues that we have in the bronze.
25:10:55
마지막 단계는 깨끗한 결과를 얻은 후, 실버 레이어에 삽입하는 것입니다.
And the last step, once I have clean results, what we're going to do, we're going to go and insert it into the silver layer.
25:11:01
이것이 우리가 실버 레이어 코드를 작성하면서 진행할 세 가지 단계입니다.
And those are the three phases that we will be doing as we are writing the code for the silver layer.
25:11:05
세 번째 단계는 실버 레이어에 모든 데이터가 있을 때, 데이터가 이제 올바른지 확인하고 더 이상 품질 문제가 없도록 하는 것입니다.
And the third step, once we have all the data in the silver layer, we have to make sure that the data is now correct and we don't have any quality issues anymore.
25:11:14
문제를 발견하면, 물론 우리가 할 수 있는 것은 다시 코딩으로 돌아가는 것입니다. 데이터 정제를 하고 다시 확인할 것입니다.
And if you find any issues, of course, what you can do, we're going to go back to coding. We're going to do the data cleansing and again, check.
25:11:20
이것은 검증과 코딩 사이의 사이클과 같습니다. 실버 레이어의 품질이 좋으면, 마지막 단계인 문서화와 작업을 Git에 커밋하는 단계를 건너뛸 수 없습니다.
So it is like a cycle between validating and coding. Once the quality of the silver layer is good, we cannot skip the last phase where we're going to document and commit our work in the Git.
25:11:30
여기서 우리는 두 가지 새로운 문서를 만들 것입니다. 데이터 흐름 다이어그램과 데이터 통합 다이어그램을 구축할 것입니다.
And here we're going to have two new documentations. We're going to build the data flow diagram and as well the data integration diagram after we understood the relationship between the sources from the first step.
25:11:41
이것이 프로세스이며, 이것이 우리가 실버 레이어를 구축하는 방법입니다.
So this is the process and this is how we're going to build the silver layer.
25:11:49
좋습니다. 이제 브론즈 레이어의 데이터를 탐색해 보겠습니다. 왜냐하면
all right so now exploring the data in the bronze layer so why it
25:11:52
데이터를 이해하는 것이 매우 중요하기 때문입니다.
is very important because understanding the data it is
25:11:55
시민 레이어에서 스마트한 결정을 내리는 열쇠입니다. 브론즈 레이어에서는
the key to make smart decisions in the civil layer it was
25:11:58
데이터의 내용을 이해하는 데 초점을 맞추지 않았습니다.
not the focus in the bronze layer to understand the content
25:12:01
데이터를 데이터 웨어하우스로 가져오는 방법에만 집중했습니다.
of the data at all we focus only how to get the data
25:12:05
그래서 이제 테이블을 탐색하고 이해하는 데 잠시 시간을 가져야 합니다.
to the data warehouse so that's why we have now to take a moment in
25:12:08
이 테이블들 간의 관계가 무엇인지 연결하는 방법을 이해하는 것이 매우 중요합니다.
order to explore and understand the tables and as well how to connect them what are the relationship between
25:12:14
새로운 소스 시스템에 대해 배우면서 문서를 작성하는 것입니다.
these tables and it is very important as you are learning about
25:12:18
이제 소스를 탐색해 보겠습니다. 좋아요, 이제 가서
the new source system is to create like some kind of documentation so
25:12:21
하나씩 탐색해 보겠습니다. 첫 번째는
now let's go and explore the sources okay so now let's go
25:12:24
CRM에서 고객 정보를 가지고 있습니다. 오른쪽 클릭하세요.
and explore them one by one we can start with the first one from the
25:12:27
상위 천 개 행을 선택하고, 이것은 물론 중요합니다.
crm we have the customer info so right click on it
25:12:31
데이터가 많다면 수백만 개의 행을 탐색하지 마세요.
and say select top thousand rows and this is of course important
25:12:34
데이터가 많다면 수백만 개의 행을 탐색하지 마세요.
if you have like a lot of data don't go and explore millions of rows
25:12:37
항상 쿼리를 제한하세요. 예를 들어, 여기서는 상위
always limit your queries so for example here we are using the top
25:12:40
수천 개만 사용하여 시스템에 영향을 주지 않도록 합니다.
thousands just to make sure that you are not impacting the system with your
25:12:43
쿼리를 이제 이 테이블의 내용을 살펴보겠습니다.
queries so now let's have a look to the content of this table so we
25:12:46
여기 고객 정보가 있습니다. 우리는
can see that we have here customer informations so we have
25:12:49
고객의 ID와 키, 이름, 성, 소매 상태, 성별이 있습니다.
an id we have a key for the customer we have first
25:12:52
고객의 생성 날짜도 있습니다. 간단히 말해, 이 테이블은
name last name my retail status gender and
25:12:55
고객 정보와 많은 세부 정보를 위한 것입니다.
the creation date of the customer so simply this is a table
25:12:58
고객에 대한 두 개의 식별자가 있습니다. 하나는
for the customer information and a lot of details for
25:13:02
기술 ID이고, 다른 하나는
the customers and here we have like two identifiers one
25:13:05
고객 번호와 같습니다. 아마도 우리는
it is like technical id and another one it's
25:13:08
아이디어나 키를 사용하여 다른 테이블과 조인할 수 있습니다.
like the customer number so maybe we can use either the
25:13:11
보통 제가 하는 것은 데이터 모델을 그리거나
idea or the key in order to join it with other tables so now what i
25:13:14
통합 모델을 문서화하고
usually do is to go and draw like data model or
25:13:17
제가 이해하는 것을 시각화하는 것입니다. 그렇게 하지 않으면
let's say integration model just to document and
25:13:20
시간이 지나면 잊어버릴 것입니다. 이제 도형을 찾으러 갑니다.
visual what i am understanding because if you don't do that you're
25:13:24
테이블을 검색해 보겠습니다. 이걸 선택할게요.
going to forget it after a while so now we go and search for a shape
25:13:27
여기서 스타일을 변경할 수 있습니다. 예를 들어, 둥글게 만들거나 스케치로 만들 수 있습니다.
let's search for a table and i'm gonna go and pick this one over
25:13:30
그리고 색상을 변경할 수 있습니다. 파란색으로 만들겠습니다.
here so here we can go and change the style for example we can make it rounded or you can go make it sketch and so on
25:13:37
그런 다음 텍스트로 가서 전체를 선택하세요.
and we can go and change the color i'm gonna make it blue
25:13:40
그리고 크기를 36으로 키웁니다.
then go to the text make sure to select the whole thing
25:13:43
그 아이템들에 대해 제가 할 것은 선택하는 것입니다.
and let's make it bigger 36 and
25:13:46
그들을 선택하고 정렬로 가서 40으로 만들 수 있습니다.
then what i'm gonna do for those items i'm just gonna select
25:13:49
이런 식으로, 이제 우리가 할 것은
them and go to arrange and maybe make it 40
25:13:53
테이블 이름을 넣는 것입니다. 이것이 우리가 사용할 것입니다.
something like this so now what we're gonna do we're gonna just go and
25:13:56
테이블 이름을 입력할 차례입니다. 이것이 우리가
put the table name so this is the one that we are
25:13:59
지금 배우고 있는 것입니다. 제가 할 일은
now learning about and what i'm gonna do i'm just gonna
25:14:02
여기에 기본 키를 입력하는 것입니다. 모든 정보를 나열하지는 않을 것입니다.
go and put here the primary key i will not go and list all the informations
25:14:05
기본 키는 ID였고, 저는
so the primary key was the id and i
25:14:09
지금 필요 없는 모든 것을 제거할 것입니다.
will go and remove all those stuff i don't need it now as
25:14:12
테이블 이름이 그리 친숙하지 않으니, 저는
you can see the table name is not really friendly so i can go and bring
25:14:15
텍스트를 가져와서 위에 넣고 이렇게 말할 것입니다.
a text and put it here on top and say this
25:14:18
이것은 고객 정보입니다. 친숙하게 만들기 위해서입니다.
is the customer information just to
25:14:21
그리고 잊지 않도록 하기 위해서입니다. 그리고 저는
make it friendly and to not forget about it and as
25:14:24
크기를 20 정도로 늘릴 것입니다.
well i'm gonna increase the size to maybe 20 something
25:14:27
이렇게 하면 첫 번째 테이블이 완성되었습니다.
like this okay with that we have our first table and
25:14:30
이제 계속 탐색할 것입니다. 두 번째로 이동합시다.
we're gonna go and keep exploring so let's move to the second one we're
25:14:34
제품 정보를 가져올 것입니다. 오른쪽 클릭하고
going to take the product information right click on it and
25:14:37
상위 천 개를 선택할 것입니다. 아래에 넣겠습니다.
select the top thousand draws i will just put it below
25:14:40
이전 쿼리를 쿼리하여 이 테이블을 살펴보겠습니다.
the previous query query it now by looking to this table
25:14:43
제품 정보가 있습니다. 여기에는
we can see we have product informations so we have here
25:14:46
제품의 기본 키가 있습니다. 그리고 우리는
a primary key for the product and then we have like a key or
25:14:50
제품 번호와 그 다음에 제품의 전체 이름이 있습니다.
let's say product number and after that we have the full name of
25:14:53
제품의 가격이 있고, 그 다음에
the product the product costs and then we have the
25:14:56
제품 라인이 있으며 시작과 종료가 있습니다.
product line and then we have like start and end
25:14:59
이것은 시작과 종료가 왜 있는지 이해하는 데 흥미롭습니다.
well this is interesting to understand why we have start and
25:15:02
예를 들어, 이 세 개의 행을 살펴봅시다.
ends let's have a look for example for those three rows
25:15:06
이 세 개 모두 같은 키를 가지고 있지만,
all of those three having the same key but they have
25:15:09
서로 다른 ID를 가지고 있습니다. 같은 제품이지만
different ids so it is the same product but
25:15:12
서로 다른 가격을 가지고 있습니다. 2011년에는 12의 가격이 있고, 2012년에는 14, 마지막 해인 2013년에는 13입니다.
with different costs so for 2011 we have the cost of 12 then 2012 we have 14 and for the last year 2013
25:15:22
13이 있으니, 우리는 역사처럼 보입니다.
13 we have 13 so it's like we have like a history for
25:15:25
변경 사항을 위해 이 표는 현재 정보를 보유하고 있을 뿐만 아니라
the changes so this table not only holding the current
25:15:28
제품의 역사 정보도 포함하고 있습니다.
informations of the product but also history informations
25:15:31
제품의 시작 및 종료 날짜가 있으며, 이제 이 정보를 다시 그려보겠습니다.
of the product and that's why we have those two
25:15:34
여기서 복제할 것이니 이 표의 이름은 brd 정보가 될 것이고, 현재 및 역사에 대한 짧은 설명을 추가하겠습니다.
dates start and end now let's go back and draw this information
25:15:37
제품 정보는 이런 식으로 될 것입니다.
over here so i'm just gonna go and duplicate it so the name of this table gonna be the brd info and let's go and give it like a short description current and history
25:15:48
이 표에 역사가 있다는 것을 잊지 않기 위해서입니다.
products information something like this
25:15:51
여기에도 prd id가 있습니다.
just to not forget that we have history in this table and here we
25:15:54
이 두 표를 연결하기 위해 사용할 수 있는 것이 없습니다.
have as well the prd id and there
25:15:57
여기나 다른 표에 고객 ID가 없습니다.
is like nothing that we can use in order to join those two tables
25:16:01
여기나 다른 표에 제품 ID가 없습니다. 이 표는 여기까지입니다.
we don't have like a customer id here or in the other table
25:16:04
여기나 다른 표에 고객 ID가 없습니다. 이 표는 여기까지입니다.
we don't have any product id okay so that's it for this table
25:16:07
세 번째 표로 넘어가고 CRM의 마지막 표로 가겠습니다.
let's jump to the third table and the last one in the crm so let's go and select i just made the other queries as well short so let's go and execute so
25:16:15
여기에는 주문에 대한 많은 정보가 있습니다.
what do you have over here we have a lot of informations about the order
25:16:18
판매 및 많은 측정값, 주문 번호가 있습니다.
the sales and a lot of measures order number we
25:16:21
제품 키가 있으니, 이것은 제품 표와 연결하는 데 사용할 수 있습니다.
have the product key so this is something that we
25:16:24
고객 ID가 있지만 고객 키는 없습니다.
can use in order to join it with the product table we have the
25:16:27
여기에는 ID가 있고, 여기에는 키가 있습니다.
customer id we don't have the customer key so here
25:16:30
표를 연결하는 두 가지 방법이 있으며, 여기에는 주문 날짜, 배송 날짜, 새 날짜가 있습니다.
we have like id and here we have key so there is like two
25:16:34
판매 금액, 수량 및 가격이 있으며, 이것은
different ways on how to join tables and then we have here like dates the order dates the shipping dates the new date and then we have
25:16:42
이벤트 표와 같으며, 거래 표입니다.
the sales amount the quantity and the price so this
25:16:45
주문 및 판매에 대한 것이며, 고객과 연결하기에 좋은 표입니다.
is like an event table it is transactional table about
25:16:48
제품과 고객을 연결하기 위한 것입니다.
the orders and sales and it is great table in order
25:16:51
주문과도 연결하기 위해서입니다. 이 새로운 정보를 문서화합시다.
to connect the customers with the products and
25:16:55
판매 및 주문에 대한 거래 기록입니다.
as well with the orders so let's document this new information that we have so the table name is the sales details so we can go and describe it like this transactional records
25:17:07
판매 및 주문에 대한
about sales and orders and
25:17:11
이 테이블을 다른 두 개와 연결하는 방법을 설명해야 합니다.
now we have to go and describe how we can connect this table to
25:17:14
우리는 제품 ID를 사용하지 않고
the other two so we are not using the product id we
25:17:17
제품 키를 사용하고 이제
are using the products key and now
25:17:20
여기에 새로운 열이 필요합니다. Ctrl과 Enter를 누를 수 있습니다.
we need a new column over here so you can hold ctrl and enter
25:17:23
여기에서 새 행을 추가할 수 있습니다.
or you can go over here and add a new row and
25:17:26
다른 행은 고객 ID가 될 수 있습니다. 이제 고객 ID에 대해
the other road can be the customer id so now for the customer id
25:17:30
쉽습니다. 연결하기 위해 화살표를 가져올 수 있습니다.
it is easy we can grow and grab an arrow in order to connect
25:17:33
이 두 테이블을 연결하지만 제품 키는 사용하지 않습니다.
those two tables but for the product key we are not
25:17:36
ID를 사용하지 않기 때문에 제거하겠습니다.
using the id so that's why i'm just gonna go and remove
25:17:39
이것은 제품 키입니다. 제품 ID가 아닙니다.
this one and say product key let's have you again you check so
25:17:42
이것은 제품 키입니다. 제품 ID가 아닙니다.
this is a product key it's not a product id as
25:17:45
구 제품 테이블을 확인하면 이 키를 사용하고 있습니다.
we go and check the old table the products info you
25:17:48
이제 우리가 할 일은 링크를 만드는 것입니다.
can see we are using this key and not the primary key
25:17:51
이렇게 하고 아마도 이 두 테이블을 바꿉니다.
so what we're gonna do now we will just go and link it like
25:17:54
고객을 아래에 두겠습니다. 완벽해 보입니다.
this and maybe switch those two tables so i
25:17:58
좋습니다. 계속 진행합시다. 이제
will put the customers below just perfect it looks
25:18:01
다른 소스 시스템으로 가겠습니다.
nice okay so let's keep moving let's go now to the
25:18:04
ARP 비용이 있으며 이 암호 같은 이름이 있습니다.
other source system we have the arp and the first one is
25:18:07
데이터를 선택합시다. 이제 여기 작은 테이블입니다.
arp costs and we have this cryptical name let's
25:18:10
정보가 세 개만 있습니다. 여기에는
go and select the data so now here it's small table
25:18:13
CID가 있고, 이것은
and we have only three informations so we have here something called
25:18:17
생일과 성별 정보가 있습니다.
cid and then we have something i think this is
25:18:20
남성, 여성 등으로 고객 정보처럼 보입니다.
the birthday and the gender information so we have here
25:18:23
여기에는 생일에 대한 추가 데이터가 있습니다.
male female and so on so it looks again like the customer informations
25:18:26
하지만 여기에는 생일에 대한 추가 데이터가 있습니다.
but here we have like extra data about the birthday and
25:18:29
이제 고객 테이블과 비교해 보겠습니다.
now if you go and compare it to the customer table that
25:18:32
다른 소스 시스템에서 가져온 데이터입니다. 쿼리를 실행해 보겠습니다.
we have from the other source system let's go and query it you
25:18:35
새 테이블은 ERP에서 가져온 것이며 ID가 없습니다.
can see the new table from the erp don't have ids it
25:18:39
실제로 고객 번호 또는 키가 있습니다.
has actually the customer number or the key so
25:18:42
고객을 사용하여 두 테이블을 조인할 수 있습니다.
we can go and join those two tables using the customer
25:18:45
정보를 문서화해 보겠습니다. 여기 오른쪽에 붙여넣겠습니다.
key let's go and document this information so i will just go and copy paste and put it here on the right side i will just go and change the color now since we are now talking
25:18:54
다른 소스 시스템에 대해 이야기하고 있습니다. 테이블 이름은
about different source system and here the table name
25:18:57
이것이 될 것이며 키는
gonna be this one and the key called
25:19:00
CID입니다. 고객 정보와 조인하려면 고객 ID가 아니라 고객 키가 필요합니다.
cid now in order to join this table with the customer info we cannot join it with the customer id we need the customer key that's why here we have to go and add a new row so control enter and we're gonna say
25:19:12
고객 키를 추가하고 화살표를 만들어야 합니다.
customer key and then we have to go and make a nice arrow
25:19:15
이 두 키 사이에 설명을 추가하겠습니다.
between those two keys so we're gonna go and give it a description
25:19:19
고객 정보와
customer information and
25:19:22
여기 생일이 있습니다. 이제 계속 진행하겠습니다.
here we have the birth date okay so now
25:19:25
다음으로 넘어가겠습니다.
let's keep going we're gonna go to the next
25:19:28
ERP 위치가 있습니다. 쿼리를 실행해 보겠습니다.
one we have the erp location let's
25:19:32
여기에서 CID가 있고 국가 정보가 있습니다.
go and query this table so what do you have over here we have the
25:19:35
이것은 고객 위치입니다. 테이블 이름은 이렇게 될 것입니다.
cid again and as you can see we have country informations and this is of course again the customer number and we have only this information the country so So let's go and document this information.
25:19:46
여기 고객 ID가 여전히 있으며 고객 키를 사용하여 조인할 수 있습니다.
This is the customer location. Table name going to be like this and we still have the same ID.
25:19:51
고객과 국가를 확인할 수 있습니다.
So we have here still that customer ID and we can go and join it using that customer key. And we have to give it that description location.
25:20:00
이제 마지막 테이블로 가서 탐색해 보겠습니다.
customers and we can see here the country okay
25:20:03
ERP EX 카탈로그가 있습니다.
so now let's go to the last table and explore it we
25:20:06
erp ex 카탈로그를 가지고 있으므로
have the erp ex catalog so
25:20:10
가서 그 정보를 쿼리해 보자, 그래서 우리가 무엇을 가지고 있지?
let's go and query those informations so what do we have
25:20:13
여기에는 ID와 카테고리가 있습니다.
here we have like an id a category a
25:20:17
하위 범주와 유지 관리가 있습니다. 이 표를 보면 모든 제품의 범주와 하위 범주를 확인할 수 있습니다.
subcategory and the maintenance here we have like either yes and no so by looking to this table we have all the categories and the subcategories of the products
25:20:26
여기에는 이러한 정보에 대한 특별 식별자가 있습니다.
and here we have like special identifier for those informations
25:20:29
이제 질문은 어떻게 연결할 것인가입니다.
now the question is how to join it so i
25:20:33
실제로 제품 정보와 연결하고 싶습니다.
would like to join it actually with the product informations so
25:20:36
이 두 테이블을 함께 확인해 보겠습니다. 제품에서는
let's go and check those two tables together okay so in the products
25:20:39
범주에 대한 ID가 없지만 이러한 정보가 있습니다.
we don't have any id for the categories but we have these
25:20:42
실제로 제품 키에 있는 정보입니다.
informations actually in the product key
25:20:45
제품 키의 처음 다섯 글자는 실제로
so the first five characters of the product key is actually
25:20:48
범주 ID이므로 이 정보를 사용할 수 있습니다.
the category id so we can use this information
25:20:52
여기에서 범주와 연결하기 위해서입니다.
over here in order to join it with the categories
25:20:55
이 정보를 설명할 수 있습니다.
so we can go and describe this information like
25:20:58
이제 이름을 지정해야 하고, 여기에서
this and then we have to go and give it a name and then here we
25:21:01
ID가 있으며, ID는 다음을 사용하여 연결할 수 있습니다.
have the id and the id could be joined using
25:21:04
제품 키이므로 제품 정보에 대해
the product key so that means for the product information
25:21:08
제품 ID는 전혀 필요하지 않습니다. 기본 키는
we don't need at all the product id the primary
25:21:11
우리가 필요한 것은 제품 키 또는 제품 번호입니다.
key all what we need is the product key or the product
25:21:14
이 정보를 그룹화하고 싶습니다.
number and what i would like to do is like to group those informations
25:21:17
상자에 넣고, 왼쪽에 있는 상자를 가져옵니다.
in a box so let's go grab
25:21:20
크기를 키우고 가장자리를
like any boxes here on the left side and and
25:21:23
조금 더 작게 만들고 채우기를 제거합니다.
make it bigger and then make the edges
25:21:27
선을 점선으로 만들고, 다른 상자를 가져옵니다.
a little bit smaller let's remove the fill and
25:21:30
여기에서 다른 상자를 만들고 이것이
the line i will make a dotted line and then let's grab
25:21:33
CRM이며 크기를 늘릴 수 있습니다.
another box over here and say this is the
25:21:36
예를 들어 40, 35로 작게 만들고 굵게 합니다.
crm and we can go and increase the size maybe something
25:21:39
40처럼 작고 35처럼 굵게
like 40 smaller 35 bold
25:21:42
그리고 색상을 파란색으로 변경하고 이 상자 위에 배치하여 모든 테이블을 이해할 수 있습니다.
and change the color to blue and just place it here on top of this box so with that we can understand all those tables
25:21:48
소스 시스템 CRM에 속하며 우리는 할 수 있습니다.
belongs to the source system crm and we can do
25:21:52
오른쪽에도 같은 작업을 할 수 있습니다.
the same stuff for the right side as well now
25:21:55
물론 여기에서 설명을 추가해야 합니다.
of course we have to go and add the description here so it
25:21:58
모든 제품 카테고리가 될 수 있습니다.
can be the product categories all
25:22:01
그렇다면 이제 서로의 테이블이 어떻게 연결되어 있는지 명확하게 이해하게 되었습니다.
right so with that we have now a clear understanding how
25:22:04
각 테이블의 내용을 이해하고, 물론 도움이 될 수 있습니다.
the tables are connected to each other's we understand now
25:22:07
데이터를 정리하기 위해 실버 레이어에서 준비하는 데 도움이 됩니다.
the content of each table and of course it can help us
25:22:10
그래서 보시다시피 구조를 이해하는 것이 매우 중요합니다.
to clean up the data in the silver layer in order to prepare
25:22:14
테이블의 구조와 관계를 이해하는 데 시간을 투자해야 합니다.
it so as you can see it is very important to take
25:22:17
코드를 작성하기 전에 그들에 대해 알아야 합니다.
time understanding the structure of the tables the relationship between
25:22:20
소스에 대한 명확한 이해를 가지게 되었고, 데이터 통합을 생성했습니다.
them before starts writing any code all right so with
25:22:23
소스를 연결하는 방법에 대한 이해를 높였습니다.
that we have now clear understanding about the sources and with that we have as well created a data integration in the draw so with that we have more understanding
25:22:32
SQL로 돌아가 품질을 확인하고 많은 데이터 변환을 수행할 것입니다.
about how to connect the sources and now in the next two tasks we will go back to sql where we're going to start checking the quality and as well doing a lot of data transformations
25:22:42
자, 가자.
so let's go okay
25:22:47
자, 이제 은색 레이어의 사양을 간단히 살펴보자.
so now let's have a quick look to the specifications of the silver layer
25:22:50
그래서 깨끗하고 표준화된 데이터를 갖는 것이 주요 목표다.
so the main objective to have clean and standardized
25:22:53
데이터를 준비해야 하며, 그 후에 진행할 것이다.
data we have to prepare the data before going
25:22:56
골드 레이어로 가기 전에 테이블을 내부에 구축할 것이다.
to the gold layer and we will be building tables inside
25:22:59
은색 레이어에서 브론즈에서 은색으로 데이터를 로드하는 방법은 전체 로드이다.
the silver layer and the way of loading the data from the bronze
25:23:02
즉, 우리는 데이터를 잘라내고 삽입할 것이며, 여기서 많은 데이터 변환이 이루어질 것이다.
to the silver is a full load so that means we're gonna truncate and then insert and here we're gonna have a lot of data transformations so we're gonna clean the data
25:23:10
우리는 정규화와 표준화를 가져올 것이며,
we're going to bring normalization standardizations we're
25:23:13
새로운 열을 도출할 것이고, 데이터도 수행할 것이다.
going to derive new columns we will be doing as well data
25:23:16
데이터 변환에서 해야 할 일이 많다.
enrichment so a lot of things to be done in the data transformation
25:23:19
하지만 우리는 새로운 데이터 모델을 구축하지 않을 것이다.
but we will not be building any new data model so
25:23:23
이것이 사양이며 우리는 이에 전념해야 합니다
those are the specifications and we have to commit ourselves to this
25:23:26
이제 실버 레이어를 위한 ddl 스크립트를 작성하고 있습니다
scope okay so now building the ddl script for the silver layer gonna
25:23:29
브론즈보다 훨씬 쉬울 것입니다. 정의가
be way easier than the bronze because the definition
25:23:32
실버의 각 테이블 구조는 브론즈와 동일할 것입니다
and the structure of each table in the silver gonna be identical
25:23:36
브론즈 레이어와 동일하므로 새로운 작업은 없습니다
to the bronze layer we are not doing anything new so
25:23:39
브론즈에서 ddl 스크립트를 가져오기만 하면 됩니다
all what you have to do is to take the ddl script from the bronze
25:23:42
스키마에 대해 검색하고 교체하면 됩니다
layer and just go and search and replace for the schema
25:23:46
스크립트에 대해 노트패드 플러스 플러스를 사용하고 있습니다
i'm just using the notepad plus plus for the scripts so i'm
25:23:49
브론즈 점을 실버 점으로 교체하겠습니다
gonna go over here and say replace the bronze dots with
25:23:52
이제 모든 ddl이 스키마 실버 레이어를 대상으로 합니다
silver dots and i'm gonna go and replace all
25:23:55
이제 메타데이터 열에 대해 이야기해야 합니다.
so with that now all the ddl is targeting the schema silver layer which is exactly what we need all right now before we execute our new ddl script for the silver
25:24:05
추가 열 또는 필드입니다
we have to talk about something called the metadata columns.
25:24:08
데이터 엔지니어가 각 테이블에 추가하는 열입니다
They are additional columns or fields that
25:24:11
예를 들어 생성 날짜라는 열을 추가할 수 있습니다
the data engineers add to each table that don't come directly from the source systems, but the data engineers use it in order to provide extra information for each record.
25:24:22
레코드가 로드된 날짜 또는 업데이트된 날짜를 추가할 수 있습니다
Like we can add a column called create date is
25:24:25
데이터의 출처를 이해하기 위해 소스 시스템을 추가할 수 있습니다
when the record was loaded or an update date when the record got updated or we can add the source system in order to understand
25:24:33
파일 위치를 추가하여 이해할 수 있습니다
the origin of the data that we have or sometimes we
25:24:36
데이터가 어디서 왔는지 추적할 수 있습니다
can add the file location in order to understand the
25:24:39
데이터 웨어하우스에서 데이터 문제가 발생하면 유용한 도구입니다
lineage from which file the data come from those are
25:24:42
손상된 데이터가 있는 경우 이 도구가 도움이 됩니다
great tool if you have data issue in your data warehouse if
25:24:46
문제가 발생하는 정확한 위치를 추적할 수 있습니다
there is like corrupt data and so on this can help you
25:24:49
문제가 발생하는 시점과 함께
to track exactly where this issue happens and
25:24:52
데이터에 간격이 있는지 이해하는 데 유용합니다
when and as well it is great in order to understand whether i
25:24:55
모든 것에 레이블을 붙이는 것과 같습니다
have gap in my data especially if you are doing incremental loads
25:24:59
어려운 시기에 사용할 때 자신에게 감사할 것입니다
it is like putting labels on everything and you will
25:25:02
어려운 시기에 사용할 때 스스로에게 감사할 것입니다.
thank yourself later when you start using them in hard times
25:25:05
이제 데이터 웨어하우스의 문제로 돌아가서
as you have an issue in your data warehouse so now back to
25:25:08
우리의 ddl 스크립트로 가서 다음을 수행하면 됩니다.
our ddl scripts and all what you have to do is to go and do the following
25:25:11
예를 들어 첫 번째 테이블에 추가할 것입니다.
so for example for the first table i will go and add
25:25:14
끝에 하나의 추가 열을 추가하여 dwh 접두사로 시작합니다.
at the end one more extra column so it starts with the prefix dwh as we have defined in the naming
25:25:21
규칙을 정의한 대로 언더스코어를 추가하여 생성합니다.
convention and then underscore let's have that create
25:25:25
날짜와 데이터 유형은 시간을 가질 수 있습니다.
dates and the data type can be the time to
25:25:28
이것에 대해 기본값을 추가할 수 있습니다.
and now what we can do is we can go and add a default value
25:25:31
데이터베이스가 이러한 정보를 자동으로 생성하도록 하고 싶습니다.
for it i want the database to generate these informations automatically
25:25:34
ETL 스크립트에서 이를 지정할 필요가 없습니다.
we don't have to specify that in any etl scripts
25:25:37
어떤 값이 될지 가져오는 날짜입니다.
so which value it's going to be the get date so
25:25:40
각 레코드는 자동으로 현재 날짜와 시간의 값을 받게 됩니다.
each record going to be inserted in this table will get automatically a value from the current date and time so now as you can see the naming convention
25:25:49
모든 열은 소스 시스템에서 가져옵니다.
it is very important all those columns comes from the source system
25:25:52
단 하나의 열만 데이터 엔지니어에서 가져옵니다.
and only this one column comes from the data engineer
25:25:55
모든 다른 테이블에 대해 동일한 작업을 반복하겠습니다.
of the data warehouse okay so that's it let's go and repeat the same thing for all other tables so i will just go and add this piece of information for each ddl
25:26:07
이제 전체 ddl 스크립트를 실행해야 합니다.
all right so i think that's it all what you have to do is now to
25:26:10
서버 레이어의 테이블을 새로 고칩니다.
go and execute the whole ddl script for the server layer let's go into that all right perfect there's no errors let's go and refresh
25:26:17
서버 레이어에서 데이터를 쓰기 전에
the tables on the object explorer and with that as you can see we have six tables for the server layer it is identical to the bronze layer but we have one extra column for the metadata
25:26:33
변환 및 정리를 위해 먼저 감지해야 합니다.
all right so now in the server layer before we start writing any data
25:26:36
품질 문제를 찾아야 합니다.
transformations and cleansing we have first to detect
25:26:39
모든 테이블을 살펴보겠습니다.
the quality issues in the bronze without knowing the issues we cannot find solution right we will explore first the quality issues only then we start writing the transformation scripts so let's go
25:26:57
데이터를 정리하고 서버 레이어에 삽입합니다.
okay so now what we're gonna do we're gonna go through all the tables over the bronze
25:27:00
여기에서 데이터를 쿼리해 보겠습니다.
layer clean up the data and then insert it to the server layer so let's start with the first table the first bronze table from the source crm so we're gonna go to the bronze crm customer info
25:27:13
첫 번째 체크에서 기본 키를 확인합니다.
So let's go and query the data over here. Now, of course, before writing any data transformations, we have to go and detect and identify the quality issues of this table.
25:27:23
기본 키에 null이 있는지 확인해야 합니다.
So usually I start with the first check where we go and check the primary key.
25:27:27
그래서 우리는 기본 키 안에 널 값이 있는지와 중복이 있는지를 확인해야 합니다.
So we have to go and check whether there are nulls inside the primary key and whether there are duplicates.
25:27:32
이제 기본 키에서 중복을 감지하기 위해 우리가 해야 할 일은 기본 키를 집계하는 것입니다.
So now in order to detect the duplicates in the primary key, what we have to do is to go and aggregate the primary key.
25:27:38
기본 키에서 한 번 이상 존재하는 값을 찾으면
if we find any value in the primary key that exists more
25:27:42
그것은 고유하지 않다는 것을 의미하며 중복이 있습니다.
than once that means it is not unique and we have duplicates
25:27:45
테이블에서 중복이 있으므로 이를 위한 쿼리를 작성해 보겠습니다.
in the table so let's go and write a query for that so
25:27:48
우리가 할 일은 고객 ID로 가고
what we're gonna do we're gonna go with the customer id and then we're
25:27:51
세고 데이터를 그룹화해야 합니다.
gonna go and count and then we have to group up the data
25:27:54
기본 키를 기준으로 그룹화하고
so group by based on the primary key and
25:27:57
물론 모든 결과가 필요하지 않습니다. 중복이 있는 경우만 필요합니다.
of course we don't need all the results we need only where we have an
25:28:00
카운트가 1보다 큰 경우를 말할 것이므로 관심이 있습니다.
issue so we're gonna say having counts higher than one so we are interested
25:28:07
카운트가 1보다 큰 값에서
in the values where the count is higher than one so
25:28:10
지금 실행해 보겠습니다. 보시다시피
let's go and execute it now as you can see we have
25:28:13
이 테이블에 중복이 있습니다. 모든 ID가
issue in this table we have duplicates because all those
25:28:16
테이블에 한 번 이상 존재하기 때문입니다.
ids exist more than one in the table which
25:28:19
완전히 잘못된 것입니다. 기본 키는 고유해야 합니다.
is completely wrong we should have the primary key unique and you can
25:28:22
기본 키가 비어 있는 세 개의 레코드가 있습니다.
see as well we have three records where the primary key is
25:28:25
비어 있는 것은 나쁜 일입니다. 이제 문제가 있습니다.
empty which is as well a bad thing now there is an issue
25:28:28
여기서 널이 하나만 있으면 결과에 나타나지 않습니다.
here if we have only one null it will not
25:28:31
기본 키가 널인 경우라고 말할 것입니다.
be here at the result so what i'm gonna do i'm gonna go over here and
25:28:35
널이 하나만 있는 경우에도 여전히 결과를 보고 싶습니다.
say or the primary key is null just
25:28:38
다시 실행하면 같은 결과를 얻을 수 있습니다.
in case if we have only one null i'm still interested to
25:28:42
이것은 테이블에서 수행할 수 있는 동등성 검사입니다.
see the results so if i go and run it again we'll get
25:28:45
기대에 미치지 못하고 있습니다.
the same results so this is equality check that you can do on the
25:28:48
따라서 우리는 이에 대해 조치를 취해야 합니다.
table and as you can see it is not meeting the expectation so
25:28:51
새 쿼리를 생성하겠습니다. 여기서 시작할 수 있습니다.
that means we have to do something about it so let's go
25:28:54
새 쿼리를 작성해야 하므로 시작해 보겠습니다.
and create a new query so here what we're gonna do we can start
25:28:57
데이터 변환을 수행하는 쿼리를 작성하고 있습니다.
writing the query that is doing the data transformation
25:29:00
데이터 정리를 위해 다시 시작하겠습니다. 데이터를 선택하고 다시 실행해 보겠습니다.
and the data cleansing so let's Let's start again by selecting the data and execute it again.
25:29:10
그래서 이제 제가 보통 하는 것은 문제에 집중하는 것입니다.
So now what I usually do, I go and focus on the issue. So for example, let's go and take one of those values and I focus on it before start writing the transformation.
25:29:19
고객 ID가 이 값과 같다고 말할 것입니다. 알겠죠.
So we're going to say where customer ID equal to this value. All right.
25:29:23
여기서 ID가 세 번 존재하는 문제가 있습니다.
So now as you can see, we have here the issue where the ID exists three times, but actually we are interested only on one of them.
25:29:30
그래서 그 중 하나를 선택하는 방법이 문제입니다.
So the question is how to pick one of those. Usually we search for a timestamp or date value to help us.
25:29:36
여기 생성 날짜를 확인하면 이 레코드가 가장 최신임을 알 수 있습니다.
So if you check the creation date over here, we can understand that this record, this one over here is the newest one.
25:29:44
이전 두 개는 그것보다 오래되었습니다.
And the previous two are older than it. So that means if I have to go and pick one of those values, I would like to get the latest one.
25:29:51
가장 신선한 정보를 담고 있기 때문입니다.
Because it holds the most fresh information. So what we have to do is, we have to go and rank all those values based on the
25:29:59
모든 값을 생성 날짜를 기준으로 정렬해야 합니다.
create dates and only pick the highest one
25:30:02
그래서 우리는 순위 기능이 필요합니다.
so that means we need the ranking function and for that in
25:30:05
우리는 놀라운 윈도우 함수를 사용할 것입니다.
scale we have the amazing window functions so let's
25:30:08
그렇게 하겠습니다. 함수 번호를 사용할 것입니다.
go and do that we will use the function row
25:30:12
고객 ID로 테이블을 나누어야 합니다.
number over and then partition
25:30:15
이제 이러한 행을 정렬해야 합니다.
by and here we have to divide the table by the customer id so we're gonna divide it by the
25:30:22
무언가에 따라 데이터를 정렬해야 합니다.
custom id and in order now to rank those rows we
25:30:25
우리가 논의한 대로 생성 날짜로 데이터를 정렬하고자 합니다.
have to sort the data by something so order by and
25:30:28
그래서 생성 날짜로 정렬합니다.
as we discussed we want to sort the data by that creation date
25:30:31
그래서 날짜를 생성하고
so create date and
25:30:34
내림차순으로 정렬할 수 있으니 가장 높은 것이 먼저 오고 그 다음은
we can sort it descending so the highest first then the
25:30:37
가장 낮은 것이니 이제 가서 그렇게 해보자 그리고 이제 우리는 그것에
lowest so let's go and do that and now we're going to go and give it a
25:30:41
이름 플래그를 마지막으로 주자 이제 가서
name flag last so now let's go and
25:30:44
실행해보자 이제 데이터는 생성 날짜로 정렬되었고 여기에서 이 레코드가 1번임을 볼 수 있다 그 다음은
execute it now the data is sorted by the creation date and you can see over here that this record is the number one then
25:30:51
더 오래된 것이 2번이고 가장 오래된 것은 3번이다
one that is older is two and the oldest one is three
25:30:54
물론 우리는 1위에 관심이 있습니다
of course we are interested in the rank number one
25:30:57
이제 필터를 제거하고 모든 것을 확인해 보겠습니다
now let's go and remove the filter and check everything so
25:31:00
이제 표를 살펴보면 깃발에
now if you have a look to the table you can see that on the flag we have
25:31:03
어디에나 1처럼 보이고 그 이유는
everywhere like one and that's because the those
25:31:07
기본 키는 하나만 존재하지만 때때로 우리는
primary keys exist only one but sometimes we will not
25:31:10
하나가 아니라 두 개, 세 개가 있을 수 있습니다. 이중 키가 있다면
have one we'll have two three and so on if there's like double kits we
25:31:13
물론 다시 확인할 수 있으니 여기로 가서
can go of course and do a double check so let's go over here and say
25:31:16
이 쿼리에서 별을 선택합니다
select star from this query
25:31:19
깃발이 지속되는 곳을 말할 수 있습니다
you can say where flag lasts is
25:31:23
하나와 같으니 이제 쿼리해 보겠습니다
in equal to one so let's go and query it and now
25:31:26
우리는 필요 없는 모든 데이터를 볼 수 있습니다. 그들은
we can see all the data that we don't need because they are causing
25:31:29
기본 키에서 중복을 일으키고 있으며 오래된 상태입니다
duplicates in the primary key and they have like an old status
25:31:32
당신이 할 수 있는 것은 1과 같다고 말하는 것입니다
so what you can do we're gonna say equal to one and
25:31:35
그렇게 하면 기본 키가 고유하고 각
with that we guarantee that our primary key is unique and each
25:31:38
값이 한 번만 존재한다고 보장합니다. 그래서 이렇게 쿼리하면
value exists only once so if i go and query it like this
25:31:42
테이블 안에 중복이 없다는 것을 볼 수 있습니다
you will see we will not find any duplicates inside our table
25:31:45
물론 그것을 확인할 수 있으니 가서 확인해 보겠습니다
and we can go and check that of course so let's go and check this
25:31:48
기본 키와 고객 ID를 말할 것입니다
primary key and we're gonna say and customer id
25:31:51
이 값과 같다고 말하면 존재하는 것을 볼 수 있습니다
equal to this value and you can see it exists
25:31:54
이제 한 번만 존재하며 최신 데이터를 가져옵니다
now only once and we are getting the freshest data from
25:31:57
이 기본 키에서 중복을 제거하기 위해 정의했습니다
this primary key so with that we have defined like transformation
25:32:01
중복을 제거하기 위해 이제
in order to remove any duplicates okay so now
25:32:04
다음으로 넘어가면 표에서 볼 수 있습니다
moving on to the next one as you can see in our table we have
25:32:07
많은 값이 문자열처럼 있습니다
a lot of values where they are like string
25:32:10
이 문자열 값에 대해 원하지 않는 공백을 확인해야 합니다
values now for these string values we have to check the unwanted spaces so now let's go and write the query that's gonna detect those unwanted spaces so we're gonna say select
25:32:21
이 열은 우리의
this column the first name from our
25:32:24
브론즈 고객 정보 테이블입니다
table bronze customer information so
25:32:28
이제 데이터를 살펴보며 쿼리를 실행해 보겠습니다
let's go and query it now by just looking to the data
25:32:31
특히 원하지 않는 공백을 찾기가 정말 어려울 것입니다
it's going to be really hard to find those unwanted spaces especially
25:32:34
세상 끝에 있을 경우에는
if they are at the end of the world but there is a very easy way in order to detect those issues so what we're gonna do we're gonna do a filter so now we're gonna say the first name
25:32:44
공백이 제거된 첫 번째 이름과 같지 않습니다
is not equal to the first name after trimming
25:32:47
값을 사용하면
the values so if you use the function trim what it can do
25:32:50
모든 앞뒤 공백을 제거합니다
it's gonna go and remove all the leading and trailing
25:32:53
이 값이 공백이 제거된 첫 번째 이름과 같지 않다면
spaces so the first name so if this value
25:32:57
문제가 발생합니다
is not equal to the first name after trimming
25:33:00
시작이나 끝에 공백이 있는 모든 첫 번째 이름의 목록을 얻을 것입니다
it then we have an issue so it is very simple let's go and execute it so now in the results we will get the list of all first names where we have
25:33:09
여기서 기대하는 것은 없습니다
spaces either at the start or at the end so
25:33:12
결과와 같은 것을 확인할 수 있습니다
again the expectation here is no
25:33:15
예를 들어 성을 확인해 보겠습니다
results and the same thing we can go and check something
25:33:19
여기에서 그것을 수행해 보겠습니다
else like for example the last name so let's go
25:33:22
여기와 여기에서 그렇게 하고 갑시다.
and do that over here and here let's go
25:33:25
실행해보면 결과에서 17명의 고객이 성에 공백이 있는 것을 볼 수 있습니다. 이는 자연스럽게 좋은 일이며 계속 확인할 수 있습니다.
and execute it we see in the results we have as well 17 customers where they have like space in their last name which is naturally good and we can go and keep checking
25:33:35
테이블 안에 있는 모든 문자열 값을 확인합니다. 예를 들어,
all the string values that we have inside the table so for example the
25:33:38
성별을 확인해보겠습니다.
gender so let's go and check that and
25:33:43
지금 실행하면 결과가 없다는 것은
execute now as you can see we don't have any results that means
25:33:46
성별의 품질이 더 좋고 원하지 않는 공백이 없다는 것을 의미합니다.
the quality of the gender is better and we don't have
25:33:49
이제 두 열을 정리하기 위해 변환을 작성해야 합니다.
any unwanted spaces so now we have to go and write transformation in
25:33:53
쿼리에서 별 대신 모든 열을 나열할 것입니다. 알겠습니다. 이제 필요한 모든 열의 목록이 있습니다.
order to clean up those two columns now what i'm gonna do
25:33:56
이제 해야 할 일은 그 두 열로 가서 시작하는 것입니다.
i'm just gonna go and list all the columns in the query instead of the star all right so now i have a list of all the columns that i need
25:34:03
그 두 열로 가서 시작해야 합니다.
and now what we have to do is to go to those two columns and start
25:34:06
원하지 않는 공백을 제거해야 합니다.
removing the unwanted spaces so we'll just use
25:34:09
트림을 사용할 것입니다. 아주 간단합니다.
the trim it's very simple and
25:34:13
물론 같은 이름을 주고
give it a name of course the same name and we will
25:34:16
성도 트림할 것입니다. 그러니
trim as well the last name so let's
25:34:19
이것을 쿼리하고 두 열을 정리했습니다.
go and query this and with that we have cleaned up those two columns
25:34:22
원하지 않는 공백에서 정리했습니다. 이제
from any unwanted spaces okay so now moving on we
25:34:25
결혼 상태와
have those two informations we have the marital status and
25:34:28
성별도 있습니다. 두 열의 값을 확인하면
as well the gender if you check the values inside those two columns as you As you can see, we have here low cardinality, but we have limited numbers of possible values that is used inside those two columns.
25:34:39
데이터 일관성을 확인해야 합니다. 매우 간단합니다.
So what you should do is to go and check that data consistency inside those two columns. So it's very simple.
25:34:45
무엇을 할까요? 다음과 같은 작업을 할 수 있습니다.
What are you going to do? You can do the following. We're going to say distinct and we're going to check the values.
25:34:52
가서 그렇게 해봅시다. 세 가지 가능한 값만 있습니다.
Let's go and do that. And as you can see, we have only three possible values, either null, F or M, which is okay.
25:35:00
물론 이렇게 유지할 수 있지만 프로젝트에서 규칙을 만들 수 있습니다.
We can stay like this of course but we can make a rule in our project
25:35:03
데이터 약어를 사용하지 않겠다고 말할 수 있습니다.
where we can say we will not be working with data abbreviations
25:35:06
우리는 친숙한 전체 이름만 사용할 것입니다.
we will go and use only friendly full
25:35:09
f 대신에 여성이라는 전체 단어를 사용할 것입니다.
names so instead of having an f we're gonna have like
25:35:12
m 대신에 남성이라는 전체 단어를 사용할 것입니다.
a full word female and instead of m we're gonna have
25:35:15
그래서 성별로 가서 조건문을 작성합니다.
like male and we make it as a rule for the whole project so each time we find the gender informations we try to give the full name of it So let's go and map those two values to a friendly one.
25:35:26
성별이 F일 때 여성으로 만듭니다.
So we're going to go to the gender over here and say case when. And we're going to say the gender is equal to F.
25:35:34
M일 때 남성으로 매핑합니다.
Then make it a female. And when it is equal to M, then map it to male.
25:35:45
이제 null에 대한 결정을 내려야 합니다.
And now we have to make decision about the nulls. As you can see over here, we have nulls.
25:35:49
null로 남길지 아니면 항상 사용하고 싶습니다.
so do we want to leave it as a null or we want to use always
25:35:53
누락된 값을 표준 기본 값으로 대체합니다.
the value unknown so with that we are replacing
25:35:56
또는 null로 남길 수 있지만 우리 프로젝트에서는
the missing values with standard default value
25:35:59
모든 누락된 값을 기본 값으로 대체합니다.
or you can leave it as null but let's say in our project that
25:36:03
그렇게 해봅시다. 그렇지 않으면 사용 불가능으로 가겠습니다.
we are replacing all the missing value with a default value
25:36:06
그래서 우리가 그걸 하러 가자. 나는 na, 사용 불가로 가거나 알 수 없는 것으로 갈 것이다.
so let's go and do that we're gonna say else i'm gonna go with the na not available or you can go with the unknown
25:36:14
물론, 그래서 그건 성별 정보에 대한 것이다.
of course so that's for the gender information
25:36:17
이렇게 하고 우리는 오래된 것을 제거할 수 있다.
like this and we can go and remove the old one and
25:36:20
지금 이 경우에 내가 보통 하는 한 가지가 있다.
now there is one thing that i usually do in this case where sometimes
25:36:23
현재 우리는 대문자 F와 대문자를 받고 있다.
what happens currently we are getting the capital f and the capital
25:36:26
하지만 시간이 지나면서 변화가 있을 수 있다.
m but maybe in the time something change and you will get like
25:36:30
소문자 m과 소문자 f를 받을 수 있으니.
lower m and lower f so just to make sure in those
25:36:33
그런 경우에 우리는 여전히 그 값을 올바르게 매핑할 수 있다.
cases we still are able to map those values to the correct
25:36:36
우리가 할 것은 upper 함수를 사용할 것이다.
value what we're gonna do we're gonna just use the function upper
25:36:39
소문자를 받는 경우를 대비하기 위해서다.
just to make sure that if we get any lowercase
25:36:43
그렇게 해서 우리는 그것을 잡을 수 있다.
values we are able to catch it so
25:36:46
여기서도 같은 일이 발생한다.
the same thing over here as well and
25:36:49
이제 추가할 수 있는 한 가지가 있다.
now one more thing that you can add as well of course if you are not
25:36:52
데이터를 신뢰하지 않는다면 원치 않는 공백을 보았다.
trusting the data because we saw some unwanted spaces
25:36:55
이름과 성에 원치 않는 공백이 있을 수 있다.
in the first name and the last name you might not trust that in the future you will get here as well unwanted spaces you can go and make sure to trim everything
25:37:04
모든 경우를 잡고 있는지 확인하기 위해서다.
just to make sure that you are
25:37:07
이제 실행하러 가자.
catching all those cases so that's it for
25:37:10
우리는 m과 f가 아닌 전체 단어 male이 있다.
now let's go and execute now as you can see we don't have
25:37:13
여성과 만약 값이 없다면 null이 된다.
an m and an f we have a full word male
25:37:16
여기서 사용 불가로 나타난다.
and female and if we don't have a value we don't have a
25:37:20
이제 우리는 경과 상태에 대해 같은 작업을 할 수 있다.
null we are getting here not available now we can go
25:37:23
우리는 세 가지 가능성만 있다.
and do the same stuff for the meridian status you can see as well we have only three possibilities the s null and an
25:37:29
m을 가지고 우리는 같은 작업을 할 수 있다.
m we can go and do the same stuff so i will just go
25:37:32
여기서 모든 것을 복사하고 사용할 것이다.
and copy everything from here and i will go and use
25:37:36
혼인 상태를 사용하고 이 하나를 제거한다.
the marital status i just remove this one
25:37:39
여기서부터 가능한 값은 무엇인지
from here and now what are the possible values we have the s
25:37:42
단일로 설정할 것입니다.
so it's gonna be single we have an m
25:37:45
결혼한 경우와 null도 있습니다.
for married and we have as well a null
25:37:48
이로 인해 사용 가능한 데이터 표준화를 진행하고 있습니다.
and with that we are getting the not available so with that we are making as well data standardizations for this
25:37:55
이제 실행해 보겠습니다.
column so let's go and execute it now as you
25:37:58
짧은 값이 없고 전체 친숙한 값이 있습니다.
can see we don't have those short values we have a full friendly
25:38:01
상태와 성별에 대한 값입니다.
value for the status and as well for the gender and
25:38:05
이 두 열에 대한 작업이 완료되었습니다.
at the same time we are handling the nulls inside those two
25:38:08
이제 마지막 열로 이동하겠습니다.
columns so with that we are done with those two columns and now we can
25:38:11
이 열이 실제 날짜인지 확인합니다.
go to the last one that create date for this type of informations
25:38:14
완전히 정확하므로 이 열에 대해 할 일이 없습니다.
we make sure that this column is a real date and not as a string or varchar and as we defined it in the data type it is a date which
25:38:22
이제 다음 단계는 삽입을 작성하는 것입니다.
is completely correct so nothing to do with this column
25:38:25
여기서 시작하여 삽입을 작성합니다.
and now the next step is that we're going to go and write that insert
25:38:28
silver.srm에 삽입합니다.
statement so how we're going to do it we can go to the start over here and say
25:38:32
고객 정보를 삽입합니다.
insert into silver.srm
25:38:36
모든 열을 지정해야 합니다.
customer info now we have to go and specify all
25:38:39
이와 같은 형식으로 입력할 것입니다.
the columns that should be inserted so we're going
25:38:42
쿼리를 실행하여 깨끗한 데이터를 삽입했습니다.
to go and type it so something like this and then we have the
25:38:45
이제 silver 테이블로 이동하겠습니다.
query over here let's go and execute it so let's do that so with that we have inserted clean data
25:38:52
사용한 모든 쿼리를 가져옵니다.
inside the silver table so now what we're gonna do we're gonna go
25:38:55
청동의 품질을 확인합니다.
and take all the queries that we have used in order to
25:38:58
청동 대신 은으로 변경합니다.
check the quality of the bronze and let's go and take it to another
25:39:01
이것은 기본 키에 대한 것입니다.
query and instead of having bronze we're gonna say silver
25:39:05
완벽하게 실행하여 결과가 없습니다.
so this is about the primary key let's go and
25:39:08
중복이 없습니다.
execute it perfect we don't have any results so we don't
25:39:11
중복이 없습니다. 다음 것도 마찬가지입니다.
have any duplicates the same thing for the next one
25:39:14
은색과 관련된 것입니다.
so the silver and it was for
25:39:17
첫 번째 이름을 확인해 보겠습니다.
the first name so let's go and check
25:39:20
첫 번째 이름을 실행해 보겠습니다. 결과가 없습니다.
the first name and run it as you can see there
25:39:23
결과가 없습니다. 문제가 없습니다.
is no results it is perfect we don't have any issues you
25:39:27
마지막 이름을 확인해 보겠습니다.
can of course go and check the last name and
25:39:31
이제 성별과 같은 지역 신원 열을 확인해 보겠습니다.
run it again we don't have any results over here and
25:39:34
완벽합니다. 은색 고객 정보를 확인해 보겠습니다.
now we can go and check those local identity columns like for example the gender let's go and execute it so as As you can see, we have that not available or the unknown male and female.
25:39:46
이제 모든 열을 살펴보겠습니다.
So perfect. And you can go and have a final look to the table to the silver customer info. Let's go and check that.
25:39:52
모든 것이 완벽해 보입니다.
So now we can have a look to all those columns.
25:39:55
우리가 추가한 메타데이터 정보입니다.
As you can see, everything looks perfect and you can see it is working this metadata
25:40:00
모든 레코드를 테이블에 삽입한 시간을 보여줍니다.
information that we have added to the table definition.
25:40:02
이 스크립트를 보면 다양한 데이터 변환을 수행했습니다.
Now it says when we have inserted all those records to the table, which is really amazing information to have a track and audit.
25:40:10
첫 번째는 이름과 성에 대한 것입니다.
Okay, so now by looking to this script, we have done different types of data transformations.
25:40:14
불필요한 공백을 제거했습니다.
The first one is with the first name and the last name. Here we have done trimming, removing unwanted spaces.
25:40:21
데이터 정화의 한 종류입니다.
This is one of the types of data cleansing. So we remove unnecessary spaces or unwanted characters to ensure data consistency.
25:40:29
다음 변환으로 넘어가겠습니다.
Now moving on to the next transformation we have this case win.
25:40:32
여기서 데이터 정규화 또는 표준화가 이루어졌습니다.
So what you have done here is data normalization or we call it sometimes data standardization.
25:40:38
결측값을 처리했습니다.
So this transformation is type of data cleansing where we can map coded values to meaningful user friendly description and we have done the same transformation as well to the gender.
25:40:49
널 대신 사용할 수 있는 값을 설정했습니다.
Another type of transformation that we have done as well in the same case win is that we have handled the missing values.
25:40:56
결측 데이터 처리는 데이터 정화의 한 종류입니다.
So instead of nulls we can have not available so
25:40:59
빈 값을 채우고 있습니다.
handling missing data is as well type of data cleansing where
25:41:02
기본값을 추가하고 있습니다.
we are filling the blanks by adding for example a
25:41:05
기본값을 설정할 수 있습니다.
default value so instead of having an empty string or
25:41:09
알 수 없는 값으로 설정할 수 있습니다.
a null we can have a default value like that not available or
25:41:12
알 수 없는 또 다른 데이터 유형과 우리가 수행한 변환
unknown another type of data and transformations that we have done in
25:41:15
이 스크립트에서는 중복을 제거했습니다. 중복 제거는 데이터 정화의 한 유형으로, 각 기본 키에 대해 하나의
this script is we have removed the duplicates so removing duplicates is as well type of data cleansing where we ensure only one
25:41:22
레코드를 식별하여 유지합니다.
record for each primary key by identifying
25:41:25
가장 관련성이 높은 역할만 유지합니다.
and retaining only the most relevant role
25:41:29
우리 데이터에 중복이 없도록 합니다. 중복을 제거하면서
to ensure there is no duplicates inside our data and
25:41:32
데이터 필터링을 수행하고 있습니다. 이것이 다양한 데이터 변환 유형입니다.
as we are removing the duplicates of course we are doing data
25:41:35
우리가 이 스크립트에서 수행한 모든
filtering so those are the different types of data transformations
25:41:38
이 스크립트에서 우리가 한 모든 것
that we have done in this script all
25:41:45
CRM의 동상 레이어에서 두 번째 테이블로 이동하면 제품이 있습니다.
right moving on to the second table in the bronze layer from the crm we have the product
25:41:49
정보와 물론 우리가 어떤 변환을 작성하기 전에
info and of course as usual before we start writing any transformations
25:41:52
데이터 품질 문제를 검색해야 합니다.
we have to search for data quality issues and
25:41:55
첫 번째로 시작하겠습니다. 기본 키를 확인해야 합니다.
we start with the first one we have to check the primary key so we have
25:41:58
이 안에 중복이나 null이 있는지 확인해야 합니다.
to check whether we have duplicates or nulls inside this
25:42:01
따라서 해야 할 일은 데이터를 기본 키로 그룹화하는 것입니다.
key so what you have to do we have to group up the data by the primary
25:42:05
또는 null이 있는지 확인합니다. 그러니 가서 실행해 봅시다.
key or check whether we have nulls so let's go and execute
25:42:08
보시다시피 모든 것이 안전합니다. 기본 키에 중복이나 null이 없습니다.
it so as you can see everything is safe we don't have duplicates or
25:42:11
이제 다음으로 이동하겠습니다. 여기 제품 키가 있습니다. 이 열에는 많은 정보가 있습니다. 이제 우리가 해야 할 일은 이 문자열을 두 개의 정보로 나누는 것입니다.
nulls in the primary key now moving on to the next one we have the product key here we have in this column a lot of informations so Now what we have to do is to go and split this string into two informations.
25:42:21
그래서 우리는 새로운 두 개의 열을 파생하고 있습니다. 이제 첫 번째는 카테고리 ID입니다.
So we are deriving new two columns. So now let's start with the first one is the category ID.
25:42:27
첫 다섯 자리는 실제로 카테고리 ID입니다.
The first five characters, they are actually the category ID.
25:42:31
그리고 우리는 부분 문자열 함수를 사용하여 문자열의 일부를 추출할 수 있습니다. 세 개의 인수가 필요합니다.
And we can go and use the substring function in order to extract part of a string. It needs three arguments.
25:42:37
첫 번째는 우리가 추출하고자 하는 열이 될 수 있습니다. 그리고 나서 추출할 위치를 정의해야 합니다.
The first one can be the column that we want to extract from. And then we have to define the position where to extract.
25:42:45
첫 번째 부분이 왼쪽에 있으므로 첫 번째 위치에서 시작합니다. 그리고 나서 길이를 지정해야 합니다.
And since the first part is on the left side, we're going to start from the first position. And then we have to specify the length.
25:42:51
그래서 몇 개의 문자를 추출하고 싶습니까? 우리는 다섯 개의 문자가 필요합니다. 그래서 하나, 둘, 셋, 넷, 다섯.
So how many characters we want to extract? We need five characters. So one, two, three, four, five.
25:42:56
그래서 카테고리 ID에 대한 것은 여기까지입니다. 카테고리 ID. 이제 가서 실행해 봅시다.
So that's it for the category ID. Category ID. Let's go and execute it.
25:43:02
이제 보시다시피 카테고리 ID라는 새 열이 생겼습니다. 그리고 문자열의 첫 번째 부분이 포함되어 있습니다.
Now, as you can see, we have a new column called the category ID. And it contains the first part of the string.
25:43:07
그리고 다른 소스 시스템의 데이터베이스에도 카테고리 ID가 있습니다.
And in our database from the other source system, we have as well the category ID.
25:43:12
이제 우리는 확인하러 가서 우리가
now we can go and double check just in order to make sure that we
25:43:15
데이터를 함께 조인할 수 있으므로 ID를 확인하러 가겠습니다.
can join data together so we're going to go and check the id
25:43:19
프롬프트 테이블 ERP에서
from the prompts table erp
25:43:22
카테고리에서 가져올 수 있습니다.
and this can be from the category so in
25:43:25
이 테이블에는 카테고리 ID가 있으며, 당신은
this table we have the category ids and you can
25:43:28
여기에서 카테고리의 ID를 볼 수 있습니다.
see over here those are the ids of the category and
25:43:31
코드 레이어에서 이 두 테이블을 조인해야 하지만
in the code layer we have to go and join those two tables but
25:43:35
여기에는 카테고리와 서브카테고리 사이에 언더스코어가 있습니다.
here we still have an issue we have here an underscore between
25:43:38
우리 테이블에는 실제로 마이너스가 있으므로
the category and the subcategory but in our
25:43:41
이를 언더스코어로 교체해야 일치하는 정보를 얻을 수 있습니다.
table we have actually a minus so we have to
25:43:44
이 두 테이블 간의 일치하는 정보를 위해
replace that with an underscore in order to have matching informations
25:43:48
이 두 테이블을 조인할 수 없게 됩니다.
between those two tables otherwise we will not be able to join the
25:43:51
우리는 함수 교체를 사용할 것이며
tables so we're going to use the function replace and
25:43:55
당신이 교체하는 것은 마이너스를 언더스코어로 교체하는 것입니다.
what you are replacing we are replacing the minus with an underscore something like this
25:44:01
이제 실행하면 언더스코어를 얻을 수 있습니다.
and if you go now and execute it we will get an underscore
25:44:04
다른 테이블과 정확히 같으며, 모든 것이 일치하는지 확인할 수 있습니다.
exactly like the other table and of course we can go and check whether everything is matching by having very simple query where we say
25:44:12
이 새로운 정보는
this new information not in
25:44:15
우리는 카테고리 ID를 찾으려고 합니다.
and then we have this nice sub query so
25:44:18
두 번째 테이블에 없는
we are trying to find any category id that is not
25:44:22
지금 실행해 보겠습니다.
available in the second table so let's go and execute
25:44:25
일치하지 않는 카테고리가 하나만 있습니다.
it now as you can see we have only one category that is not matching
25:44:28
이 테이블에서 찾을 수 없습니다.
we are not finding it in this table which is may be correct
25:44:32
조금 더 크게 만들어 보겠습니다.
so if you go over here you will not find this category
25:44:35
이 테이블에서 하나의 카테고리를 찾을 수 없습니다.
i just make it a little bit bigger so we are not finding this
25:44:38
이 표에서 하나의 범주를 만들었습니다.
one category from this table which is fine so our
25:44:41
체크가 괜찮으니 첫 번째 부분이 완료되었습니다.
check is okay okay so that's we have the first part now we
25:44:45
두 번째 부분을 추출해야 합니다.
have to go and extract the second part and we're going to do the same thing
25:44:48
위치 번호 7에서 시작합니다.
so we're going to use the substring and the three argument the product key but this time we will not start cutting from the first position we have to be in the middle so one two, three, four, five, six, seven.
25:44:59
길이를 정의해야 합니다.
so we start from the position number 7
25:45:02
추출할 문자의 길이를 정의해야 합니다.
and now we have to define the length how many characters to
25:45:06
제품 키의 길이가 다릅니다.
be extracted but if you look over here you can see that we have
25:45:09
고정되어 있지 않아서 우리는
different length of the product keys it is
25:45:12
여기서 숫자를 지정할 수 없습니다.
not fixed like the category id so we cannot go and
25:45:15
이를 위해 트릭이 있습니다.
here specify a number we have to make something dynamic and there
25:45:18
전체 열의 길이를 사용할 수 있습니다.
is a trick in order to do that we can go and use the length of
25:45:21
충분한 문자를 추출할 수 있습니다.
the whole column with that we make sure that we are all
25:45:25
정보를 잃지 않도록 동적으로 만들 것입니다.
is getting enough characters to be extracted and we
25:45:28
고정 길이가 아닙니다.
will not be losing any information so we will make it dynamic
25:45:31
제품 키가 있습니다.
like this we will not have it as a fixed length and
25:45:34
이제 두 번째 부분을 추출하고 있습니다.
with that we have the products key so let's
25:45:37
판매 세부정보와 조인하기 위해 필요합니다.
go and execute it as you can see we are now extracting the second part from this string now why we need the product key we need it in order to join it with another table called
25:45:49
이 열 이름을 확인해 보겠습니다.
sales details so let's go and check the sales details
25:45:52
sls 제품 키입니다.
so let me just check that column name this
25:45:55
브론즈 CRM 판매입니다.
sls product key so from
25:45:59
브론즈 CRM 판매
bronze crm sales
25:46:03
여기 데이터를 확인하러 가자
let's go and check the data over here and it
25:46:06
아주 멋져 보이므로 사실 우리는 그 정보를 함께 결합할 수 있지만 물론 우리는 그것을 확인할 수 있습니다. 그래서 우리는 어디에 있는지 말할 것이고, 새로운 열을 가져와서 말할 것입니다.
looks wonderful so actually we can go and join those informations together but of course we can go and check that so we're gonna say where and we're gonna take our new column and we're gonna say
25:46:16
서브 쿼리에는 포함되지 않도록
not in the sub query just to make
25:46:19
우리가 놓치는 것이 없도록 확인합시다. 그러니 실행해 봅시다.
sure that we are not missing anything so let's go and execute so
25:46:22
주문이 없는 제품이 많은 것 같습니다
it looks like we have a lot of products that don't
25:46:26
좋은 기분은 없지만
have any orders well i don't have a nice
25:46:29
이런 것을 시도해 보겠습니다
feelings about it let's go and try something like this
25:46:32
여기서 prd 키와 같은 값을 말합니다
one here and we say where sls
25:46:36
마지막 세 개를 잘라내겠습니다
prd key like this value over
25:46:39
이 테이블 안에서 검색하기 위해서입니다
here so i'll just cut the last three
25:46:42
이런 키가 없으니 두 번째를 잘라내겠습니다
just to search inside this table so we really
25:46:45
하나를 잘라내고 검색해 보겠습니다
don't have such a keys let me just cut the second
25:46:48
우리는 그것도 없으니 시작하는 모든 것
one so let's go and search for it
25:46:51
f 키로 시작하는 모든 것에 대해
we don't have it as well so anything that starts with
25:46:54
f 키로 시작하는 제품에 대한 주문이 없습니다
the f key we don't have any order with the product
25:46:58
f 키로 시작하는 곳에서 제거하겠습니다
where it starts with the f key so let's go and remove it
25:47:01
그렇지만 우리는 테이블을 조인할 수 있습니다
but still we are able to join the tables right so if
25:47:04
not in 대신 in이라고 말하겠습니다
i go and say in instead of not in so
25:47:07
그렇게 하면 모든 제품을 일치시킬 수 있습니다
with that you are able to match all those products so that
25:47:11
모든 것이 괜찮다는 의미입니다
means everything is fine actually it's just products that
25:47:14
주문이 없는 제품이므로 기쁩니다
don't have any orders so with that i'm happy
25:47:17
이 변환으로 다음으로 넘어갑니다
with this transformation now moving on to the next one
25:47:20
여기 제품 이름이 있습니다
we have here the name of the product we can go
25:47:23
불필요한 공백이 있는지 확인합니다
and check whether there is unwanted spaces so
25:47:26
품질 검사를 위해 같은 테이블을 사용합니다
let's go to our quality checks make sure to use the same table and we can use the product name and check whether
25:47:34
트리밍 후 불일치가 있는지 확인합니다
we find any unmatching after trimming so
25:47:37
잘하고 있습니다, 이 열은 안전합니다
let's go and do it well it looks really fine so we don't have
25:47:40
다음으로 넘어가겠습니다
to trim anything this column is safe now moving
25:47:43
비용을 확인해야 합니다
on to the next one we have the costs so here we have
25:47:46
숫자와 품질을 확인해야 합니다.
numbers and we have to check the quality of the numbers so
25:47:49
널(null)이나 음수인지 확인할 수 있습니다.
what you can do we can check whether we have nulls or negative
25:47:52
음수 비용이나 가격은 비현실적입니다.
numbers so negative costs or negative prices which is not realistic depending on the business of course so let's say in our business we don't have any
25:48:01
음수 비용이 없다고 가정해 보겠습니다.
negative costs so it's gonna be like this
25:48:04
0보다 작은지 확인해 보겠습니다.
let's go and check whether it's something less than zero or
25:48:08
비용이 널인지 확인해 보겠습니다.
whether we have costs that is null
25:48:12
정보를 잘 확인해 보겠습니다.
so let's go and check those informations well
25:48:15
널을 0으로 대체할 수 있습니다.
as you can see we don't have any negative values but we have nulls so
25:48:19
널을 0으로 대체하는 함수가 있습니다.
we can go and handle that by replacing the null with zero of course if the business allow that so in this case server in order to replace
25:48:26
널을 0으로 대체하라고 합니다.
the null with a zero we have a very nice function called is null so we are saying if it is null
25:48:34
매우 간단합니다.
then replace this value with a zero it
25:48:37
이름을 주고 실행해 보겠습니다.
is very simple like this and we give it a
25:48:40
더 이상 널이 없고 0이 있습니다.
name of course so let's go and execute it and as you can
25:48:43
계산에 더 좋습니다.
see we don't have any more nulls we have zero which is better
25:48:46
카디널리티가 낮습니다.
for the calculations if you are later doing any aggregate functions like the average now moving on to the next one we have the product line this is again abbreviation of something
25:48:56
모든 가능한 값을 확인해 보겠습니다.
the cardinality is low so let's go and check all possible values
25:48:59
이 열에서 사용할 것입니다.
inside this column so we're just going to use the
25:49:03
브랜드 라인을 사용할 것입니다.
distinct going to be brd line so
25:49:06
가능한 값은 널과 약어입니다.
let's go and execute it and as you can see the possible values are
25:49:09
전체 이름으로 대체해야 합니다.
null mrst and again those are abbreviations
25:49:13
친숙한 값으로 대체해야 합니다.
but in our data warehouse we have decided to give full nice names so we have to go and replace those codes those abbreviations
25:49:20
정보를 얻기 위해 전문가에게 물어봅니다.
with a friendly value and of course in order to get those informations i usually go and ask the
25:49:25
사례를 구축해 보겠습니다.
expert from the source system or an expert from the
25:49:29
대문자와 트림을 사용해 보겠습니다.
process so let's start building our case win and
25:49:32
모든 경우를 확인해 보겠습니다.
then let's use the upper and as well the trim just
25:49:36
모든 경우를 확인하기 위해
to make sure that we are having all the cases so
25:49:39
브랜드 라인이 동일합니다
the brd line is equal
25:49:42
첫 번째 값인 m부터 시작하겠습니다. 그러면 친숙한 값은 산이 될 것입니다
to so let's start with the first value the m then we will get the friendly value it's going to be mountain then to the next one so i will just copy and paste here
25:49:54
r이면 로드이고, let에 대한 또 다른 것입니다
if it is an r then it is rods and another one for let
25:50:00
여기서 우리가 가진 것은 mr입니다
me check what do we have here we have mr and then
25:50:04
s는 다른 셀을 나타냅니다
s the s stands for other cells
25:50:07
t는 투어링을 나타냅니다
and we have that t so let's go and get that
25:50:11
마지막에 우리는 else를 가지고 있습니다
t so the t stands for touring
25:50:14
알 수 없는 정보가 없으므로 다른 것은 필요하지 않습니다
we have at the end and else for
25:50:17
그게 전부입니다. 이전과 같이 이름을 붙이겠습니다
unknown not available so we don't need any else
25:50:20
제품 라인입니다. 이전 것을 제거합시다
so that's it and we're gonna name it as before so
25:50:23
실행해 보겠습니다. 여기에는 없습니다
product line so let's remove the old one and
25:50:27
더 이상 단축키와 약어가 없습니다
let's execute it and as you can see we don't have here
25:50:30
이제 전체 친숙한 값이 있지만 가겠습니다
anymore those shortcuts and the abbreviations
25:50:33
대문자 O처럼 보이니 더 멋져 보입니다
we have now full friendly value but i will go and
25:50:36
이제 보기 좋은 친숙한 값이 있습니다
have here like capital o it looks nicer so
25:50:40
이 경우에 대해 우리가 가진 친숙한 값이 있습니다
that we have nice friendly value now by looking to this case
25:50:43
하나의 값을 다른 값으로 매핑하고 있습니다
when as you can see it is always like we are mapping one value
25:50:46
시간이 지나면서 우리는 빠른 형태를 가지고 있습니다
to another value and we are repeating all time upper time our
25:50:49
단순 매핑일 경우 구문은
time and so on we have here a quick form in the case when
25:50:52
매우 간단합니다. case라고 말합니다
if it is just a simple mapping so the syntax
25:50:55
열을 평가하고 있습니다
is very simple we say case and then we have
25:50:59
여기서 우리는 그냥 equal 없이 when이라고 말합니다
the column so we are evaluating this value over
25:51:02
m이면 산으로 만듭니다
here and then we just say when without the equal
25:51:05
다음 것에도 동일하게 적용합니다
so if it is an m then make it mountain the same
25:51:09
다음 것에 대해 같은 방식으로
thing for the next one and so so with
25:51:12
함수를 한 번만 사용하고 반복할 필요가 없으므로
that we have the functions only once and we don't have to go and
25:51:15
값을 매핑하는 경우 복잡한 조건이 있다면
keep repeating the same function over and over and this one only
25:51:18
이렇게 할 수는 없지만 지금은 빠른 형식을 유지할 것입니다
if you are mapping values but if you have complex conditions you
25:51:21
사례를 더 보기 좋고 짧게 만들기 위해
cannot do it like this but for now i'm gonna stay with the quick form
25:51:24
같은 결과를 얻을 수 있습니다. 이제 다시
of the case when it looks nicer and shorter so let's go and
25:51:27
우리 테이블로 가서 마지막 두 열을 확인합시다
execute it we will get the same results okay so now back to
25:51:30
시작일과 종료일이 있습니다. 이는 구간을 정의하는 것과 같습니다
our table let's go to the last two columns we have the start and
25:51:34
시작과 종료가 있으므로 시작의 품질을 확인해 봅시다
end date so it's like defining an interval we
25:51:37
그리고 종료 날짜를 확인할 것입니다. 이제
have start and end so let's go and check the quality of the start
25:51:40
문제 테이블에서 모든 항목을 선택하겠습니다
and end dates we're gonna go and say select star from
25:51:43
문제 테이블로 가서
our problems table and now we're gonna go
25:51:47
이렇게 검색합니다. 종료 날짜를 찾고 있습니다
and search it like this we are searching for the end dates
25:51:50
시작보다 작은
that is smaller than the start
25:51:53
시작 날짜를 확인해 보겠습니다
so we are g start dates so
25:51:56
항상 종료 후에 있어야 하므로
let's go and query this so you can see the start
25:51:59
전혀 말이 안 되므로 이 두 날짜에 대한 데이터 문제가 있습니다
is always like after the end which makes no
25:52:02
이런 종류의 데이터 변환을 위해 제가 보통 하는 것은
sense at all so we have here data issue with those two dates
25:52:05
몇 가지 예를 가져와서 엑셀에 넣는 것입니다
so now for this kind of data transformations what i usually do
25:52:08
어떻게 수정할지 생각해 보겠습니다. 여기서
is i go and grab a few examples and put it in excel
25:52:11
두 개의 제품을 가져왔습니다. 이 제품과 저 제품
and try to think about how i'm gonna go and fix it so here i took
25:52:15
각각에 대해 세 개의 행이 있습니다
like two products this one and this one over here and
25:52:18
이런 상황이 있으므로 이제 어떻게 할 것인지
for that we have like three rows for each one of them and we have this
25:52:21
수정할 것입니다. 하나의 솔루션을 복사할 것입니다
situation over here so the question now how are we gonna go and
25:52:24
매우 간단하므로 시작 날짜를 바꾸겠습니다
fix it i will go and make like a copy of one solution where
25:52:27
우리는 매우 간단하다고 말할 것입니다. 시작 날짜를
we're gonna say it's very simple let's go and switch the start date with
25:52:30
종료 날짜로 바꿉니다. 그래서 종료 날짜를
the end date so if i go and grab the end
25:52:33
가져와서 시작에 두면 훨씬 더 보기 좋을 것입니다.
date and put it at the start things gonna
25:52:36
시작은 항상 종료보다 젊습니다.
look way nicer right so we have the start is always younger
25:52:40
하지만 친구들, 데이터는 이제 말이 안 됩니다.
than the end but my friends the data now makes no
25:52:43
2007년부터 시작한다고 말하고 2011년까지 끝난다고
sense because we say it starts from 2007 and
25:52:46
2011년에는 가격이 12였지만
ends by 2011 the price was 12 but
25:52:49
2008년과 2012년 사이에는 14가 있었는데, 이는 그리 좋지 않습니다. 예를 들어 2010년을 보면, 2010년에는 12였고 동시에 14였습니다.
between 2008 and 2012 we have 14 which is not really good because if you take for example the year 2010 For 2010 it was 12 and at the same time 14.
25:53:01
따라서 이 두 날짜 사이에 겹침이 있는 것은 정말 나쁩니다.
So it is really bad to have an overlapping between those two dates.
25:53:05
2007년부터 시작해서 11년까지 끝나야 하며, 12년 2월부터 시작해서 다른 것으로 끝나야 합니다.
It should start from 2007 and end with 11 and then start February from 12 and end with something else.
25:53:12
연도 간에 겹침이 없어야 합니다. 따라서 시작이 항상 끝보다 작아야 한다고 말하는 것만으로는 충분하지 않으며, 첫 번째 기록의 끝도
There should be no overlapping between years. So it's not enough to say the start should be always smaller than the ends but as well the end of the first history
25:53:23
다음 기록의 시작보다 젊어야 합니다. 이는 겹침이 없도록 하기 위한 규칙이기도 합니다.
should be younger than the start of the next records. This is as well a rule in order to have no overlapping.
25:53:29
이 기록은 시작이 없지만 이미 끝이 있어 그리 좋지 않습니다. 우리는 항상 시작이 있어야 합니다.
This one has no start but has already an end which is not really okay because we have always to have starts.
25:53:37
역사화의 각 새로운 기록은 시작이 있어야 합니다.
Each new record in historicalization has to have a start.
25:53:40
따라서 이 기록은 잘못되었고, 물론 끝 없이 시작이 있는 것은 괜찮습니다.
So for this record over here this is as well wrong and of course it is okay to have the start without an end.
25:53:47
따라서 이 시나리오에서는 괜찮습니다. 이는
So in this scenario it's fine because this indicates
25:53:50
현재 비용에 대한 정보입니다.
this is the current information about the costs so
25:53:53
다시 말해, 이 해결책은 전혀 작동하지 않으므로 이제
again this solution is not working at all so now for
25:53:56
우리가 할 수 있는 해결책은 완전히 무시하자는 것입니다.
the solution to what we can say let's go and ignore completely
25:54:00
종료 날짜를 무시하고 시작 날짜만 가져옵니다.
the end date and we take only the start dates
25:54:03
그래서 여기 붙여넣고 이제 시작 날짜를 따라
so let's go and paste it over here but now we go and rebuild
25:54:06
종료 날짜를 완전히 재구성합니다.
the end date completely from the start date following
25:54:09
우리가 정의한 규칙을 따르면서, 규칙은 종료
the rules that we have defined so the rule says the end
25:54:13
현재 기록의 날짜는 시작에서 온다고 말합니다.
of date of the current records comes from the start
25:54:16
다음 기록의 날짜입니다. 그래서 여기 이 종료 날짜가 있습니다.
date from the next record so here this end date
25:54:20
다음 레코드에서 이 값이 나옵니다.
comes from this value over here from the next record
25:54:23
그렇다면 우리는 다음 시작 날짜를 가져와서
so that means we take the next start date and
25:54:26
이전 레코드의 종료 날짜로 설정합니다.
put it at the end date for the previous records so with that
25:54:29
보시다시피 종료 날짜가 더 높습니다.
as you can see it is working the end date is higher
25:54:32
시작 날짜보다 더 높고 우리는
than the start dates and as well we are making sure
25:54:35
이 날짜가 다음 레코드와 겹치지 않도록 하고 있습니다.
this date is not overlapping with the next records but
25:54:38
더 좋게 만들기 위해 하루를 빼서
as well in order to make it way nicer we can subtract it with one so we can take the previous day like this so with that we we are making sure the end date is smaller than the next starts.
25:54:50
이 날짜를 이전 날짜로 설정할 수 있습니다.
And now for the next record, this one over here, the end date going to come from the next start date.
25:54:55
그래서 우리는 종료 날짜를 하루 줄이고
So we will take this one for a year and put it as an
25:54:58
이제 두 날짜를 비교하면
end date and subtract it with one so
25:55:02
여전히 시작 날짜보다 높습니다.
we will get the previous day so now if you compare those two
25:55:05
다음 레코드와 비교하면
you can see it's still higher than the start and if
25:55:08
여전히 다음 날짜보다 작습니다.
you compare it with the next record this one over here it
25:55:11
겹치지 않습니다.
is still smaller than the next one so there is no overlapping
25:55:14
마지막 레코드에 대해 정보를 가지고 있지 않으므로 null이 됩니다.
and now for the last record since we don't have here any informations it will be a null which is totally fine so as you can see i'm really happy
25:55:23
이 시나리오에 대해 매우 기쁩니다.
with this scenario over here of course you can go and validate this with
25:55:26
물론 이것을 검증할 수 있습니다.
an expert from the source system let's say i've done that and
25:55:29
전문가에게 확인을 받았습니다.
they approved it and now i can go and clean up the data using this
25:55:32
이제 데이터를 정리할 수 있습니다.
new logic so this is how i usually brainstorm about fixing
25:55:36
엑셀을 사용하여 복잡한 문제를 해결합니다.
and issues if i have like a complex stuff i go and use
25:55:39
이 예제를 사용하여 전문가와 논의합니다.
excel and then discuss it with the expert using this example it's way better than showing a database queries and so on it just makes things easier to explain and as well to discuss
25:55:49
이제 제가 보통 하는 방식입니다.
so now how i usually do it i usually go and make a focus
25:55:52
필요한 열에만 집중합니다.
on only the columns that i need and take only one two
25:55:55
논리를 구축하는 동안 시나리오를 설정합니다.
scenarios while i'm building the logic and once everything is
25:55:58
쿼리에 통합합니다.
ready i go and integrate it in the query so now i'm
25:56:01
이 열들만 그리고 이 제품들만 집중하고 있습니다
focusing only on these columns and only for these products
25:56:04
이제 SQL에서 우리의 논리를 구축해 보겠습니다. 특정 레코드에 있고 다른 레코드의 정보를 접근하고 싶다면, 두 가지 놀라운 윈도우 함수가 있습니다
so now let's go and build our logic now in sql if you are at specific record and you want to access another information from another records and for that we have two amazing window functions
25:56:15
이 시나리오에서는 리드와 래그가 있습니다. 다음 레코드에 접근하고 싶습니다
we have the lead and lag in this scenario we want to access
25:56:19
다음 레코드, 그래서 우리는 리드 함수를 사용해야 합니다
the next records that's why we have to go with the function leads
25:56:22
리드를 구축해 보겠습니다. 그럼 무엇이 필요할까요?
so let's go and build it lead and then what do we need we
25:56:25
시작 날짜의 리드가 필요합니다
need the lead of the start date
25:56:29
다음 레코드의 시작 날짜가 필요합니다
so we want the start date of the next records and
25:56:32
그런 다음 오버라고 말하고 데이터를 파티션해야 합니다
then we say over and we have to partition the
25:56:35
데이터는 윈도우가 오직 하나의 제품에 집중하게 될 것입니다
data so the window gonna be focusing on only
25:56:38
제품 키에 따라 데이터를 나누고 있습니다
one product which is the product key and not the product id
25:56:41
물론 데이터를 판매해야 하므로 정렬하고 있습니다
so we are dividing the data by product key and
25:56:45
시작 날짜에 따라 데이터를 정렬하고 있습니다
of course we have to go and sell the data so order by and we are
25:56:48
오름차순으로 가장 낮은 것부터 가장 높은 것까지
sorting the data by the start date and
25:56:52
또 다른 이름을 주고 싶습니다. 예를 들어
ascending so from the lowest to the highest and let's go
25:56:55
테스트라고 부르겠습니다. 데이터를 테스트하기 위해서
and give it another name so as let's say
25:56:58
실행해 보겠습니다. 여기서 뭔가 놓친 것 같습니다. 파티션이라고 합니다
test for example just to test the data so let's
25:57:01
다시 실행해 보겠습니다. 이제 다시 실행해 보겠습니다
go and execute and i think i missed something here it says partition
25:57:04
첫 번째 파티션의 결과를 확인해 보겠습니다. 시작은
by so let's go and execute again and now let's go and
25:57:07
2011년이고 끝은 2012년입니다
check the results for the first partition over here so the start
25:57:11
이 정보는 다음 레코드에서 왔습니다
is 2011 and the end is 2012 and
25:57:14
이 데이터는 이전 레코드로 이동되었습니다
this information came from the next record so this data
25:57:18
이 레코드에 대해서도 마찬가지입니다
is moved to the previous record over here and the same
25:57:21
다음 레코드에서 끝 날짜가 나옵니다
thing for this record so the end date comes
25:57:24
마지막 레코드는 null입니다
from the next record so our logic is working and
25:57:27
정말 멋져 보이지만 무엇이 빠졌을까요?
the last record over here is null because we are at the end of the window and there is no next data that's why we'll get null and this is perfect
25:57:34
물론 정말 멋져 보이지만 무엇이 부족한가요
of course so it looks really awesome but what is missing
25:57:37
우리는 이전 날짜를 가져와야 합니다
is we have to go and get the previous day and
25:57:40
우리는 매우 간단하게 마이너스 원을 사용하여 할 수 있습니다
we can do that very simply using minus one we are just subtracting
25:57:44
하루를 빼면 두 날짜가 겹치지 않습니다
one day so we have no overlapping between those two
25:57:47
두 날짜에 대해 같은 일이 발생하므로
dates and the same thing for those two dates so as you can see we have
25:57:50
완벽한 종료 날짜를 만들었습니다
just built a perfect end date which is way better than
25:57:53
우리가 소스 시스템에서 가져온 원래 데이터보다 훨씬 낫습니다
the original data that we got from the source system now let's take this one over here and put it inside our query so we don't need the
25:58:01
이것을 쿼리에 넣고
end date we need our new end date we'll
25:58:04
종료 날짜가 필요합니다
just remove that test and execute now it looks
25:58:08
테스트를 제거하고 실행하면 이제
perfect all right now we are not done yet with those two dates
25:58:11
완벽합니다 이제 우리는 두 날짜에 대해 아직 끝나지 않았습니다
actually we are saying all time dates because we don't
25:58:14
사실 우리는 항상 날짜를 말하고 있습니다
have here any informations about the time always zero
25:58:17
여기 시간에 대한 정보가 없으므로
so it makes no sense to have these informations inside
25:58:21
이 정보를 포함하는 것은 의미가 없습니다
our data so what we can do we can do a very simple cast
25:58:24
우리는 매우 간단한 캐스트를 할 수 있습니다
and we make this column as a date instead
25:58:27
이 열을 날짜로 만듭니다
of date time so this is for the first one and
25:58:30
첫 번째 것과 다음 것에 대해서도 날짜로
as well for the next one as date so let's try
25:58:33
그것을 시도해 보겠습니다
that out and as you can see it is nicer we don't have
25:58:37
더 나아졌습니다 시간 정보가 없습니다
the time informations of course we can tell the source systems
25:58:40
물론 소스 시스템에 대해 모든 문제를 말할 수 있습니다
about all those issues but since they don't provide the time
25:58:43
시간을 제공하지 않기 때문에 의미가 없습니다
it makes no sense to have date and time okay so it was
25:58:46
날짜와 시간이 필요 없습니다
a long run but we have now a cleaned product
25:58:49
우리는 이제 정리된 제품 정보를 가지고 있습니다
informations and this is way nicer than the original
25:58:52
원래보다 훨씬 낫습니다
product information that we got from the source crm so if you grab
25:58:55
소스 CRM에서 가져온 제품 정보입니다
the ddl of the server table you can see that we don't have a
25:58:59
카테고리 ID가 없으므로 제품 ID와 제품 키가 있습니다.
category id so we have product id and product key and
25:59:02
이 두 열의 데이터 유형을 변경했습니다.
as well those two columns we just changed the data type so it's
25:59:05
여기서 날짜 시간으로 변경했지만 날짜로 변경했습니다.
date time here but we have changed us to a date so
25:59:08
즉, ddl에 몇 가지 수정을 해야 합니다.
that means we have to go and do few modifications to the ddl
25:59:11
여기에서 카테고리 ID라고 말할 것입니다.
so what we're gonna do we're gonna go over here and say category id and i
25:59:15
시작과 끝을 위해 같은 데이터 유형을 사용할 것입니다.
will be using the same data type for the start and the end
25:59:18
이번에는 날짜이고 날짜 및 시간이 아닙니다.
this time it's gonna be date and not date and time so that's it for
25:59:21
이제 이를 실행하여 수리하겠습니다.
now let's go and execute it in order to repair
25:59:24
ddl과 이것은 실버 레이어에서 발생한 일입니다.
the ddl and this is what happened in the silver layer sometimes
25:59:28
메타데이터를 조정해야 합니다.
we have to adjust the metadata if the quality of
25:59:31
데이터 유형이 좋지 않거나 새로운 정보를 구축하고 있습니다.
the data types and so on is not good or we are building new
25:59:34
데이터는 제품 레이어와 매우 유사하지만 몇 가지 수정을 해야 합니다.
derived informations in order later to integrate the
25:59:37
이 쿼리의 결과를 실버 테이블에 삽입하겠습니다.
data so it will be like very close to the product layer but with few modifications so make sure to update your ddl scripts and now the next step is that we're gonna go and insert the data into the table.
25:59:48
이전에 했던 것처럼 실버에 삽입합니다.
And now the next we're going to go and insert the result of this query that is cleaning up the bronze table into the silver table.
25:59:55
그런 다음 내가 준비한 모든 열을 나열해야 합니다.
So as we've done it before, insert into silver that
26:00:00
그렇다면 우리는
and then we have to go and list all the columns i've
26:00:03
쿼리를 실행하여 삽입할 수 있습니다.
just prepared those columns so with that we can
26:00:06
데이터를 삽입했습니다.
go and now run our query in order to insert the
26:00:09
이제 품질을 확인하는 것이 매우 중요합니다.
data so now as you can see this quill did insert the data and the
26:00:12
실버 테이블의 품질을 확인합니다.
very important step is now to check the quality of the
26:00:15
실버로 전환하여 기본 키를 확인합니다.
silver table so we go back to our data quality checks and we go
26:00:18
문제가 없으며 예를 들어 확인할 수 있습니다.
switch to the silver so let's check the primary key
26:00:22
여기에서 트림도 문제가 없으며 이제
there is no issues and we can go and check for example
26:00:25
비용을 확인해 보겠습니다.
here the trims there is as well no issue and now
26:00:28
부정적이거나 null이 아니어야 합니다.
let's go and check the costs it should not be
26:00:31
부정적이거나 null이 아니어야 합니다. 완벽하군요, 갑시다.
negative or null which is perfect let's go
26:00:34
데이터 표준화를 확인해 봅시다. 보시다시피 그들은
and check the data standardizations as you can see they are
26:00:37
친숙하고 null이 없으며 이제 매우 흥미롭습니다.
friendly and we don't have any nulls and now very interesting
26:00:41
날짜의 순서를 확인해 봅시다. 그러니 갑시다.
the order of the dates so let's go and check that as
26:00:44
문제가 없다는 것을 알 수 있고 마지막으로
you can see we don't have any issues and finally what
26:00:48
나는 은색을 최종적으로 살펴보러 갑니다.
i do i go and have a final look to the silver
26:00:51
표를 보면 모든 것이 올바른 열에 정확히 삽입되었습니다.
table and as we can see everything is inserted correctly in the correct columns so all those columns
26:00:57
모든 열은 소스 시스템에서 가져온 것이며 마지막은 자동으로
comes from the source system and the last one is automatically
26:01:00
생성됩니다. ddl에서 우리가 로드했을 때를 나타냅니다.
generated from the ddl indicate when we loaded
26:01:03
이 표를 이제 앉아서 우리의 스크립트를 살펴봅시다. 무엇이
this table now let's sit back and have a look at our script what
26:01:07
여기서 데이터 변환의 다양한 유형입니다.
are the different types of data transformations that we have done here
26:01:10
예를 들어, 여기서 카테고리 ID와 제품 키입니다.
is for example over here the category id and the product key
26:01:13
우리는 새로운 열을 도출했습니다. 이는 기존 열의 계산이나 변환을 기반으로 새로운 열을 만드는 것입니다.
we have derived new columns so it is when we create a new column based on calculations or transformations of an existing one so sometimes we need columns only for analytics
26:01:24
그래서 우리는 매번 소스 시스템에 가서 생성해 달라고 요청할 수 없습니다.
and we cannot each time go to the source system and ask them to create
26:01:27
그 대신 우리는 필요한 열을 도출합니다.
it so instead of that we derive our own columns
26:01:30
분석을 위해 필요한 다른 변환이 있습니다.
that we need for the analytics another transformation we
26:01:33
여기서 null인 경우를 처리하고 있습니다.
have is that is null over here so we are handling here
26:01:37
누락된 정보가 있습니다. null 대신 0을 가질 수 있습니다.
missing information instead of null we can have a zero
26:01:40
또 하나의 변환이 있습니다. 제품에 대해
and one more transformation we have over here for the product
26:01:43
우리가 여기서 수행한 데이터 정규화입니다. 코드 값 대신 친숙한 값을 가집니다.
line we have done here data normalization instead of having a code value we have a friendly value and as well we have handled
26:01:50
누락된 데이터에 대해서도 처리했습니다. 예를 들어, 여기서
the missing data for example over here instead of having a
26:01:54
null 대신 사용할 수 없는 값을 가질 수 있습니다. 이제 다른 데이터로 넘어갑니다.
null we can have not available all right moving on to another data
26:01:57
변환을 수행했습니다. 데이터 유형 캐스팅입니다.
transformation we have done data type casting so
26:02:00
우리는 데이터 유형을 하나에서 다른 것으로 변환하고 있습니다.
we are converting the data type from one to another and
26:02:03
이것도 데이터 변환으로 간주됩니다. 이제 마지막으로 넘어갑니다.
this considered as well to be a data transformation and now moving on
26:02:06
마지막으로 우리가 하는 것은 데이터 유형 변환이지만, 더 중요한 것은
to the last one we are doing as well data type casting but what's
26:02:09
데이터 보강을 하고 있다는 것입니다. 이 유형의 변환은 데이터에 가치를 추가하는 것과 관련이 있습니다.
more important we are doing data enrichment this type of transformation it's all about adding value to your data so we are
26:02:17
우리 데이터 세트에 새로운 관련 데이터를 추가하고 있습니다. 그래서 이것이 다양한 데이터 변환의 유형입니다.
adding a new relevant data to our data sets so those are the different types of data transformations
26:02:23
우리가 이 테이블을 위해 수행한 것입니다. 알겠죠?
that we have done for this table okay
26:02:29
계속 진행합시다. 우리는 판매 세부 정보를 가지고 있으며, 이것이 마지막
so let's keep going we have the sales details and this is the last
26:02:32
CRM의 테이블입니다. 여기서 무엇을 가지고 있습니까? 주문 번호가 있습니다.
table in the crm so what do you have over here we have the order number and
26:02:35
이것은 문자열입니다. 물론 문제가 있는지 확인할 수 있습니다.
this is a string of course we can go and check whether we have an issue with
26:02:38
원하지 않는 공백을 확인할 수 있습니다. 그래서 우리는 검색할 수 있습니다.
the unwanted spaces so we can search whether we're
26:02:41
무언가를 찾을 수 있습니다. 그래서 우리는 트림과 무언가를 할 수 있습니다.
going to find something so we can say trim and something
26:02:45
이렇게 하고 실행해 봅시다. 그래서 우리는 원하지 않는 공백이 없다는 것을 볼 수 있습니다.
like this and let's go and executed so we can see that we don't have
26:02:48
이것은 우리가 이 열을 변환할 필요가 없다는 것을 의미합니다.
any unwanted spaces that means we don't have to transform this column
26:02:51
그래서 우리는 있는 그대로 두어도 됩니다. 이제 다음 두 열은
so we can leave it as it is now the next two columns they are
26:02:54
키와 ID와 같은 것입니다. 다른 것들과 연결하기 위해서입니다.
like keys and ids in order to connect it with the other
26:02:57
우리가 이전에 배운 대로, 우리는 제품 키를 사용하고 있습니다.
tables as we learned before we are using the product key in
26:03:01
제품 정보와 연결하기 위해 고객 ID를 고객의 고객 ID와 연결하고 있습니다.
order to connect it with the product informations and we
26:03:04
모든 것이 완벽하게 작동하는지 확인해야 합니다. 그래서 우리는 이 열의 무결성을 확인할 수 있습니다.
are connecting the customer id with the customer id from the customer
26:03:07
제품 키가 포함되어 있고, 그런 다음
info so that means we have to go and check whether everything is working perfectly so we can go and check the integrity of those columns where we say the
26:03:14
서브 쿼리를 만들고 이번에는 실버 레이어에서 작업할 수 있습니다.
product key nuts in and then we make a
26:03:17
그래서 우리는 실버에서 제품 키를 말할 수 있습니다.
sub query and this time we can work with the silver layer right
26:03:21
제품 정보에서. 그래서 이것을 쿼리해 봅시다.
so we can say the product key from silver
26:03:24
문제가 발생하지 않는 것을 볼 수 있습니다. 즉, 모든 제품 키가
dot product info so let's go and query this and as
26:03:27
판매 세부 정보에서 사용되고 연결될 수 있습니다.
you can see we are not getting any issue that means all the product keys
26:03:31
제품 정보와 연결될 수 있습니다. 동일한 것을 확인할 수 있습니다.
from the sales details can be used and connected
26:03:34
고객 ID의 무결성을 확인할 수 있습니다. 우리는 제품이 아니라 고객 정보를 사용할 수 있습니다.
with the product info the same thing we can go and check the integrity of
26:03:37
고객 ID와 이름을 사용할 수 있습니다. 그래서 그것을 쿼리해 봅시다.
the customer id and we can use not the products we can go to the customer info and the name was
26:03:43
cst id이므로 쿼리를 실행해 보겠습니다.
cst id so let's go and query that
26:03:46
여기에는 문제가 없으므로
and the same thing we don't have here any issues so that means we
26:03:49
고객 ID를 사용하여 판매를 연결할 수 있습니다.
can go and connect the sales with the customers using the customer id
26:03:52
변환할 필요가 없습니다.
and we don't have to do any transformations for it so
26:03:55
이제 세 가지 열이 정말 좋아 보입니다.
things looks really nice for those three columns now we come to
26:03:59
여기에서 도전적인 부분은 날짜입니다.
the challenging one we have here the dates now
26:04:02
이 날짜는 실제 날짜가 아니라 정수입니다.
those dates are not actual dates they are integer so those
26:04:05
숫자이므로 이렇게 두고 싶지 않습니다.
are numbers and we don't want to have it like this we
26:04:08
데이터 유형을 정수에서
would like to clean that up we have to change the data type from integer
26:04:11
날짜로 변경해야 합니다.
to a date now if you want to convert an integer to
26:04:14
정수를 날짜로 변환하려면
a date we have to be careful with the values that we have inside
26:04:18
각 열의 값을 주의해야 합니다.
each of those columns so now let's check the quality for example of
26:04:21
주문 날짜가 0보다 작은 경우
the order date let's say where order date is
26:04:24
부정적인 값이 없으므로 좋습니다.
less than zero for example something negative well we don't have any negative values which is good let's go and check whether we have any zeros well this is bad so we have here a lot of zeros now what we can do we can replace
26:04:36
정보를 null로 바꿀 수 있습니다.
those informations with a null. You can use of course the null if function like this.
26:04:40
null if 함수를 사용할 수 있습니다.
We can say null if and if it is zero, then make it null. So let's execute it.
26:04:46
이제 이 정수는 연도 정보를 포함하고 있습니다.
And as you can see now, all those informations are null. Now let's go and check again the data.
26:04:50
여기에서 하나, 둘, 셋, 넷, 다섯이 필요합니다.
So now this integer has the years information at the start and then the months and then the day.
26:04:56
각 숫자의 길이는 h여야 합니다.
So here we have to have like one, two, three, four, five.
26:04:59
길이가 8보다 작거나 크면
So the length of each number should be h
26:05:02
문제가 발생합니다.
and if the length is less than eight or higher than eight then
26:05:05
길이 판매 주문이 같지 않으면
we have an issue let's go and check that so we're gonna say or
26:05:08
h와 같지 않다는 의미입니다.
length sales order is not equal
26:05:11
이제 실행해 보겠습니다.
to h that means less or higher let's
26:05:14
여기에서 결과를 확인해 보겠습니다.
go and execute it now let's go and check the results over here and
26:05:18
그 두 정보는 날짜처럼 보이지 않으므로
those two informations they don't look like dates so
26:05:21
이 정보로부터 실제 날짜를 만들 수 없습니다
we cannot go and make from these information's a real
26:05:24
그들은 단지 나쁜 데이터 품질일 뿐이며 물론
date they are just bad data quality and of course you can go and
26:05:27
날짜의 경계를 확인해야 합니다 예를 들어
check the boundaries of a date like for example it
26:05:30
예를 들어 2050년의 금액보다 높지 않아야 합니다
should not be higher than for example let's go and get this
26:05:33
그 날짜이므로 실행해 보겠습니다 그리고 그 정보를 제거하면
value 2050 of the money for the month and
26:05:36
확실히 하기 위해서입니다 그래서 우리는 날짜가
the date so let's go and execute it and if we just remove those informations
26:05:39
당신의 비즈니스에서 가지고 있는 경계 밖에 있지 않도록
just to make sure so we don't have any dates that is
26:05:42
비즈니스가 시작된 시점에 따라 다르지 않도록 해야 합니다
outside of the boundaries that you have in your business or you go for example and say the boundary should be not
26:05:49
비즈니스가 시작된 시점에 따라 다르지 않도록 해야 합니다
less than depend when your business started maybe something like
26:05:52
이 값들은 null보다 작기 때문에 얻고 있습니다
this we are getting of course those values because they are less
26:05:55
이 값들은 null보다 작기 때문에 얻고 있습니다
than in null but if you have values around this date you
26:05:58
쿼리에서 그것을 얻을 수 있으므로 나머지를 추가할 수 있습니다
will get it as well in the query so we can go and add the rest
26:06:01
모든 이러한 검사는 열을 검증하는 것입니다
so all those checks like validate the column
26:06:04
날짜 정보를 가진 열이 있고 데이터 유형이
that has date informations and it has the data type
26:06:07
정수입니다 그래서 여기서 어떤 문제가 있는지
integer so again what are the issues over here we have zeros and sometimes we have like strange numbers that cannot be converted to a date so
26:06:16
쿼리에서 그것을 수정해 보겠습니다 그래서
let's go and fix that in our query so we can say case when
26:06:19
판매 주문의 주문 날짜가
the sales order the order date is equal to
26:06:22
0이거나 주문 날짜가
zero or of the order date is not
26:06:25
8과 같지 않으면 null입니다 그러므로 우리는 원하지 않습니다
equal to eight then null right we don't want
26:06:29
그 값들을 처리하고 싶지 않습니다 그들은 잘못된 값입니다
to deal with those values they are just wrong and they are not real
26:06:32
그 값들을 처리하고 싶지 않습니다 그들은 잘못된 값입니다
dates otherwise we say else it's gonna be the order
26:06:35
이것을 정수로 원하지 않으므로 어떻게 할 수 있을까요
date now what you're gonna do we're gonna go and convert this to a
26:06:38
정수에서 날짜로 변환할 수 없습니다
date we don't want this as an integer so how we can do that we can go and cast it first to a varchar because we cannot
26:06:46
정수에서 날짜로 변환해야 합니다
cast from integer to date in sql server first
26:06:49
문자열로 변환한 후
you have to convert it to a varchar and then from varchar you
26:06:52
날짜로 변환합니다. 이렇게 SQL 서버에서
go to a date well this is how we do it in sql server so
26:06:56
정수를 변환하는 방법입니다.
we cast this first to a varchar and then we cast it to a date like this that's it so we have end and we are using the same column name
26:07:06
날짜로 변환하는 방법입니다.
so this is how we transform an integer to
26:07:09
현재 날짜는 실제 날짜입니다.
a date so let's go and query this and as you can see the order
26:07:12
숫자가 아닙니다. 이제 이전 열을 제거할 수 있습니다.
date now is a real date it is not a
26:07:15
배송 날짜에 대해 동일한 작업을 수행해야 합니다.
number so we can go and get rid of that old column now we have to go and do the same stuff for the shipping date so we can go over here and replace
26:07:23
배송 날짜로 모든 것을 교체합시다.
everything with the shipping date and let's
26:07:26
쿼리를 실행해 봅시다. 배송 날짜는 완벽합니다.
go and query well as you can see the shipping date is perfect we don't have
26:07:29
이 열에 문제는 없지만, 주문 날짜에서 많은 문제를 발견했습니다.
any issue with this column but still i don't like that we found a lot of issues with the order date so what we're gonna do just in case this happens for the shipping
26:07:37
미래의 배송 날짜에 동일한 규칙을 적용할 것입니다.
date in the future i will go and apply the same rules to
26:07:40
배송 날짜를 이렇게 설정합시다.
the shipping dates oh let's take the shipping date like
26:07:45
지금 적용하고 싶지 않다면 항상
this and if you don't want to apply it now you have always
26:07:48
매일 실행되는 품질 검사를 구축해야 합니다.
to build like quality checks that runs every day in
26:07:51
문제를 감지하기 위해
order to detect those issues and once you detect it
26:07:54
변환을 수행할 수 있습니다. 배송 날짜에 대해
then you can go and do the transformations but for now i'm gonna apply
26:07:57
즉시 적용할 것입니다. 이제 마감일로 가서
it right away so that is for the shipping date now we go to the due date and we will do the same test let's go and execute it
26:08:05
동일한 규칙을 적용할 것입니다.
and as well it is perfect so still i'm
26:08:08
쿼리에서 마감일을 모두 가져옵시다.
gonna apply the same rules so let's get the due date everywhere
26:08:12
여기에서 누락된 것이 없는지 확인하세요.
here in the query just make sure you don't miss anything here
26:08:15
이제 실행합시다. 완벽합니다.
so let's go and execute now perfect
26:08:18
주문 날짜, 배송 날짜, 마감일이 있습니다.
as you can see we have the order date shipping date and due dates and
26:08:21
모두 날짜이며 잘못된 데이터가 없습니다.
all of them are date and don't have any wrong data inside
26:08:24
이 열에 대해 추가 검사를 할 수 있습니다.
those columns now still there is one more check that we can do and
26:08:27
주문 날짜는 항상 더 작아야 합니다.
if that's the order date should be always smaller
26:08:30
배송 날짜나 기한보다 항상 작아야 합니다.
than the shipping date or the due date because it makes no
26:08:34
주문 없이 물건을 배송하는 것은 말이 안 되죠.
sense right if you are delivering an item without an order
26:08:37
먼저 주문이 발생한 후에 배송을 해야 합니다.
so first the order should happen then we are shipping
26:08:40
그 날짜들 사이에 순서가 있어야 합니다.
the items so there is like an order of those dates and we can
26:08:43
주문 날짜가 더 높다고 말할 수 있는 곳입니다.
go and check that so we are checking now for invalid date orders
26:08:46
배송 날짜보다 높거나 주문 날짜를 찾고 있습니다.
where we can say the order date is higher
26:08:49
주문 날짜가 더 높은 주문을 찾고 있습니다.
than the shipping date or we are searching
26:08:52
기한보다 높아야 하므로 이렇게 할 수 있습니다.
as well for an order where the order date
26:08:55
기한이므로 잘 확인해 보자구요.
is higher than the due date so we can have it like this
26:08:58
데이터와 품질에서 그런 실수가 없어서 정말 좋습니다.
due date so let's go and check well that's
26:09:01
주문 날짜는 항상 더 작아야 합니다.
really good we don't have such a mistake on the data and the quality
26:09:05
배송 날짜나 기한보다 항상 작아야 합니다.
looks good so the order date is always smaller
26:09:08
변환이나 정리를 할 필요가 없습니다.
than the shipping date or the due dates so we don't have
26:09:11
마지막 세 열로 넘어가겠습니다.
to do any transformations or cleanup okay friends now moving
26:09:14
판매 수량과 가격이 서로 연결되어 있습니다.
on to the last three columns we have the sales quantity
26:09:17
판매는 수량과 가격을 곱한 값과 같아야 합니다.
and the price all those informations are connected to each
26:09:20
판매 수량과 가격 정보는 양수여야 합니다.
other's so we have a business rule or calculation it says the sales must be equal to quantity multiplied by the price and all
26:09:28
음수나 제로는 허용되지 않습니다.
sales quantity and price informations must be positive
26:09:31
널도 허용되지 않습니다.
numbers so it's not allowed to be negative zero
26:09:34
데이터 일관성을 확인해야 합니다.
or a null so those are the business rules and we have to check
26:09:38
모든 정보가 우리의 규칙을 따릅니다.
the data consistency in our table does all
26:09:41
먼저 우리의 규칙으로 시작하겠습니다.
those three informations following our rules so we're
26:09:44
판매가 수량과 같지 않다면.
gonna start first with our rule right so we're gonna say if
26:09:47
판매는 수량과 같지 않습니다.
the sales is not equal to quantity
26:09:50
가격과 곱해져서 결과가 우리의 기대와 일치하지 않는 곳을 찾고 있으며, 다른 것들도 확인할 수 있습니다.
multiplied by the price so we are are searching where the result is not matching our expectation and as well we can go and check other stuff
26:09:59
예를 들어 매출이 null이거나 수량이 null일 수 있습니다.
like the nulls so for example we can say or sales is null or quantity is null and the last one for the price
26:10:10
그리고 우리는 그들이 음수인지 또는 0인지 확인할 수 있습니다.
and as well we can go and check whether they are negative numbers or zero so we can go over here and say less or equal to zero and apply it for the other columns as well so with that we are checking
26:10:22
계산을 확인하고 null이 있는지 확인하고 있습니다.
the calculation and as well we are checking whether we have null
26:10:25
0 또는 음수입니다. 정보를 확인해 보겠습니다.
zero or negative numbers let's go and check our informations
26:10:28
여기서 고유한 값을 가져올 것입니다.
i'm gonna have here distinct so let's go and
26:10:31
쿼리할 것이고, 물론 여기 나쁜 데이터가 있습니다.
query it and of course we have here bad data but
26:10:35
판매 수량으로 데이터를 판매할 수 있습니다.
we can go and sell the data by the sales quantity
26:10:38
가격을 보고, 판매에서 null과 음수가 있습니다.
and the price so let's do it now by looking to the data we can see in the sales we have nulls we have negative
26:10:46
모든 나쁜 조합이 있습니다.
numbers and zeros so we have all bad combinations
26:10:49
여기 가격은 50이고 수량은 1이지만 매출은
and as well we have here bad calculations so as you can see
26:10:52
2인데, 이는 올바르지 않으며 잘못된 계산이 있습니다.
the price here is 50 the quantity is one but the sales
26:10:55
여기서는 10이 있어야 하고 여기서는 9여야 합니다.
is two which is not correct and here we have as well wrong calculations
26:10:59
잘못된 가격이며 수량을 보면
here we have to have a 10 and here nine or maybe the price is
26:11:02
null이 없고 0이나 음수가 없으므로 수량이 매출보다 나아 보입니다.
wrong and by looking to the quantity now you can see
26:11:05
가격에는 null과 음수가 있습니다.
we don't have any nulls we don't have any zeros or negative numbers so the quantity looks better than the sales and if you look to the
26:11:12
그래서 우리는 0이 없습니다.
prices we have nulls we have negatives and
26:11:15
판매와 가격이 잘못되었습니다.
yeah we don't have zeros so that means the quality of the
26:11:18
계산이 작동하지 않습니다.
sales and the price is wrong the calculation is not working
26:11:21
이 시나리오가 있습니다. 여기서 어떻게 할지
and we have these scenarios now of course how i do it here i
26:11:24
모든 것을 혼자서 변환하려고 하지 않습니다.
don't go and try now to transform everything on my own i
26:11:27
전문가와 이야기합니다.
usually go and talk to an expert maybe someone from the
26:11:30
비즈니스 또는 소스 시스템의 전문가와 이야기합니다.
business or from the source system and i show those scenarios and discuss and usually there is like two answers either they're gonna tell me you know
26:11:37
내 소스에서 수정할 것이므로 거기에서 살아야 합니다.
what i will fix it in my source so i have to live with it there
26:11:40
입고되는 나쁜 데이터입니다.
is incoming bad data and the bad data can be presented
26:11:43
창고에서 소스 시스템이 문제를 해결할 때까지.
in the warehouse until the source system clean up those
26:11:47
문제와 다른 답변이 있을 수 있습니다. 우리는
issues and the other answer you might get you know what we don't have
26:11:50
예산이 없고 데이터가 정말 오래되었습니다.
the budget and those data are really old and we are not going
26:11:53
그대로 두거나 데이터 품질을 개선하자고 말해야 합니다.
to do anything so here you have to decide either you leave it as
26:11:56
이 문제를 해결하기 위해 전문가에게 요청해야 합니다.
it is or you say you know what let's go and improve the quality of the data but here you have to ask for the experts to
26:12:02
규칙에 따라 다릅니다. 다른 규칙은 다른 변환을 만듭니다.
support you solving these issues because it really depends
26:12:05
이제 다음 규칙이 있다고 가정해 봅시다.
on the rules different rules makes different transformations
26:12:08
판매 및 형성이 null이거나 음수 또는 0이면
so now let's say that we have the following rules if the
26:12:12
품질을 곱하여 계산 공식을 사용합니다.
sales and formations are null or negative or zero then
26:12:15
가격과 품질을 곱하여 계산합니다.
use the calculation the formula by multiplying the quality
26:12:18
예를 들어, 여기서 null 또는 0이면 판매 및 수량에서 계산합니다.
with the price and now if the prices are wrong for
26:12:21
가격이 음수인 경우, 예를 들어
example we have here null or zero then go and calculate it from the sales and the quantity and if you have a price that is a minus like minus
26:12:30
21의 음수인 경우, 21로 변환해야 합니다.
21 a negative number then you have to go and convert
26:12:33
계산 없이 21로 변환해야 합니다.
it to a 21 so from a negative to positive
26:12:36
이제 규칙에 따라 변환을 구축할 것입니다.
without any calculations so those are the rules and now
26:12:39
단계별로 진행하겠습니다. 새로운 판매를 구축할 것입니다.
we're gonna go and build the transformations based on those rules
26:12:42
규칙이 판매가 null인 경우입니다.
so let's do it step by step i will go over here and we're gonna start building the new sales so what is the rule says case when of course as usual if the sales
26:12:53
음수이거나 0인 경우입니다.
is null or let's say the sales is
26:12:56
판매 정보가 있지만 따르지 않습니다.
negative number or equal to zero or another scenario
26:12:59
계산을 따르지 않으므로 잘못된 정보입니다.
we have a sales information but it is not following
26:13:02
판매가 수량과 같지 않다고 말할 것입니다.
the calculation so we have a wrong information in the sales so
26:13:06
가격으로 곱해지지 않습니다.
we're going to say the sales is not equal to the quantity
26:13:09
물론 가격을 이렇게 두지 않을 것입니다.
multiplied by the price but of
26:13:13
절대값 함수로 모든 것을 변환할 것입니다.
course we will not leave the price like this by using the function abs
26:13:16
음수를 양수로 변환해야 합니다.
the absolute is going to go and convert everything from
26:13:19
계산을 사용해야 합니다.
negative to positive then what we have to do is to go
26:13:23
계산을 사용해야 하므로
and use the calculation so it's going to be
26:13:26
수량에 가격을 곱한 것이므로
the quantity multiplied by the price so
26:13:29
우리는 소스 시스템에서 온 값을 사용하지 않는다는 의미입니다
that means we are not using the value that's come from the source system
26:13:32
우리는 지금 다시 계산하고 있다고 가정합시다
we are recalculating it now let's say the sales
26:13:35
판매가 올바르고 그런 시나리오 중 하나가 아니라고 가정합시다
is correct and not one of those scenarios so we can say else
26:13:39
우리는 소스에서 오는 판매를 그대로 사용할 것입니다
we will go with the sales as it is that comes from the
26:13:42
소스가 올바르기 때문에 정말 좋습니다
source because it is correct it's really nice let's go and say
26:13:45
여기에서 이전 값을 구식으로 이름을 바꾸겠습니다
an end and give it the same name i will go i rename the
26:13:48
여기 오래된 값으로서의 오래된 것
old one here as an old value
26:13:51
가격에 대해서도 마찬가지로 수량은 그렇지 않을 것입니다
and the same for the price the quantity will not
26:13:55
그것을 건드리지 마세요. 그것은 정확하니까 이렇게 하고 이제
touch it because it is correct so like this and now
26:13:58
가격을 변환하러 갑시다. 다시 말해
let's go and transform the prices so again as
26:14:01
보통처럼 케이스를 사용할 것입니다. 그러면 어떤 시나리오가 있나요?
usual we go with case when so what are the scenarios
26:14:04
가격이 null이거나
the price is null or
26:14:08
가격이 0보다 작거나 같으면
the price is less or equal to zero
26:14:11
그럼 우리가 할 것은 계산을 하는 것입니다.
then what we're gonna do we're gonna do the calculation so
26:14:14
판매량을 수량으로 나누는 것입니다.
it's it can be the sales divided by the quantity
26:14:17
판매 수량이지만 여기서는
the sls quantity but here we have
26:14:20
현재 0으로 나누지 않도록 해야 합니다.
to make sure that we are not dividing by zero currently we
26:14:23
현재 수량에 0이 없지만 미래에 0이 될 수도 있습니다.
don't have any zeros in the quantity but you don't know in the future you might get a
26:14:26
0이 되면 전체 코드가 중단될 것입니다. 그래서 해야 할 것은
zero and the whole code gonna break so what you have to do is to
26:14:29
가서 0이 있으면 그것을 null로 바꾸는 것입니다.
go and say if you get any zero replace
26:14:33
그래서 이제 만약 0이라면
it with a null so now if if it is zero
26:14:36
null로 만드세요. 이제 가격이 null이 아니고 가격이 음수가 아니거나 0보다 크면 모든 것이
then make it null so that's it now if the price is not null and the price is not negative or equal to zero then everything is
26:14:43
괜찮습니다. 그래서 이제 else가 있을 것입니다.
fine and that's why we're gonna have now the else it's gonna be
26:14:46
출처 시스템에서 가격이 그대로입니다.
the price as it is from the source system so
26:14:49
그래서 가격이 끝났다고 말할 것입니다.
that's it we're gonna say ends as price so i'm
26:14:52
이것은 이전 정보이고 이것은 새로운 변환된 정리된 정보입니다.
totally happy with that let's go and execute it and check of course so
26:14:56
여기에는 이전에 null이 있었지만 이제는
those are the old informations and those are the new transformed cleaned
26:14:59
두 개가 있습니다. 그래서 두 개를 하나와 곱하면 두 개가 됩니다.
up informations so here previously we have a null but now we
26:15:03
여기서 매출이 올바릅니다. 이제 다음으로 넘어가겠습니다.
have two so two multiply with one we are getting two
26:15:06
여기서 이전 매출은 0이지만 곱하면
so the sales is here correct now moving on to the next one we have in the sales 40 but the price is two so two multiplied with one we should get two so the new sales is correct it is two and not 40.
26:15:18
수량과 네 개를 곱하면 네 개가 됩니다.
now to the next one over here the old sales is zero but if you go and multiply
26:15:22
여기서는 올바르지 않으므로 새로운 매출은
the four with the quantity you will get four so the sales
26:15:25
네 개입니다. 그래서 마이너스를 가져가겠습니다.
here is not correct that's why in the new sales we have it correct as
26:15:28
이 경우 마이너스가 올바르지 않으므로 가격을 가져옵니다.
a four and let's go and get a minus so in this case we have
26:15:31
하나와 곱하면 여기서 아홉이 나와야 합니다.
a minus which is not correct so we are getting the price
26:15:35
여기서 매출이 올바릅니다. 이제 시나리오를 가져가겠습니다.
multiplied with one we should get here a nine and this
26:15:38
가격이 null인 경우입니다.
sales here is correct now let's go and get a scenario
26:15:41
여기서는 가격이 없지만 매출에서 계산했습니다.
where the price is null like this here so
26:15:44
수량과 함께 10을 2로 나누면 5가 됩니다.
we don't have here price but we calculated from the sales
26:15:47
그래서 새로운 가격이 더 좋습니다.
and the quantity so we divided the 10 by two and we have five
26:15:50
마이너스도 마찬가지입니다.
so the new price is better and the same thing for the
26:15:53
여기서 마이너스 21이 있습니다.
minuses so we have here minus 21 and in the output
26:15:57
우리는 21이 올바르므로 지금은
we have 21 which is correct so for now i don't
26:16:00
데이터가 잘못된 시나리오를 보지 못했습니다.
see any scenario where the data is wrong so everything looks
26:16:03
이전보다 더 나아졌고, 전문가의 비즈니스 규칙을 적용했습니다.
better than before and with that we have applied the
26:16:06
데이터 웨어하우스의 데이터를 정리했습니다.
business rules from the experts and we have cleaned up
26:16:09
그래서 이제 우리가 할 일은 정보를 복사하여 쿼리에 통합하는 것입니다.
the data in the data warehouse and this is way better than before because we are presenting now better data for analysis and reporting but it is challenging and you have exactly to understand the business.
26:16:20
그래서 매출 대신 새로운 계산을 가져오고 가격 대신 올바른 계산을 가져올 것입니다.
So now what we're going to do, we're going to go and copy those informations and integrate it in our query.
26:16:25
그래서 이제 우리가 할 일은 정보를 복사해서 쿼리에 통합하는 것입니다.
So instead of sales, we're going to get our new calculation and instead of the price, we will get our correct calculation.
26:16:33
그리고 여기서 끝이 빠졌습니다. 전체를 다시 실행해 봅시다.
And here I'm missing the end. Let's go and run the whole thing again.
26:16:37
그래서 이제 우리는 정리된 판매 수량과 가격을 가지고 있으며, 이는 우리의 비즈니스 규칙을 따릅니다.
So with that, we have as well now cleaned sales quantity and price and it is following our business rules.
26:16:44
그래서 이제 우리는 판매 세부 정보를 정리하는 작업을 완료했습니다.
So with that, we are done cleaning up the sales details.
26:16:47
다음 단계는 판매 세부 정보에 삽입하는 것입니다.
the next step we're going to go and insert it to the sales details but
26:16:51
DDL을 다시 확인해야 하므로 이제 여러분이 해야 할 일은
we have to go and check again the ddl so now all what you
26:16:54
그 결과를 DDL과 비교하는 것입니다.
have to do is to compare those results with the ddl so
26:16:57
첫 번째는 주문 번호이며, 제품 키와 고객
the first one is the order number it's fine the product key the customer
26:17:00
ID가 있지만 여기서 문제가 있습니다. 모든 정보가 이제
id but here we have an issue all those informations now
26:17:03
날짜이고 정수가 아닙니다. 그래서 우리는 변경해야 합니다.
are date and not an integer so we have to go and change
26:17:06
데이터 유형을 변경하고, 그로 인해 이전보다 더 나은 데이터 유형을 가지게 됩니다. 그러면 판매 수량과 가격이 올바르니, 가서
the data type and with that we have better data type than before then the sales quantity price it is correct let's go and
26:17:14
테이블을 삭제하고 처음부터 다시 생성하세요. 잊지 마세요.
drop the table and create it from scratch again and don't forget
26:17:17
DDL 스크립트를 업데이트하는 것입니다. 그래서 이게 전부입니다.
to update your ddl script so that's it for this
26:17:20
이제 결과를 삽입하러 갑니다.
and we're gonna go now and insert the results into
26:17:23
우리의 실버 테이블 판매 세부 정보에 삽입해야 하며,
our silver table sales details and we have to go and
26:17:26
모든 열을 나열해야 합니다. 이미 열 목록을 준비했습니다.
list now all the columns i have already prepared the list of
26:17:29
모든 열을 나열해야 하며, 열의 올바른 순서를 확인하세요. 이제 데이터를 삽입하러 갑니다.
all the columns so make sure that you have the correct order of the columns so let's go now and insert the data and with that and with that we can see that the sql did insert data to our sales details
26:17:41
하지만 이제 매우 중요한 것은
but now very important is to check the health of the
26:17:44
실버 테이블의 상태를 확인하는 것입니다. 그래서 여기서 브론즈 대신
silver table so what you're gonna do instead here of bronze we're gonna go
26:17:47
실버로 전환할 것입니다. 여기서 확인해 봅시다.
and switch it to silver so let's check over here
26:17:50
여기서 항상 주문이 배송보다 작습니다.
so here always the order is smaller than the shipping
26:17:53
그리고 마감일이 정말 좋습니다. 하지만 이제 저는
and the due date which is really nice but now i'm
26:17:56
계산에 매우 관심이 있습니다. 그래서 여기서 우리는 전환할 것입니다.
very interested on the calculations so here we're gonna switch
26:18:00
브론즈에서 실버로, 그리고 모든 것을 없애겠습니다.
it from bronze to silver and i'm gonna go and get rid of all
26:18:03
그 계산이 필요 없으니, 이제 문제가 있는지 확인해 봅시다.
those calculations because we don't need it this
26:18:06
이제 문제가 있는지 확인해 봅시다. 잘 됐습니다.
and now let's see whether we have an issue well perfect
26:18:10
우리 데이터는 비즈니스 규칙을 따르고 있으며, 널 값이 없습니다.
our data is following the business rules we don't have any nulls
26:18:13
부정적인 값과 제로가 있습니다. 이제 마지막 단계입니다.
negative values zeros now as usual the last step
26:18:16
최종 점검을 위해 마지막으로 살펴보겠습니다.
the final check we will just have a final look to
26:18:19
테이블에는 주문 번호, 제품 키, 고객 ID가 있습니다.
the table so we have the order number the product key the customer
26:18:22
이 세 가지 날짜와 판매 수량이 있습니다.
id those three dates we have the sales quantity
26:18:26
가격과 메타데이터 열이 있으며, 모든 것이 완벽합니다. 이제 코드에서 어떤 데이터 변환을 하고 있는지 살펴보겠습니다.
and the price and of course we have our metadata column everything is perfect so now by looking to our code what are the different types of data transformation that we are doing so on On those three columns, we are doing the following.
26:18:38
처음에는 유효하지 않은 데이터를 처리하고 있습니다. 이것도 변환의 일종입니다.
So at the start, we are handling invalid data. And this is as well type of transformation.
26:18:44
동시에 데이터 타입 캐스팅도 하고 있습니다. 더 올바른 데이터 타입으로 변경하고 있습니다.
And as well, at the same time, we are doing data type casting. So we are changing it to more correct data type.
26:18:50
여기에서 판매를 살펴보면, 누락된 데이터와 유효하지 않은 데이터를 처리하고 있습니다.
And if you are looking to the sales over here, then what you are doing over here is we are handling the missing data and as well the invalid data by deriving the column from already existing one.
26:19:02
가격에 대해서도 매우 유사합니다.
And it is as well very similar for the price.
26:19:05
여기에서 유효하지 않은 데이터를 특정 계산에서 파생하여 처리하고 있습니다.
we are handling as well the invalid data by deriving it from specific calculation over here so those are the different types of data transformations that you have done in this script
26:19:19
좋습니다. 이제 다음 단계로 넘어갑시다. 시스템에는
all right now let's keep moving to the next our system we have the
26:19:22
고객 az12가 있습니다. 여기에는 세 개의 열이 있으며, 먼저 ID부터 시작하겠습니다.
customer az12 so here we have like only three columns and let's start with the id first so again we have the customers
26:19:30
이 정보를 확인하면, 이 테이블을 CRM 테이블 고객 정보와 연결할 수 있습니다.
those informations and if you go and check again our model, you can see that we can connect this table with the CRM table customer info using the customer key.
26:19:39
따라서 이 두 테이블을 연결할 수 있도록 확인해야 합니다.
So that means we have to go and make sure that we can go and connect those two tables. So let's go and check the other table.
26:19:46
서버 레이어를 확인할 수 있습니다. 두 테이블을 쿼리해 보겠습니다.
We can go and check of course the server layer. So let's query it and we can query both of the tables.
26:19:52
여기에서 CRM의 고객 키에 포함되지 않은 추가 문자가 있습니다.
Now we can see there is here like extra characters that are not included in the customer key from the CRM.
26:20:00
이 고객을 검색해 보겠습니다. CID와 유사한 ID를 가진 고객을 찾고 있습니다.
So let's go and search for example for this customer over here where CID like so we are searching for customer has similar ID.
26:20:11
이 고객을 찾고 있지만, AS에 세 개의 문자가 있습니다.
Now as you can see we are finding this customer but the issue is that we have those three characters in AS.
26:20:16
NAS가 있는 이유에 대한 설명이 없습니다. 이 정보를 제거해야 합니다.
There is no specifications or explanation why we have the NAS. So actually what we have to do is to go and remove those informations.
26:20:23
필요하지 않습니다. 다시 데이터를 확인해 보겠습니다.
We don't need it. So let's again check the data. So
26:20:26
오래된 데이터의 시작 부분에 NAS가 있습니다.
it looks like the old data have an NAS at the start
26:20:29
그 후에는 새로운 데이터가 있습니다.
and then afterward we have new data without those
26:20:32
이 세 문자를 정리해야 다른 테이블과 연결할 수 있습니다.
three characters So we have to clean up those IDs in order to be able to connect it with other tables So we're gonna do it like this
26:20:39
우리는 케이스 승리로 시작할 것입니다. 두 가지 시나리오가 있으므로
We're gonna start with the case win since we have like two scenarios in
26:20:42
우리 데이터에서 CID가 세 문자 NAS와 같다면, ID가 그 세 문자로 시작하면 변환 함수를 적용할 것입니다.
our data So if the CID is like the three characters NAS So if the ID starts with those three characters then we're gonna go and apply transformation function
26:20:54
그렇지 않으면 그대로 유지될 것입니다.
otherwise it's gonna stay like it is so
26:20:58
그게 다입니다. 이제 우리는 변환을 구축해야 합니다.
that's it so now we have to go and build
26:21:01
변환을 위해 서브스트링을 사용할 것이고,
the transformation so we're gonna use substring and
26:21:04
그런 다음 문자열을 정의해야 합니다. 그것은
then we have to define the string it's gonna be the
26:21:07
CID가 될 것이고, 그 위치를 정의해야 합니다.
cid and then we have to define the position where it
26:21:10
잘라내기 또는 추출을 시작하는 위치를 정의해야 합니다. 우리는 하나, 둘, 셋, 넷이라고 할 수 있습니다.
starts cutting or extracting so we can say one two three and then four so we have to define the position number four and then we have to define the string
26:21:19
추출해야 할 문자의 수를 정의해야 합니다.
how many characters should be extracted i
26:21:22
동적으로 만들 것입니다. 길이에 따라 진행할 것입니다.
will make it dynamic so i will go with the length i will not
26:21:25
얼마나 되는지 세지 않을 것입니다. 우리는 CID를 말할 것입니다.
go and count how much so we're gonna say the cid so
26:21:28
NAS와 같다면 잘 보입니다. 그러면
it looks good if it's like nas then go
26:21:32
CID에서 네 번째 위치에서 추출합니다.
and extract from the cid at the position number four
26:21:35
나머지 문자를 추출합니다. 이제 실행해 보겠습니다. 여기서 다시 쉼표가 빠졌습니다.
the rest of the characters so let's go and execute it and i'm missing here a comma again where we don't have any nas at the start
26:21:43
아무 NAS도 시작하지 않는 경우입니다.
and if you scroll down you can see those as
26:21:47
스크롤을 내리면 그런 것들이 보입니다.
well are not affected so with that we have
26:21:50
영향을 받지 않는 것들입니다. 그래서 우리는
now a nice id to be joined with the other table of
26:21:53
다른 테이블과 조인할 수 있는 멋진 ID를 갖게 되었습니다.
course we can go and test it like this where and then we take the
26:21:56
물론 이렇게 테스트할 수 있습니다.
whole thing the whole transformation and say not
26:21:59
전체 변환을 가져와서 말합니다.
in we remove of course the alias name we don't need
26:22:02
별칭 이름을 제거합니다. 필요하지 않습니다.
it and then we make a simple substring select distinct cst key the customer key from the silver
26:22:11
간단한 서브스트링을 만들고, 고객 키를 선택합니다.
table can be silver crm cost info
26:22:15
그래서 그게 다입니다. 확인해 보겠습니다.
so that's it let's go and check so as you can
26:22:18
잘 작동하고 있습니다. 우리는 찾을 수 없습니다.
see it is working fine so we are not able to find any
26:22:21
고객 정보와 일치하지 않는 데이터입니다.
unmatching data between the customer info from erb
26:22:24
변환 후 고객 정보와 CRM 간의 불일치 데이터
and the crm but of course after that transformation
26:22:27
변환을 사용하지 않으면 이렇게 제거할 경우 불일치 데이터가 많아지므로 변환이 작동하고 있다는 뜻입니다.
if you don't use the transformation so if you just remove it like this we will find a lot of unmatching data so this means our transformation is working
26:22:36
첫 번째 열은 여기까지입니다. 이제
perfectly and we can go and remove the original value so
26:22:39
다음 필드는 고객의 생일입니다.
that's it for the first column okay now moving on to
26:22:42
첫 번째로 해야 할 일은 데이터 유형을 확인하는 것입니다. 날짜입니다.
the next field we have the birthday of the customers so
26:22:45
정수나 문자열이 아니므로 괜찮습니다.
the first thing to do is to check the data type it is a date so
26:22:48
변환할 필요는 없지만 여전히 확인할 사항이 있습니다.
it's fine it is not an integer or a string so
26:22:51
생일과 관련하여 확인할 사항이 있습니다.
we don't have to convert anything but still there is something to check
26:22:54
범위를 벗어난 것이 있는지 확인할 수 있습니다.
with the birth date so we can check whether we have something out
26:22:57
예를 들어 정말 오래된 날짜가 있는지 확인할 수 있습니다.
of range so for example we can go and check whether we have really
26:23:01
그리고 24를 예로 들면 첫 번째
old dates at the best dates so let's take 19 100
26:23:04
날짜를 확인해 보겠습니다.
and let's say 24 and we can take the first
26:23:07
100세 이상의 고객이 있는 것 같습니다.
date of the month so let's go and check that well
26:23:11
정확한지 모르겠지만 이상하게 들립니다.
it looks like that we have customers that are older than a hundred
26:23:14
사업에 입찰하는 것이 이상하게 들립니다.
year well i don't know maybe this is correct but it
26:23:17
아이들에게 인사하세요. 안녕, 아이들. 예! 그리고 우리는 미래에 생일이 있는 고객이 거의 불가능한 다른 경계를 확인할 수 있습니다.
sounds of course strange to bid on the business of course hey this is creed and he is in charge of something that is correct
26:23:27
생일이 현재 날짜보다 크다고 말할 수 있습니다. 이렇게. 그러니 이 정보를 쿼리해 보겠습니다.
Say hi to the kids. Hi, kids. Yay. And then we can go and check the other boundary where it is almost impossible to have a customer that the birthday is in the future.
26:23:37
잘 작동하지 않을 것입니다. 왜냐하면 그들 사이에 '또는'이 있어야 합니다.
So we can say birth date is higher than the current date, like this. So let's go and query this information.
26:23:45
여기 목록을 확인하면 생일에 대해 유효하지 않은 날짜가 있습니다.
Well, it will not work because we have to have like an or between them.
26:23:48
모든 날짜가 미래의 생일입니다. 이는 전혀 용납할 수 없습니다.
And now if we check the list over here, we have dates that are invalid for the birth dates.
26:23:54
이는 나쁜 데이터 품질의 지표입니다. 물론 이를 수정하기 위해 원본 시스템에 보고할 수 있습니다.
So all those dates, they are all birthday in the future. And this is totally unacceptable.
26:23:59
여기서 이 날짜들에 대해 무엇을 할지는 여러분에게 달려 있습니다. 나쁜 데이터로 그대로 두거나.
So this is an indicator for bad data quality. Of course, you can go and report it to the source system in order to correct it.
26:24:05
아니면 모든 날짜를 null로 교체하여 정리할 수 있습니다.
So here, it's up to you what to do with those dates. Either leave it as it is, as bad data.
26:24:10
아니면 극단적인 경우에만 교체할 수 있습니다.
Or we can go and clean that up by replacing all those dates with a null.
26:24:14
그것에 대한 변환을 작성해 보겠습니다. 평소처럼 생일이 현재 날짜와 시간보다 크면 null로 시작할 수 있습니다.
Or maybe replacing only the one that is extreme, where it is 100% is incorrect.
26:24:19
그래서 그에 대한 변환을 작성해 보겠습니다. 평소처럼, 생년월일이 현재 날짜와 시간보다 크면 null로 시작할 수 있습니다.
So let's go and write the transformation for that. As usual, we can start with case when birth date is larger than the current date and time, then null.
26:24:31
그렇지 않으면 생년월일을 그대로 두는 else를 가질 수 있습니다.
Otherwise, we can have an else where we have the birth date as it is.
26:24:35
그리고 생년월일로 끝나는 것입니다. 이제 실행해 보겠습니다.
And then we have an end as birth date. So let's go and execute it.
26:24:41
그리고 그로 인해 미래의 생일을 가진 고객은 없어야 합니다. 그래서 생년월일에 대한 내용은 여기까지입니다.
And with that, we should not get any customer where the birthday in the future. So that's it for the birth date.
26:24:48
이제 다음으로 넘어가겠습니다. 성별이 있습니다. 성별 정보는 낮은 카디널리티를 가지므로 이 열 내의 모든 가능한 값을 확인해야 합니다.
Now let's move to the next one. We have the gender. Now again the gender information is low cardinalities so we have to go and check all the possible values inside this column.
26:24:56
모든 가능한 값을 확인하기 위해 select를 사용할 것입니다.
So in order to check all the possible values we're going to use select
26:25:00
우리 테이블에서 distinct gen을 사용하겠습니다.
distinct gen from our table so let's
26:25:03
실행해 보겠습니다. 이제 데이터가 그리 좋지 않습니다.
go and execute it and now the data doesn't look really
26:25:06
그래서 null이 있는 곳에 f가 있고
good so we have here in null we have an f we
26:25:09
빈 문자열이 있고 남성과 여성도 있습니다.
have here an empty string we have male female and
26:25:13
다시 m이 있으니 이건 그리 좋지 않습니다. 우리가 할 일입니다.
again we have the m so this is not really good what we're gonna do
26:25:16
우리는 모든 정보를 정리하여
we're gonna go and clean up all those informations in order to have
26:25:19
남성, 여성, 그리고 사용 불가능한 세 가지 값만 가지도록 할 것입니다.
only three values male female and not
26:25:22
사용 불가능하므로 이렇게 할 것입니다. case when이라고 말할 것입니다.
available so we're gonna do it like this we're gonna say case when and
26:25:25
값을 다듬어 공백이 없도록 할 것입니다.
now we're gonna go and trim the values just to make sure there
26:25:28
또한 대문자 함수를 사용하여 미래에 소문자가 있는 경우를 대비할 것입니다.
is like no empty spaces and as well i'm gonna go and use
26:25:31
모든 다양한 시나리오를 다루고 있습니다. 그래서 case입니다.
the upper function just to make sure that in the future if
26:25:35
f4에서 여성이라면
we get any lower cases and so on we are covering
26:25:38
여성으로 설정하고 진행할 수 있습니다.
all the different scenarios so case this is
26:25:41
남성에 대해서도 같은 작업을 수행합니다.
in f4 it's a female then
26:25:45
그래서 m이거나 남성이면
make it as female and we can go and
26:25:48
확실히 대문자로 만들어야 합니다.
do the same thing for the male like this
26:25:51
여기서 upper를 사용하고 있으므로
so if it is an m or a male make
26:25:54
남성입니다. 그렇지 않으면 모든 다른 시나리오에서는
sure it is capital letters because here we are using the upper then
26:25:57
사용 불가능해야 합니다. 빈 문자열이거나
it is a male otherwise all other scenarios it
26:26:01
사용할 수 없어야 하므로 빈 문자열이든
should be not available so whether it is an empty string or
26:26:04
널과 같은 것이므로 끝이 있어야 합니다
nulls and so on so we have to have an end
26:26:07
물론 이제 테스트를 해보겠습니다
of course as gen so now let's go and test
26:26:10
남성 빈 값은 사용할 수 없고
it and check whether we have covered everything so you can see the m is now
26:26:13
여성 빈 문자열이거나 공백이 있을 수 있습니다
male the empty is not available the f
26:26:16
사용할 수 없는 여성은 그대로 유지되고 남성도 마찬가지입니다
is female the empty string or maybe space is here is
26:26:20
그래서 모든 시나리오를 다루고 있습니다
not available female gonna stay as it is and the same for
26:26:23
프로젝트의 기준을 따르고 있으므로
the male so with that we are covering all the scenarios and
26:26:26
이것을 잘라서 원래 쿼리에 넣겠습니다
we are following our standards in the project so i'm gonna go and
26:26:29
여기서 전체를 실행해 보겠습니다
cut this and put it in our original query
26:26:32
그렇게 해서 세 개의 열을 정리했습니다
over here so let's go and execute the whole thing and
26:26:36
이제 질문은 ddl에서 무엇인가를 변경했는가입니다
with that we have cleaned up all those three columns
26:26:39
우리는 아무것도 변경하지 않았고 새로운 열도 도입하지 않았습니다
now the question is did we change anything in the ddl well
26:26:42
또한 데이터 유형을 변경하지 않았습니다
we didn't change anything we didn't introduce any new column
26:26:45
그래서 다음 단계는 서버 레이어에 삽입하는 것입니다
or change any data type so that means the next step is
26:26:48
보통처럼 여기서 silver에 삽입하겠습니다
we're gonna go and insert it in the server layer so
26:26:51
고객을 erp에 삽입한 후
as usual we're gonna say here insert into silver
26:26:55
모든 열 이름을 나열하겠습니다
erp the customer and then we're gonna go and
26:26:58
성별, 알겠습니다. 이제 실행해 보겠습니다
list all the column names so cid birthdays and
26:27:02
그것을 실행하면 모든 데이터가 삽입된 것을 볼 수 있습니다
the gender all right so let's go and execute
26:27:05
물론 다음 단계로 데이터 품질을 확인하는 것이 매우 중요합니다
it and with that we can see it inserted all the data and
26:27:08
여기서 쿼리로 돌아가서
of course the very important step as the next is to check the data
26:27:12
브론즈에서 실버로 변경하겠습니다
quality so let's go back to our query over here and
26:27:15
실버 레이어를 확인해 보겠습니다
change it from bronze to silver so let's go and check the
26:27:18
고객이지만 우리는 그것을 변경하지 않았습니다
silver layer well of course we are getting those very old
26:27:21
고객이지만 우리는 변경하지 않았습니다. 우리는 단지
customers but we didn't change that we only
26:27:24
미래의 생일을 변경했으며 결과에서 볼 수 없습니다. 즉, 모든 것이 깨끗하다는 의미입니다. 다음으로 다른 성별을 확인해 보겠습니다. 보시다시피, 우리는 세 가지 값만 있습니다.
change the birthday that is in the future and we don't see it here in the results so that means everything is clean so for the next one let's go and check the different genders and And as you can see, we have only the three values.
26:27:35
물론, 우리는 테이블을 최종적으로 살펴볼 수 있습니다.
And of course, we can go and take a final look to our table.
26:27:40
여기에서 CID, 생년월일, 성별을 볼 수 있으며 메타데이터 열도 확인할 수 있습니다. 모든 것이 놀랍습니다.
So you can see the CID here, the birth date, gender, and then we see our metadata column. And everything looks amazing.
26:27:47
그게 전부입니다. 우리가 수행한 데이터 변환의 종류는 무엇인가요?
So that's it. What are the different types of data transformations that we have done?
26:27:51
먼저, ID와 관련하여, 우리는 유효하지 않은 값을 처리했습니다. 그래서 필요 없는 부분을 제거했습니다.
First, with the ID, what you have done, we have handled invalid values. So we have removed this part where it is not needed.
26:27:58
그리고 생년월일에 대해서도 마찬가지입니다. 우리는 유효하지 않은 값을 처리했습니다.
And the same thing goes for the birth dates. We have handled as well invalid values.
26:28:03
마지막으로 성별에 대해서는 코드를 더 친숙한 값으로 매핑하여 데이터 정규화를 수행했습니다.
And then for the last one, for the gender, we have done data normalizations by mapping the code to more friendly value.
26:28:09
그리고 결측값도 처리했습니다. 이것이 우리가 이 코드에서 수행한 유형입니다.
And as well, we have handled the missing values. So those are the types that we have done in this code.
26:28:19
좋습니다, 두 번째 테이블로 넘어가겠습니다. 위치 정보가 있습니다. ARP 위치 A101이 있습니다.
Okay, moving on to the second table, we have the location informations. So we have ARP location A101.
26:28:26
여기에서 작업이 쉬운 이유는 두 개의 열만 있기 때문입니다. 통합 모델을 확인하면 우리의 테이블을 찾을 수 있습니다.
So now here the task is easy because we have only two columns. And if you go and check the integration model, we can find our table over here.
26:28:32
그래서 우리는 다른 시스템의 고객 정보와 CIID를 사용하여 연결할 수 있습니다.
So we can go and connect it together with the customer info from the other system using a CIID with the customer key.
26:28:40
이 두 정보는 테이블을 결합하기 위해 일치해야 합니다. 즉, 데이터를 확인해야 합니다.
So those two informations must be matching in order to join the tables. So that means we have to go and check the data.
26:28:46
데이터를 선택해 보겠습니다. CST 키에서. 실버 데이터를 가져옵시다. 고객 정보.
So let's go and select the data. CST key from. Let's go and get the silver data. Customer info.
26:28:53
결과를 확인하면 CIID에 문제가 있음을 알 수 있습니다.
So let's go. Now if you go and check the result, you can see over here that we have an issue with the CIID.
26:28:59
문자와 숫자 사이에 마이너스가 있지만, 고객 ID, 고객 번호는 문자와 숫자를 분리하는 것이 없습니다.
There is like a minus between the characters and the numbers, but the customer ID, the customer number, we don't have anything that splits the characters with the numbers.
26:29:09
이 두 정보를 결합하면 작동하지 않을 것입니다. 그래서 우리가 해야 할 일은 이 마이너스를 제거하는 것입니다. 완전히 불필요합니다.
So if you go and join those two informations, it will not be working. So what we have to do, we have to go and get rid of this minus because it is totally unnecessary.
26:29:17
그래서 이를 수정하겠습니다. 매우 간단할 것입니다. 우리가 할 일은 CIID를 말하는 것입니다.
So let's go and fix that. It's going to be very simple. So what you're going to do, we can say CIID.
26:29:22
그래서 우리는 마이너스를 검색하고 아무것도 아닌 것으로 교체할 것입니다. 이렇게 간단합니다.
So we're going to go and search for the minus and replace it with nothing. It's very simple like this.
26:29:28
다시 쿼리해 보겠습니다. 그렇게 하면 모든 것이 서로 매우 비슷해 보입니다. 그리고 우리는 쿼리를 수행할 수 있습니다.
So let's go and query it again. And with that, things look very similar to each other's. And as well, we can go and query it.
26:29:34
우리의 변환이 포함되지 않은 곳을 말할 것입니다.
So we're going to say where our transformation is not in.
26:29:38
그런 다음 이것을 서브쿼리로 사용할 수 있습니다. 그래서 실행해 보겠습니다.
Then we can go and use this as a subquery like this. So let's go and execute it.
26:29:44
보시다시피, 이제 일치하지 않는 데이터를 찾지 못하고 있습니다. 즉, 우리의 변환이 작동하고 있다는 의미입니다.
And as you can see, we are not finding any unmatching data now. So that means our transformation is working.
26:29:50
그것으로 우리는 두 테이블을 연결할 수 있습니다. 변환을 제거하면 많은 일치하지 않는 데이터를 찾을 수 있습니다.
And with that, we can go and connect those two tables together. So if I take that transformation away, you can see that we will find a lot of unmatching data.
26:29:58
변환은 괜찮습니다. 우리는 그것을 유지할 것이고
So the transformation is okay. we're gonna stay with it and
26:30:01
이제 여러 나라에 대해 이야기해 보겠습니다.
now let's speak about the countries now we have here multiple
26:30:04
값들이 여러 개 있습니다. 제가 할 일은 이것이 낮은 카디널리티라는 것입니다.
values and so on what i'm gonna do this is low cardinality
26:30:08
이 안에 있는 모든 가능한 값을 확인해야 합니다.
and we have to go and check all possible values inside this
26:30:11
이렇게 해서 우리 테이블에서 국가를 구별할 수 있습니다.
column so that means we are checking whether the data is consistent so
26:30:15
정보를 확인해 보겠습니다. 이제 널 값이 있습니다. 빈 문자열이 있는데, 이는 정말 나쁩니다.
we can do it like this distinct the country from our table i'm just gonna go and copy it like this and as well I'm going to go and sell the data by that country.
26:30:26
국가의 전체 이름이 있습니다. 그리고 국가의 약어도 있습니다. 이것은 혼합입니다.
So let's go and check the informations. Now you can see we have a null. We have an empty string, which is really bad.
26:30:33
DE가 있고 때때로 독일이 있습니다. 그리고 영국도 있습니다.
And then we have a full name of country. And then we have as well an abbreviation of the countries. Well, this is a mix.
26:30:40
미국의 경우, 같은 정보의 세 가지 버전이 있습니다.
This is not really good because sometimes we have DE and sometimes we have Germany. And then we have the United Kingdom.
26:30:46
국가의 품질이 자연스럽게 좋습니다. 그래서 이 변환 작업을 해보겠습니다.
And then for the United States, we have like three versions of the same information, which is as well not really good.
26:30:52
국가가 D와 같으면 독일로 변환하겠습니다.
So the quality of the country is naturally good. So let's go and work on that transformation.
26:30:57
다음은 미국에 관한 것입니다. 그래서 트림된 국가가 포함되어 있습니다.
As usual, we're going to start with the case when if trim country is equal to D, then we're going to transform it to Germany.
26:31:08
이제 그 두 값을 가져오겠습니다. US와 USA입니다.
And the next one, it's going to be about the USA. So if trim country is in.
26:31:14
그것은 미국이 될 것입니다. 그래서 우리는 세 가지 경우를 다루었습니다.
So now let's go and get those two values, the US and the USA. So US and USA.
26:31:21
이제 널과 빈 문자열에 대해 이야기해야 합니다.
Then it's going to be the United States. So with that we have covered as well the three cases.
26:31:29
그것은 사용 불가능할 것입니다. 그렇지 않으면 국가를 그대로 가져오고 싶습니다.
Now we have to talk about the null and the empty string. So we're going to say when trim country is equal to empty string or country is null.
26:31:40
트림된 국가를 사용하여 선행 또는 후행 공백이 없도록 합니다.
Then it's going to be not available. Otherwise I would like to get the country as it is.
26:31:45
이것이 국가라고 말해 보겠습니다. 그래서 작동하고 국가 정보가 변환되었습니다.
So trim country just to make sure that we don't have any leading or trailing spaces. So that's it.
26:31:52
이제 전체 새로운 변환을 가져와서 이전 것과 비교하겠습니다.
Let's go and say this is a country. So it is working and the country information is transformed.
26:31:58
이것을 이전 국가라고 부르겠습니다. 그리고 쿼리해 보겠습니다.
And now what I'm going to do, I'm going to take the whole new transformation and compare it to the old one.
26:32:03
이제 이전과 같은 값의 상태를 확인할 수 있습니다.
Let me just call this as old country. And let's go and query it.
26:32:09
빈 문자열은 사용 불가능하고 이제 같은 것입니다.
So now we can check those values state as before. So nothing did change. The DE is now Germany.
26:32:15
영국은 이전과 같이 검정색으로 남아 있습니다.
the empty string is not available then now the same thing and
26:32:18
미국은 완벽해 보입니다. 그래서 우리는
the united kingdom stayed as black it's like before and now we have one value for all those information so it's only the united
26:32:26
두 번째 열도 정리했습니다.
states so it looks perfect and with that we have
26:32:29
결과가 깨끗해졌습니다.
cleaned as well the second column so with that we have now clean
26:32:32
결과가 나왔고 이제 질문은 ddl에서 뭔가를 변경했는가입니다.
results and now the question did we change anything in the ddl
26:32:35
우리는 아무것도 변경하지 않았습니다. 두 개 모두 varchar이므로 이제 즉시 테이블에 삽입할 수 있습니다. 따라서 silver 고객 위치에 삽입합니다.
well we haven't changed anything both of them are varchar so we can go now immediately and insert it into our table So insert into silver customer location.
26:32:46
여기에서 열을 지정해야 합니다. 매우 간단합니다. ID와 국가입니다. 이제 실행해 보겠습니다.
And here we have to specify the columns. It's very simple. The ID and the country. So let's go and execute it.
26:32:53
보시다시피, 이제 모든 값이 삽입되었습니다. 다음으로 이 정보를 다시 확인하겠습니다.
And as you can see, we got now inserted all those values. Of course, as a next we go and double check those informations.
26:32:59
저는 여기서 모든 것을 제거하고 싶습니다. 그리고 bronze 대신 silver로 가겠습니다.
I would just go and remove all those stuff as well here. And instead of bronze, let's go with the silver.
26:33:06
보시다시피, 국가의 모든 값이 좋습니다. 테이블을 최종적으로 살펴보겠습니다. 이렇게요.
So as you can see, all the values of the country looks good. And let's have a final look to the table. So like this.
26:33:12
우리는 구분자 없이 ID를 가지고 있습니다. 국가와 메타데이터 정보도 있습니다.
So we have the IDs without the separator. We have the countries and as well our metadata information.
26:33:19
그렇게 해서 우리는 위치에 대한 데이터를 정리했습니다. 알겠습니다.
So with that, we have cleaned up the data for the location. Okay.
26:33:22
이제 여기서 수행한 데이터 변환의 다양한 유형은 먼저 잘못된 값을 처리했습니다.
So now what are the different types of data transformation that we have done here is first we have handled invalid values.
26:33:28
우리는 마이너스를 빈 문자열로 제거했습니다. 그리고 국가에 대해서는 데이터 정규화를 수행했습니다.
So we have removed the minus with an empty string. And for the country, we have done data normalization.
26:33:34
우리는 코드를 친숙한 값으로 교체했습니다.
So we have replaced codes with friendly values.
26:33:38
그리고 동시에 빈 문자열과 null을 사용하지 않음으로 대체하여 누락된 값을 처리했습니다.
And as well at the same time, we have handled missing values by replacing the empty string and null with not available.
26:33:44
그리고 한 가지 더, 물론 원하지 않는 공백을 제거했습니다.
And one more thing, of course, we have removed the unwanted spaces.
26:33:48
그래서 이것이 우리가 이 테이블에 대해 수행한 다양한 변환 유형입니다.
So those are the different types of transformation that we have done for this table.
26:33:56
자, 여러분, 이제 에너지를 유지하고, 정신을 유지하세요. 우리는 마지막 테이블을 정리해야 합니다.
Okay guys, now keep the energy up, keep the spirit up. We have to go and clean up the last table in the bronze layer.
26:34:02
물론 우리는 아무것도 건너뛸 수 없습니다. 품질을 확인해야 합니다.
And of course we cannot go and skip anything. have to check
26:34:06
우리는 이제 제품 카테고리에 대한 테이블을 가지고 있습니다.
the quality and to detect all the errors so now
26:34:09
여기에는 네 개의 열이 있습니다. 첫 번째 열부터 시작해 보겠습니다.
we have a table about the categories for the products and
26:34:12
ID를 보시다시피, 우리의 통합 모델에서 연결할 수 있습니다.
here we have like four columns let's go and start with the first one the
26:34:15
이 테이블은 crm의 제품 정보와 함께 연결됩니다.
id as you can see in our integration model we can connect
26:34:18
제품 키를 사용하여 silver에서 기억하실 겁니다.
this table together with the product info from the crm
26:34:21
우리는 제품 정보에 대해 이를 위한 추가 열을 만들었습니다. 데이터를 선택하면 열이 있습니다.
using the product key and as you remember in the silver
26:34:24
카테고리 ID라고 불리며, 이것은 정확히
layer we have created an extra column for that in the product info so if you go and select those data you can see we have a column
26:34:32
이 테이블에 있는 ID와 일치합니다.
called category id and this one is exactly
26:34:35
우리는 테스트를 수행했으므로 이 ID는 준비되었습니다.
matching the id that we have in this table and we
26:34:38
테스트를 완료했으므로 이 ID는 사용할 준비가 되었습니다.
have done the testing so this id is ready to be
26:34:41
다른 테이블과 함께 사용할 수 있으므로 여기서 할 일이 없습니다.
used together with the other table so there is nothing
26:34:44
다음 열은 문자열입니다.
to do over here and now for the next columns they are string
26:34:48
원하지 않는 공백이 있는지 확인할 수 있습니다.
and of course we can go and check whether there are any unwanted
26:34:51
원하지 않는 공백을 확인하고 있습니다.
spaces so we are checking for the unwanted spaces so
26:34:54
여기서 같은 테이블을 가져오겠습니다.
let's go and check select start from and
26:34:57
카테고리를 확인하고 있습니다.
we're gonna go and get the same table like this here and first
26:35:00
카테고리가 원하지 않는 공백을 제거한 후와 같습니다.
we are checking the category so the category is not
26:35:04
공백을 제거한 후와 같습니다.
equal to the category after trimming the unwanted
26:35:07
결과가 없으므로 원하지 않는 공백이 없습니다.
spaces so let's go and execute it
26:35:10
원하지 않는 공백이 없으므로 다른 열을 확인하겠습니다.
and as you can see we don't have any results so there are no
26:35:13
다른 열을 확인하겠습니다. 예를 들어, 하위 카테고리입니다.
unwanted spaces let's go and check the other column for example the subcategory the next one so let's get
26:35:20
원하지 않는 공백이 없으므로 하위 카테고리를 확인하겠습니다.
the subcategory and the under query as well we
26:35:23
하위 카테고리를 확인하겠습니다.
don't have anything so that means we don't have unwanted spaces
26:35:26
하위 카테고리를 확인하겠습니다.
for the subcategory let's go now and check the last column
26:35:30
지금 복사하고 붙여넣겠습니다.
so i will just copy and paste now let's get the
26:35:33
결과가 없습니다. 원하지 않는 공백이 없습니다.
maintenance and let's go and execute and as well
26:35:36
이 테이블 안에 원하지 않는 공백이 없습니다.
no results perfect we don't have any unwanted spaces
26:35:39
데이터 표준화를 확인하겠습니다.
inside this table so now the next step is that we're
26:35:42
이것을 선택하겠습니다.
going to go and check the data standardizations because all those columns has low cardinality so what you can do
26:35:48
우리 테이블에서 고양이 카테고리를 가져오겠습니다.
we can say select this thing let's
26:35:52
복사하고 붙여넣고 모든 값을 확인하겠습니다.
get the cats category from our table i'll
26:35:55
액세서리, 자전거, 의류가 있습니다.
just copy and paste it and check all values so
26:35:58
모든 것이 완벽해 보입니다.
as you can see we have the accessories bikes clothing and
26:36:01
이 열에서 변경할 필요가 없습니다.
components everything looks perfect we don't have to change
26:36:04
이 열에서 아무것도 변경할 필요가 없습니다. 하위 범주를 확인해 보겠습니다. 아래로 스크롤하면 모든 값이 친숙하고 좋습니다. 여기서 변경할 것이 없습니다.
anything in this column let's go and check the subcategory and if you scroll down all values are friendly and nice as well nothing to change here
26:36:14
마지막 열인 유지 보수를 확인해 보겠습니다. 완벽합니다.
and let's go and check the last column the maintenance perfect
26:36:17
우리는 두 가지 값만 있습니다. 예와 아니오, 우리는 아무것도 없습니다.
we have only two values yes and no we don't have any
26:36:20
널 값이 없습니다. 친구들, 이는 이 테이블이
nulls so my friends that means this table has
26:36:23
정말 좋은 데이터 품질을 가지고 있으며 우리는 정리할 필요가 없습니다.
really nice data quality and we don't have to clean up
26:36:26
아무것도 변경할 필요가 없지만 여전히 우리의 프로세스를 따라야 합니다. 우리는
anything but still we have to follow our process we have to
26:36:29
구리에서 은으로 로드해야 합니다. 아무것도 변환하지 않았더라도
go and load it from the bronze to the silver even if we
26:36:32
우리의 작업은 정말 쉽습니다. 우리는 '은 ERP PX에 삽입'이라고 말할 것이고, 정의할 것입니다.
didn't transform anything so our job is really easy here we're gonna go and say insert into silver dots erp px and so on and we're gonna go and define
26:36:44
열을 정의할 것입니다. ID, 카테고리
the columns so it's going to be the id the category
26:36:47
하위 카테고리 유지 보수입니다. 그래서
subcategory maintenance so that's
26:36:50
이제 데이터를 삽입해 보겠습니다. 평소처럼 우리가 할 일입니다.
it let's go and insert the data now as usual what we're going to do
26:36:53
데이터를 확인해 보겠습니다.
we're going to go and check the data so
26:36:56
실버 ERP DX 시작합시다
silver erp dx let's
26:36:59
모든 ID, 카테고리, 하위 카테고리, 유지 관리가 여기 있으며 메타 열이 있어 모든 것이 올바르게 삽입되었습니다.
have a look all right so we can see the ids are here the categories the subcategories the maintenance and we have our meta column so everything is inserted correctly
26:37:10
좋습니다. 이제 모든 쿼리와 6개 테이블에 대한 삽입 문이 있습니다.
All right, so now I have all those queries and the insert statements for all six tables.
26:37:15
데이터를 삽입하기 전에 중요한 것은 테이블을 비우고 초기화해야 한다는 것입니다.
And now what is important before inserting any data, we have to make sure that we are truncating and emptying the table.
26:37:22
이 쿼리를 두 번 실행하면 무슨 일이 발생할까요? 중복이 삽입됩니다.
Because if you run this query twice, what's going to happen, you will be inserting duplicates.
26:37:26
먼저 데이터를 초기화한 다음 전체 로드를 수행하고 모든 데이터를 삽입합니다. 그래서 우리는 한 단계가 필요합니다.
So first truncate the data and then do a full load, insert all data. So we're going to have one step before.
26:37:33
브론즈 레이어와 같습니다. 테이블을 초기화하고 실버 고객 정보를 초기화할 것입니다.
It's like the bronze layer. We're going to say truncate table and then we will be truncating the silver customer info.
26:37:39
그 후에 데이터를 삽입해야 합니다.
and only after that we have to go and insert the data
26:37:42
물론 이 멋진 정보를 제공할 수 있습니다.
and of course we can go and give this nice information at
26:37:45
먼저 테이블을 초기화한 다음 삽입합니다.
the start so first we are truncating the table and then inserting
26:37:48
전체를 실행해 보겠습니다. 시작합시다.
so if i go and run the whole thing so let's go
26:37:51
이 작업을 수행하면 작동할 것이므로 다시 실행할 수 있습니다.
and do it it will be working so if i can run it again we
26:37:54
중복이 없을 것이므로 이 단계를 추가해야 합니다.
will not have any duplicates so we have to go and add this step
26:37:58
각 삽입 전에 이 단계를 추가해야 합니다.
before each insert so let's go and do that
26:38:01
모든 테이블 작업이 완료되었습니다. 이제 모든 것을 실행해 보겠습니다.
all right so i'm done with all tables so now let's go and run everything so let's go and execute it
26:38:08
메시지에서 모든 것이 완벽하게 작동하는 것을 볼 수 있습니다.
and we can see in the messaging everything working perfectly
26:38:11
모든 테이블을 비우고 데이터를 삽입했습니다.
so with that we made all tables empty and then we inserted
26:38:14
데이터가 이렇기 때문에
the data so
26:38:19
우리가 멋진 스크립트를 가지고 있어요, 그 스크립트는
perfect with that we have a nice script that loads the
26:38:22
은색 레이어를 로드하지만, 물론 프론트 레이어처럼 우리는
silver layer but of course like the front layer we're gonna put
26:38:25
모든 것을 하나의 저장 프로시저에 넣을 것이므로, 이제 그렇게 해봅시다.
everything in one stored procedure so let's go and do that
26:38:29
여기서 시작 부분으로 가서 프로시저를 생성하거나 수정하겠다고 말하고, 우리는
we'll go to the beginning over here and say create or alter procedure and we're
26:38:35
은색 스키마에 넣고 명명 규칙을 사용합니다.
put it in the schema silver and using the naming convention
26:38:38
은색 로드를 하고, 여기서 시작하겠다고 말할 것입니다.
load silver and we're gonna go over here and say begin and
26:38:41
전체 코드를 가져오고, 긴 코드이므로
take the whole code and it is long one and
26:38:44
탭으로 한 번 눌러주고, 마지막에 우리는 이렇게 말할 것입니다.
give it one push with the tab and then at the end we're gonna say and
26:38:48
완벽합니다, 저장 프로시저가 생겼습니다.
perfect so we have our stored procedure but
26:38:51
우리는 여기서 오류가 발생하지 않도록 잊어버렸습니다.
we forgot here that us with that we will not have an error
26:38:54
이제 실행해봅시다. 저장 프로시저가 생성되었습니다. 프로그래머블리티로 가면 두 개의 프로시저를 찾을 수 있습니다: 로드 브론즈와 로드
let's go and execute it so the stored procedure is created if you go to the programmability and you will find two procedures load bronze and load
26:39:03
은색. 이제 시도해봅시다. 당신이 해야 할 일은 이제 단지 실행하는 것입니다.
silver so now let's go and try it out all what you have to do is now only to execute
26:39:08
은색 로드 은색을 실행합시다.
the silver load silver so let's
26:39:11
저장 프로시저를 실행하고, 그렇게 하면 우리는
execute the start procedure and with that we will get
26:39:14
같은 결과를 얻을 것입니다. 이 세 번째 프로시저는 이제
the same results this third procedure now is
26:39:17
전체 은색 레이어를 로드하는 책임이 있습니다.
responsible of loading the whole silver layer now
26:39:20
물론 여기 메시징이 그리 좋지 않습니다.
of course the messaging here is not really good because
26:39:23
우리는 브론즈 레이어에서 많은 것들을 추가할 수 있다는 것을 배웠습니다.
we have learned in the bronze layer we can go and add many stuff
26:39:26
예를 들어 오류 처리, 좋은 메시징, 잡기
like handling the error doing nice messaging catching
26:39:30
소요 시간을 추가하는 것과 같은 것들입니다. 이제 당신의 작업은 비디오를 일시 정지하고, 이 세 번째 프로시저를 가져가서 브론즈 레이어와 매우 유사하게 변환하는 것입니다. 같은 메시징과 우리가 추가한 모든 추가 기능을 포함하여.
the duration time so now your your task is to pause the video, take this third procedure and go and transform it to be very similar to the bronze layer with the same messaging and all the add-ons that we have added.
26:39:42
비디오를 지금 일시 정지하세요. 저도 오프라인에서 할 것이고 곧 뵙겠습니다.
So pause the video now, I will do it as well offline and I will see you soon.
26:39:52
좋습니다. 완료되셨기를 바라며 결과를 보여드릴 수 있습니다.
Okay, so I hope you are done and I can show you the results.
26:39:55
우리가 정의한 청동 레이어와 비슷합니다. 몇 가지 변수를 잘라내기 위해
It's like the bronze layer we have defined at the star, few variables in order to cut
26:40:00
지속 시간을 가지고 시작 시간과 종료 시간 패치를
the duration so we have the start time the end time patch
26:40:03
시작 시간과 종료 시간 패치를 출력하고 있습니다.
start time and patch end time and then we are printing
26:40:06
출력에서 멋진 메시지를 만들기 위해 많은 작업을 하고 있습니다.
a lot of stuff in order to have like nice messaging in the output
26:40:09
시작할 때 서버 레이어를 로드하고 있다고 말하고 있습니다.
so at the start we are saying loading the server layer and
26:40:13
소스 시스템에 따라 분할을 시작하므로 로딩 중입니다.
then we start splitting by the source system so loading the
26:40:16
CRM 테이블을 보여드릴 것이며 지금은 하나의 테이블만 보여드리겠습니다.
crm tables and i'm going to show you only one table for now so
26:40:19
타이머를 설정하고 시작 시간을 말하며 날짜와 시간 정보를 가져옵니다.
we are setting the timer so we are saying start time get the date and time information to it then we are doing the usual we
26:40:26
테이블을 잘라내고 정리한 후 새 정보를 삽입합니다.
truncating the table and then we are inserting the
26:40:29
멋진 메시지를 만들어 로드 지속 시간을 말할 것입니다.
new informations after cleaning it up and we have this
26:40:32
시작 시간과 종료 시간의 차이를 찾고 있습니다.
nice message we will say load duration where we are finding
26:40:36
함수 date diff를 사용하여 결과를 보여주고 싶습니다.
the differences between the start time and the end time using
26:40:39
초 단위로 결과를 출력하고 있습니다.
the function date diff and we want to show the result in
26:40:42
이 테이블을 로드하는 데 걸린 시간을 출력하고 있습니다.
the seconds so we are just printing how long it
26:40:45
모든 테이블에 대해 이 프로세스를 반복할 수 있습니다.
took to load this table and we can go and repeat this
26:40:48
SQL이 시도 부분을 실행하도록 하고 문제가 있으면
process for all the tables and of course we are putting everything in try and catch so the sql gonna go
26:40:54
SQL이 실행되도록 하고 있습니다.
and try to execute the try part and if there
26:40:57
문제 발생 시 캐치로 가고 있습니다.
are any issues the sql gonna go and execute the
26:41:01
오류 메시지, 오류 번호 및 오류 상태를 출력하고 있습니다.
catch and here we are just printing few information like
26:41:04
청동 레이어와 동일한 기준을 따르고 있습니다.
the error message the error number and the error states and we
26:41:07
전체를 실행해 보겠습니다.
are following exactly the same standards as the bronze layer so
26:41:10
그렇게 하면 소금 절차의 정의가 업데이트되었습니다.
let's go and execute the whole thing and
26:41:14
이제 실행하고 은색 점을 로드합니다.
with that we have updated the definition of the salt procedure let's go
26:41:17
이제 실행해 보겠습니다.
now and execute it so execute silver dots loads silver so let's go and do that it went
26:41:24
매우 빠르게 진행됩니다.
very fast like few than one seconds again because we are working
26:41:27
로컬 머신에서 서버 레이어를 로드합니다.
on local machine loading the server layer loading the
26:41:30
CRM 테이블을 로드하고 있습니다.
crm tables and we can see this nice messaging so
26:41:34
테이블을 잘라내고 데이터를 삽입하는 것으로 시작합니다.
it starts with truncating the table inserting the data and
26:41:37
이 테이블의 로드 기간을 확인하고 있습니다.
we are getting the load duration for this table and you will see
26:41:40
모든 것이 1초 이내입니다.
that everything is below one second and that's because
26:41:43
실제 프로젝트에서는 물론 1초 이상을 얻을 수 있으므로, 결국 전체 서버 레이어의 로드 지속 시간이 있으며, 이제 하나 더 있습니다.
at a real project you will get of course more than one second so at the end we have load duration of the whole server layer and now i have one more
26:41:51
이 서브 프로시저에 다양한 유형을 추가하고 있습니다.
thing for you let's say that you are changing the design of
26:41:54
메시징 유형을 추가하거나 로그를 생성하고 있습니다.
this third procedure for the silver layer you are adding different types
26:41:58
이제 새로운 아이디어와 재설계가 필요합니다.
of messaging or maybe you are creating your logs and so on
26:42:01
항상 같은 변경 사항을 고려해야 합니다.
so now all those new ideas and redesigns that you
26:42:04
다른 저장 프로시저에서도 같은 변경 사항을 적용해야 합니다.
are doing for the silver layer you have always to think about bringing
26:42:07
코드를 항상 같은 기준에 맞춰 유지해야 합니다.
the same changes as well in the other stored procedure
26:42:10
스크립트를 유지하고 최신 상태로 유지해야 합니다.
for the bronze layer so always try to keep your codes following the same standards don't have like one idea in one start procedure and an old idea in another one.
26:42:20
모든 것을 최선의 관행에 따라 진행해야 합니다.
Always try to maintain those scripts and to keep them all up to date following the same standards otherwise it can be really hard for other developers to understand the cause.
26:42:29
이제 매우 훌륭한 두 개의 ETL 스크립트가 있습니다.
I know that needs a lot of work and commitments but this is your job to make everything following the best practices and following the same naming convention and standards that you put for your projects.
26:42:40
브론즈 레이어를 로드하는 스크립트입니다.
So guys now we have very nice two ETL scripts.
26:42:44
우리의 데이터 웨어하우스는 매우 간단합니다.
that loads the bronze layer and another one for the server
26:42:47
먼저 브론즈 레이어를 실행해야 합니다.
layer so now our data warehouse is very simple all what you have
26:42:50
CSV 파일에서 모든 데이터를 가져옵니다.
to do is to run first the bronze layer and
26:42:53
소스에서 데이터를 가져와 데이터 웨어하우스에 넣습니다.
with that we are taking all the data from the csv files from
26:42:57
브론즈 레이어에 데이터를 넣고 있습니다.
the source and we put it inside our data warehouse in
26:43:00
브론즈 레이어를 새로 고칩니다.
the bronze layer and with that we are refreshing the whole
26:43:03
브론즈 레이어에서 데이터를 가져와 변환합니다.
bronze layer once it's done the next step is to run the stored procedure of the server layer so once you execute it you are taking now all the
26:43:11
브론즈 레이어에서 데이터를 변환하고 정리합니다.
data from the bronze layer transforming it cleaning it
26:43:15
서버 레이어로 로드합니다. 그리고
up and then loading it to the server layer and as
26:43:18
데이터를 한 레이어에서 다른 레이어로 이동하고 있습니다.
you can see the concept is very simple we are just moving the data
26:43:21
서버 레이어에서 많은 데이터 변환을 수행했습니다.
from one layer another layer with different tasks all
26:43:24
좋은 친구들, 서버 레이어에서 데이터 변환을 많이 했다는 것을 볼 수 있습니다.
right guys so as you can see in the server layer we have done a lot of data transformations
26:43:28
그리고 데이터 정화에서 우리가 가진 모든 유형을 다루었습니다. 그래서 중복 제거, 데이터 필터링, 누락된 데이터 처리, 유효하지 않은 데이터, 원하지 않는 공백, 데이터 유형 캐스팅 등을 수행했습니다.
and we have covered all the types that we have in the data cleansing so we remove duplicates data filtering handling missing data invalid data unwanted spaces casting the data types and so on.
26:43:40
또한 새로운 열을 파생하고, 데이터 풍부화를 수행했으며, 많은 데이터를 정규화했습니다.
And as well, we have derived new columns, we have done data enrichment, and we have normalized a lot of data.
26:43:46
그래서 이제, 물론 우리가 아직 하지 않은 것은 비즈니스 규칙과 로직, 데이터 집계 및 데이터 통합입니다.
So now, of course, what we have not done yet, business rules and logic, data aggregations, and data integration.
26:43:51
다음 레이어를 위한 것입니다. 좋아요, 친구들, 드디어 데이터를 정리하고 데이터 품질을 확인했습니다.
This is for the next layer. All right, my friends, so finally, we are done cleaning up the data and checking the quality of our data.
26:43:59
그래서 우리는 이 두 단계를 마무리할 수 있습니다. 그리고 이제 다음 단계로 넘어가야 하므로 데이터 흐름 다이어그램을 확장해야 합니다. 자, 갑시다.
So we can go and close those two steps. And now to the next step, we have to go and extend the data flow diagram. So let's go.
26:44:10
좋아요, 이제 실버 레이어를 위한 데이터 흐름을 확장해 보겠습니다.
Okay, so now let's go and extend our data flow for the silver layer.
26:44:15
제가 할 것은 전체를 복사해서 브론즈 레이어 옆에 두는 것입니다.
So what I'm going to do, I'm just going to go and copy the whole thing and put it side by side to the bronze layer.
26:44:20
그리고 이것을 실버 레이어라고 부르겠습니다.
And let's call it silver layer.
26:44:24
테이블 이름은 이전과 동일하게 유지됩니다. 왜냐하면 브론즈 레이어와 일대일 관계가 있기 때문입니다. 하지만 우리가 할 것은 색상을 변경하는 것입니다.
And the table name is going to stay as before because we have like one to one like the bronze layer. But what we're going to do, we're going to go and change the coloring.
26:44:31
그래서 모든 것을 표시하고 회색으로 만들어 실버처럼 보이게 하겠습니다. 그리고 물론, 매우 중요한 것은 계보를 만드는 것입니다.
So I'm going to go and mark everything and make it gray like silver. And of course, what is very important is to make the lineage.
26:44:38
그래서 이제 브론즈에서 화살표를 그려 서버 테이블로 연결하겠습니다.
So I'm going to go now from the bronze and take an arrow and put it to the server table.
26:44:43
이제 이렇게 해서 세 레이어 간의 계보가 생겼고, 고객 정보 테이블을 확인하고 있습니다.
And now with that, we have like a lineage between three layers and you are checking this table, the customer info.
26:44:49
이것이 고객 정보의 브론즈 레이어에서 어떻게 오는지 이해할 수 있습니다.
You can understand how this comes from the bronze layer from the customer info.
26:44:54
그리고 이것은 소스 시스템 CRM에서 오는 것입니다.
And as well, this comes from the source system CRM.
26:44:57
그래서 이제 서로 다른 레이어 간의 계보를 볼 수 있으며, 어떤 스크립트를 보지 않고도 한 그림에서 전체 프로젝트를 이해할 수 있습니다.
So now we can see the lineage between different layers and without looking to any scripts and so on in one picture, you can understand the whole project.
26:45:05
그래서 이 그림을 보면서 많은 것을 설명할 필요가 없습니다.
So I don't have to explain a lot of stuff by just looking to this picture.
26:45:09
데이터가 소스, 브론즈 레이어, 실버 레이어를 거쳐 나중에 골드 레이어로 흐르는 방식을 이해할 수 있습니다.
You can understand how the data is flowing between sources, bronze layer, silver layer and to the gold layer, of course, later.
26:45:17
보시다시피, 정말 깔끔하고 보기 좋습니다. 좋아요. 그래서 이를 통해 데이터 흐름을 업데이트했습니다.
So as you can see, it looks really nice and clean. All right. So with that, we have updated the data flow.
26:45:23
다음으로, 우리는 작업을 git 레포에 커밋할 것입니다. 자, 갑시다.
next we're gonna go and commit our work in the get repo so let's go
26:45:31
좋아요, 이제 스크립트를 커밋하러 갑시다. 우리는 가야 합니다.
okay so now let's go and commit our scripts we're gonna go to the
26:45:34
폴더 스크립트가 있고 여기 서버 레이어가 있습니다.
folder scripts and here we have a server layer if
26:45:37
서버 레이어를 위해 ddl 스크립트를 넣을 것입니다.
you don't have it of course you can go and create it so first we're gonna go and put
26:45:40
ddl 스크립트를 넣을 것이므로 코드를 붙여넣겠습니다.
the ddl scripts for the server layer so let's go
26:45:43
작업을 커밋하고 같은 작업을 수행할 것입니다.
and i will paste the code over here and as usual we have this comment at the header explaining the purpose of this script so let's go and commit
26:45:52
저장 프로시저를 위해 같은 작업을 수행할 것입니다.
our work and we're gonna do the same thing for the
26:45:55
저장 프로시저를 위해 이미 파일이 있습니다.
stored procedure that's loads the silver layer so
26:45:58
여기에서 붙여넣겠습니다. 저장 프로시저가 있습니다.
i'm gonna go over here i have already file for that so
26:46:01
여기에서 붙여넣겠습니다. 저장 프로시저가 있습니다.
let's go and paste that so we have here our stored procedures
26:46:05
이 스크립트는 데이터를 로드하는 ATL 프로세스를 수행합니다.
and as usual at the start we have as well so this script
26:46:08
브론즈에서 실버로 데이터를 로드합니다.
is doing the atl process where we load the data
26:46:11
먼저 테이블을 잘라내고 변환된 데이터를 삽입합니다.
from bronze into silver so the action is to truncate
26:46:14
브론즈에서 실버로 데이터를 삽입합니다. 매개변수는 없습니다.
the table first and then insert transformed cleansed
26:46:17
프로젝트에 커밋할 또 다른 것이 있습니다. 모든 쿼리입니다.
data from bronze to silver there are no parameters at all and this is how you can use the start procedure okay so we're gonna go and commit our work
26:46:27
서버 레이어의 품질을 확인하기 위해 만든 쿼리입니다.
and now one more thing that we want to commit in our projects all those queries
26:46:31
이번에는 스크립트에 넣지 않을 것입니다.
that you have built to check the quality of the server layer
26:46:34
테스트로 가서 품질 검사 실버라는 새 파일을 만들 것입니다.
so this time we will not put it in the scripts we're gonna go to the
26:46:37
여기에서 모든 쿼리를 붙여넣을 것입니다.
tests and here we're gonna go and make a new file called quality checks silver and inside it we're gonna go and paste all the queries that we have filled i just here reorganize them
26:46:48
테이블별로 정리한 모든 체크를 볼 수 있습니다.
by the tables so here we can see all the checks that
26:46:51
우리가 과정 중에 수행한 체크입니다.
we have done during the course and at the header we
26:46:54
이 스크립트는 서버 레이어의 품질을 확인합니다.
have here nice comments so here we are just saying that this
26:46:57
널, 중복, 원치 않는 공백, 유효하지 않은 것을 확인합니다.
script is gonna check the quality of the server layer and we are checking
26:47:00
날짜 범위 등도 확인합니다.
for nulls duplicates unwanted spaces invalid
26:47:03
새 품질 검사를 할 때마다 공유할 것을 추천합니다.
date range and so on so that each time you come up
26:47:06
그래서 그게 전부입니다. 체크를 리포에 넣겠습니다.
with a new quality check i'm gonna recommend you to share it with the project and with the other team in order to make it part of multiple checks that you do after running the ATLs.
26:47:16
그래서 그게 전부입니다. 체크를 리포에 넣겠습니다.
So that's it. I'm going to go and put those checks in our repo.
26:47:20
그게 다야. 나는 가서 그 체크를 우리 리포지토리에 넣을 거야.
And in case I come up with new check, I'm going to go and update it. Perfect. So now we have our code in our repository.
26:47:27
좋아. 그래서 이제 우리의 코드는 안전하고 우리는 전체 에픽을 끝냈어. 우리는 실버 레이어를 구축했어.
All right. So with that, our code is safe and we are done with the whole epic. So we have built the silver layer.
26:47:33
이제 가서 최소화해 보자. 그리고 이제 내가 가장 좋아하는 레이어인 골드 레이어로 가자. 그래서 우리는 그것을 구축할 거야.
Now let's go and minimize it. And now we come to my favorite layer, the gold layer. So we're going to go and build it.
26:47:40
첫 번째 단계는, 항상 그렇듯이, 분석해야 해. 이번에는 비즈니스 객체를 탐색할 거야. 자, 시작해 보자.
The first step, as usual, we have to analyze. and this time we're gonna explore the business objects so let's go
26:47:49
좋아, 이제 우리는 큰 질문에 다다랐어. 골드 레이어를 어떻게 구축할 수 있을까?
all right so now we come to the big question how we can build the gold layer
26:47:52
항상 그렇듯이 분석하는 것부터 시작해. 이제 우리가 할 일은 무엇일까?
as usual we start with analyzing so now what we're gonna do
26:47:55
여기서는 우리가 탐색하고 이해해야 할 것들이 있어.
here is to explore and understand what are the
26:47:59
주요 비즈니스 객체는 우리 소스 시스템에 숨겨져 있어. 보시다시피 두 개의 소스와 여섯 개의 파일이 있어. 여기서 우리는 비즈니스 객체가 무엇인지 식별해야 해. 이 이해가 있으면 코딩을 시작할 수 있어.
main business objects that are hidden inside our source system so as you can see we have two sources six files and here we have to identify what are the business objects once we have this understanding then we we can start coding.
26:48:10
그리고 여기서 우리가 하고 있는 주요 변환은 데이터 통합이야. 보통 나는 이것을 세 단계로 나눠.
And here the main transformation that we are doing is data integration. And here usually I split it into three steps.
26:48:16
첫 번째로, 우리는 식별한 비즈니스 객체를 구축할 거야.
The first one, we're going to go and build those business objects that we have identified.
26:48:20
비즈니스 객체를 만든 후에는 그것을 살펴보고 이 테이블의 유형이 무엇인지 결정해야 해. 차원인가?
And after we have a business object, we have to look at it and decide what is the type of this table. Is it a dimension?
26:48:27
사실인가? 아니면 아마도 평면 테이블인가? 우리가 채운 테이블의 유형은 무엇일까?
Is it a fact? Or is it like maybe a flat table? So what type of table that we have filled?
26:48:32
마지막 단계는 물론 모든 열의 이름을 친숙하고 이해하기 쉬운 것으로 바꿔야 해.
And the last step is, of course, we have now to rename all the columns into something friendly and easy to understand.
26:48:38
그래서 우리의 소비자들이 기술적인 요구로 어려움을 겪지 않도록 해야 해. 모든 단계를 마친 후, 우리가 만든 것을 검증할 시간이야.
so that our consumers don't struggle with technical needs. So once we have all those steps, what we're going to do, it's time to validate what we have created.
26:48:45
우리가 해야 할 일은, 우리가 만든 새로운 데이터 모델이 연결 가능해야 하고 데이터 통합이 올바르게 완료되었는지 확인해야 해.
So what we have to do, the new data model that we have created, it should be connectable and we have to check that the data integration is done correctly.
26:48:53
모든 것이 괜찮다면 마지막 단계를 건너뛸 수 없어. 우리는 문서화하고 우리의 작업을 Git에 커밋해야 해.
And once everything is fine, we cannot skip the last step. We have to document and as well commit our work in the Git.
26:48:59
그는 새로운 유형의 문서화를 도입할 거야. 그래서 우리는 데이터 모델에 대한 다이어그램을 가질 거야.
And he will be introducing a new type of documentations. So we're going to have a diagram about the data model.
26:49:05
우리는 데이터 사전을 구축할 거야. 거기서 데이터 모델을 설명할 수 있어. 물론 데이터 흐름 다이어그램도 확장할 거야.
We're going to build a data dictionary where we can describe the data model. And of course, we're going to extend the data flow diagram.
26:49:11
이것이 우리의 과정이야. 이것들이 우리가 코드 레이어를 구축하기 위해 할 주요 단계들이야.
So this is our process. Those are the main steps that we will do in order to build the code layer.
26:49:20
좋아, 데이터 모델링이 정확히 무엇인지? 보통 소스 시스템은 원시 데이터를 제공할 거야.
Okay, so what is exactly data modeling? Usually, the source system is going to deliver for you raw data.
26:49:25
조직화된, 엉망인, 현재 상태에서는 그리 유용하지 않은 데이터야.
An organized, messy, not very useful in its current states.
26:49:30
하지만 이제 데이터 모델링은 이 원시 데이터를 가져와서 의미 있는 방식으로 조직하고 구조화하는 과정이야.
But now the data modeling is the process of taking this raw data and then organize it and structure it in meaningful way.
26:49:38
우리가 하는 것은 데이터를 고객, 주문, 제품과 같은 새로운 친숙하고 이해하기 쉬운 객체에 넣는 거야.
So what we are doing, we are putting the data in a new, friendly and easy to understand objects like customers, orders, products.
26:49:46
각 객체는 특정 정보에 집중하고 있어. 그리고 매우 중요한 것은 우리는 이 객체들 간의 관계를 설명할 거야.
Each one of them is focused on specific information. And what is very important is we're going to describe the relationship between those objects.
26:49:53
그래서 그들을 선으로 연결하는 거야. 오른쪽에 구축한 것을 우리는 논리적 데이터 모델이라고 불러.
So by connecting them using lines. So what you have built on the right side, we call it logical data model.
26:49:59
왼쪽과 비교하면 데이터 모델이
If you compare it to the left side you can see the data model makes
26:50:02
우리 데이터와 그 관계를 이해하기 쉽게 만들어 줍니다.
it really easy to understand our data and the relationship the
26:50:05
이제 데이터 모델링에는 세 가지 다른 단계가 있습니다.
processes behind them now in data modeling we have three different stages or
26:50:09
첫 번째 단계는 개념적 데이터 모델입니다. 여기서의 초점은
let's say three different ways on how to draw a data model the
26:50:12
첫 번째 단계는 개념적 데이터 모델입니다. 여기서 초점은
first stage is the conceptual data model here the focus
26:50:15
제품이 있으며, 세부 사항에 대해서는 전혀 다루지 않습니다.
is only on the entity so we have customers orders
26:50:19
상자 안의 열이나 속성을 지정하지 않습니다. 우리는 단지
products and we don't go in details at all so we don't specify
26:50:22
우리가 가진 엔티티가 무엇인지에 집중하고, 그들 간의
any columns or attributes inside those boxes we just
26:50:25
관계도 마찬가지입니다. 그래서 개념적 데이터
want to focus what are the entities that we have and as
26:50:28
모델은 세부 사항에 전혀 집중하지 않고 단지
well the relationship between them so the conceptual data
26:50:31
전체적인 그림을 제공합니다. 그래서 우리가 만들 수 있는 두 번째 데이터 모델은
model don't focus at all on the details it just
26:50:34
논리적 데이터 모델이며, 여기서 우리는 명시하기 시작합니다.
gives the big picture so the second data model that we can
26:50:37
우리가 찾을 수 있는 다양한 열이 무엇인지에 대해
build is the logical data model and here we start specifying
26:50:41
우리가 찾을 수 있는 다양한 열은 무엇인가요
what are the different columns that we can find in
26:50:44
각 엔티티마다 고객 ID, 이름, 성 등과 같은 열이 있으며, 이러한 엔티티 간의 관계를 그리며 어떤 열이 기본 키인지 명확히 합니다.
each entity like we have the customer id the first name last name and and so on and we still draw the relationship between those entities and as well we make it clear which columns are the primary key and so on.
26:50:54
보시다시피 여기에는 더 많은 세부 정보가 있지만, 각 열에 대한 세부 정보를 많이 설명하지 않으며, 이러한 테이블을 데이터베이스에 어떻게 저장할지에 대해서는 걱정하지 않습니다.
So as you can see we have here more details but one thing we don't describe a lot of details for each column and we are not worried how exactly we can store those tables in the database.
26:51:05
세 번째이자 마지막 단계는 물리적 데이터 모델입니다. 이것은 데이터베이스에 생성하기 전에 모든 것이 준비되는 곳입니다.
Third and last stage we have the physical data model. This is where everything gets ready before creating it in the database.
26:51:11
여기에서는 각 열에 대한 데이터 유형, 각 데이터 유형의 길이 및 기타 많은 데이터베이스 기술과 세부 정보를 추가해야 합니다.
So here you have to add all the technical details like adding for each column the data types and the length of each data type and many other database techniques and details.
26:51:22
다시 말해, 개념적 데이터 모델을 보면 큰 그림을 제공합니다.
So again, if you look to the conceptual data model, it gives us the big picture.
26:51:25
논리적 데이터 모델에서는 우리가 필요한 데이터의 세부 사항을 파고듭니다.
And in the logical data model, we dive into details of what data we need.
26:51:29
물리적 레이어 모델은 데이터베이스 구현을 위한 모든 것을 준비합니다.
And the physical layer model prepares everything for the implementation in the database.
26:51:34
솔직히 말해서, 제 프로젝트에서는 개념적 및 논리적 데이터 모델만 그립니다. 물리적 데이터 모델을 그리거나 구축하는 데는 많은 노력과 시간이 필요합니다.
And to be honest, in my projects, I only draw the conceptual and the logical data model because drawing and building the physical data model needs a lot of efforts and time.
26:51:44
그리고 Databricks와 같은 많은 도구들이 이러한 모델을 자동으로 생성합니다.
and there are many tools like in Databricks, they automatically generate those models.
26:51:49
따라서 이 프로젝트에서 우리가 할 일은 골드 레이어에 대한 논리적 데이터 모델을 그리는 것입니다.
So in this project, what we're going to do, we're going to draw the logical data model for the gold layer.
26:51:58
좋습니다, 따라서 분석과 특히 데이터 웨어하우징 및 비즈니스 인텔리전스를 위해 보고 및 분석에 최적화된 특별한 데이터 모델이 필요합니다.
All right, so now for analytics and especially for data warehousing and business intelligence, we need a special data model that is optimized for reporting and analytics,
26:52:07
그리고 그것은 유연하고 확장 가능하며 이해하기 쉬워야 합니다. 이를 위해 두 가지 특별한 데이터 모델이 있습니다.
and it should be flexible, scalable, and as well, easy to understand. And for that, we have two special data models.
26:52:13
첫 번째 데이터 모델은 스타 스키마입니다. 중앙에 사실 테이블이 있고 그 주위에 차원이 있습니다.
The first type of data model, we have the star schema. It has a central fact table in the middle and surrounded by dimensions.
26:52:20
사실 테이블은 거래, 이벤트를 포함하고 차원은 설명 정보를 포함합니다.
The fact table contains transactions, events, and the dimensions contains descriptive informations.
26:52:26
그리고 중앙의 사실 테이블과 그 주위의 차원 간의 관계는 별 모양을 형성합니다.
And the relationship between the fact table in the middle and the dimensions around it forms like a star shape.
26:52:32
그래서 우리는 이것을 스타 스키마라고 부릅니다. 그리고 우리는 눈송이 스키마라는 또 다른 데이터 모델이 있습니다. 이는 스타 스키마와 매우 유사합니다.
And that's why we call it star schema. And we have another data model called snowflake schema. It looks very similar to the star schema.
26:52:38
그래서 우리는 다시 중앙에 사실이 있고 그 주위에 차원이 있습니다.
So we have again the fact in the middle and surrounded by dimensions.
26:52:42
하지만 큰 차이점은 차원을 더 작은 하위 차원으로 나눈다는 것입니다.
But the big difference is that we break the dimensions into smaller sub dimensions.
26:52:48
이 데이터 모델의 형태는 차원을 확장할 때 눈송이처럼 보이게 됩니다.
And the shape of this data model, as you are extending the dimensions, it's going to look like a snowflake.
26:52:54
이제 나란히 비교해보면 스타 스키마가 더 쉬워 보인다는 것을 알 수 있습니다. 그래서 일반적으로 이해하기 쉽고 쿼리하기도 쉽습니다.
So now if you compare them side by side, you can see that the star schema looks easier, right? So it is usually easy to understand, easy to query.
26:53:01
이는 분석가에게 정말 완벽합니다. 하지만 한 가지 문제가 있습니다.
It is really perfect for analyzers. But it has one issue with that.
26:53:05
차원에는 중복이 있을 수 있으며 시간이 지남에 따라 차원이 커질 수 있습니다.
The dimension might contain duplicates and your dimensions get bigger with the time.
26:53:09
이제 눈송이와 비교하면 스키마가 더 복잡하다는 것을 알 수 있습니다.
Now if you compare it to the snowflake you can see the schema is more complex.
26:53:13
그래서 눈송이에서 무언가를 쿼리하려면 많은 지식과 노력이 필요합니다.
So you need a lot of knowledge and efforts in order to query something from the snowflake.
26:53:18
하지만 여기서 주요 장점은 정규화에 있습니다. 중복을 작은 테이블로 나누면 저장소를 최적화할 수 있습니다.
But the main advantage here comes with the normalization as you are breaking those redundancies in small tables you can optimize the storage.
26:53:26
하지만 솔직히 누가 저장소를 신경 쓰겠습니까? 그래서 이 프로젝트에서는 스타 스키마를 사용하기로 선택했습니다. 이는 매우 일반적으로 사용됩니다.
But to be honest who care about the storage? So for this project I have chosen to use the star schema because it is very commonly used.
26:53:32
보고서 작성에 완벽합니다. 예를 들어 Power BI를 사용할 때 저장소에 대해 걱정할 필요가 없으므로 이 모델을 채택하여 우리의 골드 레이어를 구축할 것입니다.
Perfect for reporting like for example if you are using Power BI and we don't have to worry about the storage so that's why we're gonna adopt this model to build our gold layer
26:53:46
좋습니다. 이제 이러한 데이터 모델에 대해 한 가지 더 말씀드리겠습니다. 그것들은
okay so now one more thing about those data models is that they contain
26:53:49
두 가지 유형의 테이블, 사실과 차원을 포함합니다. 그래서 제가 말할 때
two types of tables fact and dimensions so when i say
26:53:52
이것은 사실 테이블이거나 차원 테이블입니다. 차원에는
this is a fact table or a dimension table well the dimension contains
26:53:56
설명 정보나 카테고리가 포함되어 데이터에 대한 일부 맥락을 제공합니다. 예를 들어 제품 정보는
descriptive informations or like categories that gives
26:53:59
제품 이름, 카테고리, 하위 카테고리 등이 있습니다. 이것은
some context to your data for example a product info you
26:54:03
제품을 설명하는 테이블과 같습니다.
have product name category subcategories and so on this
26:54:06
우리는 이것을 차원이라고 부르지만, 반면에 사실이 있습니다.
is like a a table that is describing the products
26:54:09
사실은 거래와 같은 이벤트입니다. 그들은
and this we call it dimension but in the other hand we have facts
26:54:12
세 가지 중요한 정보를 포함합니다. 첫째, 여러 개가 있습니다.
they are events like transactions they contain
26:54:15
세 가지 중요한 정보 첫째, 여러 가지가 있습니다.
three important informations first you have multiple
26:54:18
여러 차원에서 아이디어가 있습니다. 그러면
ideas from multiple dimensions then we have
26:54:21
날짜 정보와 같은 것들, 거래가 언제
like date informations like when the transaction
26:54:24
또는 사건이 발생했는지에 대한 것입니다. 세 번째 유형의 정보는 측정값과 숫자입니다. 그러므로 이 세 가지 유형의 데이터가 하나의 테이블에 있다면, 이것은 사실입니다.
or the event did happen and the third type of information you're gonna have like measures and numbers so if you see those three types of data in one table then this is a fact
26:54:34
따라서 얼마나 많은지 또는 얼마인지를 답하는 테이블이 있다면, 이것은 사실입니다.
So if you have a table that answers how much or how many, then this is a fact.
26:54:39
하지만 누가, 무엇을, 어디서를 답하는 테이블이 있다면, 이것은 차원 테이블입니다.
But if you have a table that answers who, what, where, then this is a dimension table.
26:54:44
그래서 이것이 차원 테이블과 사실 테이블입니다. 좋아요, 친구들.
So this is what dimension and fact tables. All right, my friends.
26:54:52
지금까지 동상 계층과 은 계층에서는 비즈니스에 대한 논의가 없었습니다.
So, so far in the bronze layer and in the silver layer, we didn't discuss anything about the business.
26:54:56
그래서 동상과 은은 매우 기술적이었습니다. 우리는 데이터 수집에 집중하고 있습니다.
So the bronze and silver were very technical. We are focusing on data ingestion.
26:55:01
우리는 데이터의 품질을 정리하는 데 집중하고 있습니다. 하지만 여전히 테이블은 소스 시스템에 매우 지향적입니다.
We are focusing on cleaning up the data quality of the data. But still, the tables are very oriented to the source system.
26:55:08
이제 신의 계층에서 재미있는 부분이 시작됩니다. 우리는 소스의 전체 데이터 모델을 깨뜨릴 것입니다.
Now comes the fun part in the God layer, where we're going to go and break the whole data model of the sources.
26:55:14
우리는 비즈니스 보고 및 분석을 위해 소비하기 쉬운 완전히 새로운 것을 만들 것입니다.
So we're going to create something completely new to our business that is easy to consume for business reporting and analysis.
26:55:21
여기서 비즈니스와 프로세스에 대한 명확한 이해가 매우 중요합니다.
And here it is very important to have a clear understanding of the business and the processes.
26:55:26
이 단계에서 이미 알고 있지 않다면, 프로세스 전문가와 도메인 전문가를 만나 시간을 투자해야 합니다.
And if you don't know it already at this phase, you have really to invest time by meeting maybe process experts, the domain experts, in order to have clear understanding what we are talking about in the data.
26:55:37
이제 우리가 할 일은 소스 시스템에 숨겨진 비즈니스 객체를 감지하는 것입니다.
So now what we're going to do, we're going to try to detect what are the business objects that are hidden in the source systems.
26:55:44
이제 가서 탐색해 봅시다. 좋아요, 새로운 데이터 모델을 구축하기 위해서는 먼저 원래 데이터 모델을 이해해야 합니다.
So now let's go and explore that. All right, now in order to build a new data model, I have to understand first the original data model.
26:55:51
우리가 가진 주요 비즈니스 객체는 무엇인가요? 사물들은 서로 어떻게 관련되어 있나요?
What are the main business objects that we have? How things are related to each other?
26:55:55
이것은 새로운 모델을 구축하는 데 매우 중요한 과정입니다. 그래서 제가 보통 하는 것은 모든 테이블에 레이블을 붙이는 것입니다.
And this is a very important process in building a new model. So now what I usually do, I start giving labels to all those tables.
26:56:02
여기에서 도형으로 가서 레이블을 검색해 봅시다.
So if we go to the shapes over here, let's go and search for label.
26:56:06
더 많은 아이콘으로 가면, 여기에서 이 레이블을 가져올 것입니다. 그래서 드래그 앤 드롭하세요.
And if we go to more icons, I'm going to go and take this label over here. So drag and drop it.
26:56:11
그런 다음 글꼴 크기를 늘리겠습니다. 20으로 하고 굵게 하겠습니다. 조금 더 크게 만듭니다.
And then I'm going to go and increase maybe the size of the font. So let's go with 20 and bold. Just make it a little bit bigger.
26:56:18
이 데이터 모델을 보면, CRM과 ARP에 제품 정보가 있다는 것을 알 수 있습니다.
So now by looking to this data model, we can see that we have product informations in the CRM and as well in the ARP.
26:56:25
그리고 고객 정보와 거래 테이블도 있습니다. 이제 제품에 집중해 봅시다.
And then we have like customer informations and transactional table. So now let's focus on the products.
26:56:30
제품 정보는 여기 있습니다. 현재 및 역사적 제품 정보가 있습니다.
So the product information is over here. We have here the current and the history product informations.
26:56:36
여기에서 제품에 속하는 카테고리가 있습니다. 그래서 우리의 데이터 모델에는 제품이라는 것이 있습니다. 그래서 이 레이블을 만들어 봅시다.
And here we have the categories that belong to the products. So in our data model, we have something called products. So let's go and create this label.
26:56:43
제품이 될 것입니다. 그리고
It's going to be the product. and
26:56:46
스타일에 색상을 지정해 보겠습니다.
so let's go and give it a color to the style let's pick
26:56:49
예를 들어 빨간색을 선택하고 이 테이블 아래에
for example the red one now let's go and move
26:56:52
이 테이블에 해당하는 레이블을 붙이겠습니다.
this label and put it beneath this table over here with
26:56:55
이 테이블이 제품이라는 객체에 속한다고 표시하겠습니다.
that i have like a label saying this table belongs
26:56:59
여기 있는 다른 테이블에도 같은 작업을 하겠습니다.
to the objects called products now i'm going to do the same
26:57:02
이 테이블을 제품에 태그하여 쉽게 확인할 수 있도록 하겠습니다.
thing for the other table over here so i'm going to go and tag
26:57:05
고객에 대한 많은 정보가 있습니다. 생일과 국가도 포함되어 있습니다.
this table to the product as well so that i can see easily which tables from the sources thus has information about that product business object All right, now moving on, we have here a table called customer information.
26:57:17
고객에 대한 많은 정보가 있으며, 생일과 국가도 포함되어 있습니다.
So we have a lot of information about the customer. We have as well in the ARP customer information where we have the birthday and the country.
26:57:24
이 세 개의 테이블은 고객 객체와 관련이 있습니다. 그래서 고객이라고 부르겠습니다.
So those three tables has to do with the object's customer. So that means we're going to go and label it like that. So let's call it customer.
26:57:32
그에 대해 다른 색상을 선택하겠습니다. 녹색으로 가겠습니다.
And I'm going to go and pick a different color for that. Let's go with the green.
26:57:36
이 테이블을 이렇게 태그하고 다른 테이블도 같은 방식으로 하겠습니다.
So I will tag this table like this and the same thing for the other tables.
26:57:41
두 번째 테이블과 세 번째 테이블을 복사하여 태그하겠습니다.
So copy tag the second table and the third table.
26:57:45
어떤 테이블이 어떤 비즈니스 객체에 속하는지 쉽게 알 수 있습니다.
Now it is very easy for me to see which table to belong to which business objects.
26:57:50
여기에서 최종 테이블이 있으며, 판매 및 주문에 대한 테이블입니다.
And now we have the final table over here and only one table about the sales and orders.
26:57:55
여기에는 관련 정보가 없습니다. 그래서 이 테이블은 간단하게 판매라고 부르겠습니다.
In the ARB we don't have any information about that. So this one is going to be easy. Let's call it sales.
26:58:01
이곳으로 이동하고 색상을 바꿔 보겠습니다.
And let's move it over here and as well maybe change the color of that to for example this color over here.
26:58:08
이 단계는 데이터 모델을 구축하는 데 매우 중요합니다.
Now this step is very important by building any data model in the gold layer. It gives you a big picture about the things that you are going to module.
26:58:15
이제 다음 단계는 객체를 단계별로 구축하는 것입니다.
So now the next step is that we're going to go and build those objects step by step. So let's start with the first objects with our customers.
26:58:22
여기에서 세 개의 테이블이 있으며, CRM부터 시작하겠습니다.
So here we have three tables and we're going to start with the CRM. So let's start with this table over here. All right.
26:58:27
이로써 우리의 비즈니스 객체가 무엇인지 알게 되었고 이 작업은 완료되었습니다.
So with that, we know what are our business objects and this task is done.
26:58:31
이제 다음 단계에서는 다시 스케일로 돌아가 데이터 통합을 시작하겠습니다.
And now in the next step, we're going to go back to a scale and start doing data integrations and building completely new data model.
26:58:39
이제 최종 단계입니다. 보고 및 분석을 위해 데이터를 제공할 것입니다.
So let's go and do that. Now let's have a quick look to the gold layer specifications.
26:58:47
뷰를 사용할 것입니다. 즉, 저장 프로시저나 로드 프로세스는 없습니다.
So this is the final stage. We're going to provide data to be consumed by reporting and analytics. And this time we will not be building tables.
26:58:54
우리가 하는 모든 것은 데이터 변환뿐입니다.
We will be using views. So that means we will not be having like stored procedure or any load process to the gold layer.
26:59:01
우리가 하는 모든 것은 데이터 변환입니다. 데이터 변환의 초점은 데이터 통합, 집계, 비즈니스 로직 등이 될 것입니다.
All what we are doing is only data transformation. And the focus of the data transformation is going to be data integration, aggregation, business logic, and so on.
26:59:09
이번에는 새로운 데이터 모델을 도입할 것입니다. 우리는 스타 스키마를 사용할 것입니다. 이것이 골드 레이어의 사양입니다.
And this time, we're going to introduce a new data model. We will be doing star schema. So those are the specifications for the gold layer.
26:59:17
이번에는 실버 레이어에서 데이터를 선택하고 브론즈 레이어에서 선택하지 않도록 할 것입니다.
And this is our scope. So this time, we make sure that we are selecting data from the silver layer, not from the bronze.
26:59:23
브론즈 레이어는 데이터 품질이 좋지 않고 실버 레이어는 모든 것이 준비되고 정리되어 있습니다.
Because the bronze has bad data quality and the silver is everything is prepared and cleaned up.
26:59:29
골드 레이어를 구축하기 위해 실버 레이어를 목표로 할 것입니다.
In order to build the gold layer, we're going to be targeting the silver layer.
26:59:32
그래서 select star from으로 시작하고 실버 CRM 고객 정보를 가져가겠습니다.
So let's start with select star from and we're going to go to the silver CRM customer info.
26:59:38
이제 우리가 필요한 열을 선택하겠습니다. ID, 키, 이름이 있습니다.
So let's go and hit execute. And now we're going to go and select the columns that we need to be presented in the gold layer.
26:59:45
메타데이터 정보를 가져오지 않을 것입니다. 이것은 ID에만 해당합니다.
So let's start selecting the columns that we want. We have the ID, the key, the first name.
26:59:56
완벽한 실버, 다음 단계는 이 테이블에 별칭을 주는 것입니다.
I will not go and get the metadata information. This only belongs to the ID.
27:00:00
그래서 ci라고 부르겠습니다. 그리고
silver perfect the next step is that i'm gonna go and give this table
27:00:03
이 별칭에서 선택하고 있는지 확인하겠습니다.
an alias so let's go and call it ci and i'm
27:00:06
나중에 이 테이블을 다른 테이블과 조인할 것이기 때문입니다.
gonna make sure that we are selecting from this alias
27:00:09
이 테이블을 다른 테이블과 조인할 것입니다.
because later we're gonna go and join this table with other
27:00:12
두 번째 테이블로 이동하여 생일 정보를 가져가겠습니다.
tables so something like this so we're gonna go with those columns now
27:00:16
이제 다른 시스템으로 점프해야 하고 ci id와 고객 키로 데이터를 조인해야 합니다.
let's move to the second table let's go and get the birthday
27:00:19
이제 다른 테이블과 데이터를 조인해야 합니다.
information so now we're gonna jump to the other system and we have to join the data by the ci id together with the customer key
27:00:26
여기서 내부 조인을 사용하지 않으려고 합니다.
so now we have to go and join the data with another table and
27:00:29
다른 테이블에 고객에 대한 모든 정보가 없으면
here i try to avoid using the inner join because
27:00:32
고객을 잃을 수 있으므로 항상 마스터 테이블에서 시작하세요.
if the other table doesn't have all the information about the customers i
27:00:36
다른 테이블에 고객에 대한 모든 정보가 없으면
might lose customers so always start with the master table
27:00:40
정보를 얻기 위해 다른 테이블과 조인하면
and if you join it with any other table in order to get
27:00:43
항상 내부 조인을 피하려고 하세요.
informations try always to avoid the inner join because
27:00:46
다른 소스에 모든 고객이 없을 수 있습니다.
the other source might not have all the customers and
27:00:49
내부 조인을 하면 고객을 잃을 수 있으므로 마스터 테이블에서 시작하는 경향이 있습니다.
if you do inner join you might lose customers so i tend to start
27:00:52
마스터 테이블에서 시작한 다음 나머지는 왼쪽 조인에 관한 것입니다.
from the master table and then everything else is about
27:00:56
왼쪽 조인, 그래서 왼쪽 조인 실버 ERP를 하겠습니다.
the left join so i'm gonna say left join silver erp
27:00:59
고객 AZ12, 그래서 별칭을 주겠습니다.
customer az12 so let's give it the alias
27:01:02
CA, 이제 테이블을 조인해야 하니까
ca and now we have to join the tables so it's gonna be
27:01:05
첫 번째 테이블에서 CE로
by ce from the first table it's gonna be the
27:01:08
고객 키가 CA와 같고
customer key equal to ca and we
27:01:12
이제 CI ID를 가지고 있습니다. 물론 일치하는 데이터를 가져올 것입니다.
have the ci id now of course we're gonna get matching data
27:01:15
실버 레이어를 확인했기 때문에, 하지만 준비하지 않았다면
because we checked the silver layer but if we haven't prepared
27:01:18
실버 레이어의 데이터를 준비해야 합니다.
the data in the silver layer we have to do here preparation step
27:01:21
테이블을 조인하기 위해서, 하지만 그럴 필요는 없습니다. 왜냐하면
in order to join the tables but we don't have to do that because that
27:01:24
실버 레이어에서 사전 단계였기 때문에, 이제 체계적인 것을 볼 수 있습니다.
was a pre-step in the silver layer so now you can see the systematic
27:01:28
브론즈, 실버, 골드에서 우리가 가지고 있는 것, 이제 테이블을 조인한 후
that we have in this bronze silver gold so now after
27:01:31
필요한 정보를 선택해야 합니다.
joining the tables we have to go and pick the information that we need
27:01:34
두 번째 테이블에서 생년월일을 가져와야 합니다.
from the second table which is the birth dates so
27:01:38
생년월일과 이 테이블에서 성별 정보도 있습니다. 그래서 우리가 두 번째 테이블에서 필요한 모든 것입니다.
b dates and as well from this table there is another nice information it is the gender information so that's all what we need from the second table let's go and check the third table
27:01:49
세 번째 테이블은 위치 정보에 관한 것입니다.
so the third table is about the location information the
27:01:53
국가와 CI ID로 테이블을 연결합니다.
countries and as well we connect the tables by the ci id
27:01:56
키로, 그래서 가서 하겠습니다. 이렇게 말할 것입니다.
with the key so let's go and do that we're gonna say as
27:01:59
왼쪽 조인 실버 ERP로
well left join silver erp
27:02:02
위치, 그리고 이름을 LA로 주겠습니다.
location and i'm gonna give it the name la and
27:02:05
그런 다음 키를 조인해야 합니다. 같은 것이 될 것입니다.
then we have to join why the keys the same thing it's gonna be
27:02:08
CI 고객 키가 LA와 같고
ci customer key equal to la
27:02:12
CI ID를 다시 준비했습니다.
ci id again we have prepared those ids
27:02:15
실버 레이어의 키와 함께 조인이 작동해야 합니다.
and keys in the silver layer so the joint should be working
27:02:18
이제 두 번째 테이블에서 데이터를 선택해야 합니다.
now we have to go and pick the data from the second table
27:02:21
여기서 무엇이 있는지, ID, 국가와
so what do we have over here we have the id the country and
27:02:24
메타데이터 정보를 가져옵니다. 그러니 국가를 가져가 보겠습니다.
the metadata information so let's go and just get the country
27:02:27
완벽합니다. 이제 이를 통해 모든 것을 연결했습니다.
perfect so now with that we have joined all the
27:02:30
세 개의 테이블을 선택하고 모든 열을 선택했습니다.
three tables and we have picked all the columns that
27:02:34
이 객체에서 원하는 모든 열을 선택했습니다. 다시 말해, 여기서 이 테이블과 저 테이블을 연결했습니다.
we want in this object so again by looking over here we have joined this table with this one and this one so with that we have collected all the customer
27:02:42
그래서 우리는 두 소스 시스템에서 고객 정보를 수집했습니다.
information that we have from the two source systems
27:02:45
좋습니다. 이제 쿼리를 실행하여 모든 것이 올바른지 확인하겠습니다.
okay so now let's go and query in order to make sure that we
27:02:48
모든 것이 올바른지 확인하고 조인이 올바른지 이해하려면
have everything correct and in order to understand that your joints
27:02:51
세 개의 열을 주의 깊게 살펴봐야 합니다.
are correct you have to keep your eye in those three columns
27:02:54
데이터를 받고 있다면 조인이 올바르게 이루어지고 있다는 뜻입니다.
so if you are seeing that you are getting data that means
27:02:58
하지만 많은 널 값이나 데이터가 전혀 없다면
you are doing the joints correctly but if
27:03:01
조인이 잘못되었다는 뜻입니다. 하지만 지금은
you are seeing a lot of nulls or no data at all that
27:03:04
작동하는 것 같고, 제가 하는 또 다른 확인은
means your joints are incorrect but now it looks
27:03:07
첫 번째 테이블에 중복이 없다는 것입니다. 그렇다면
for me it is working and another check that I do
27:03:10
여러 번 조인을 수행한 후에 중복이 발생할 수 있습니다.
is that if your first table has no duplicates what
27:03:13
이제 중복이 발생하기 시작할 수 있습니다. 왜냐하면
could happen at that after doing multiple joins you might
27:03:17
테이블 간의 관계가 명확하지 않기 때문입니다.
now start getting duplicates because the relationship between
27:03:20
일대일 관계가 아닌 경우, 일대다 또는 다대다 관계가 있을 수 있습니다.
those tables is not clear one-to-one you might get
27:03:23
이 단계에서 제가 보통 하는 확인은 중복이 없는지 확인하는 것입니다.
like one-to-many relationship or many-to-many relationships so
27:03:26
결과에서 중복이 없도록 해야 합니다.
now the check that I usually do at this stage is that I have to
27:03:29
그래서 같은 고객에 대해 여러 행이 없도록 합니다.
make sure that I don't have duplicates from their results
27:03:33
그렇게 하기 위해서 빠른 그룹화를 수행합니다.
so we don't have like multiple rows for the same customer
27:03:36
그래서 고객별로 데이터를 그룹화할 수 있습니다.
so in order to do that we go and do a quick group
27:03:39
ID로 그룹화한 다음, 카운트를 수행합니다.
by so we can group by the data by the customer
27:03:42
이 서브 쿼리에서 카운트를 수행합니다. 이게 전체 서브
id and then we do the counts from
27:03:46
쿼리입니다. 그 후에 우리는 진행할 것입니다.
this sub query so this is the whole sub
27:03:49
쿼리 후에 우리는 가서
query and then after that we're going to go
27:03:52
고객 ID로 그룹화하고 카운트가 1보다 큰 것을 말합니다.
and say group by the customer id and then we say having counts higher than one
27:04:00
이 쿼리는 기본 키에 중복이 있는지 확인하려고 했습니다.
So this query actually tried to find out whether we have any duplicates in the primary key.
27:04:06
이제 실행해 보겠습니다. 중복이 없습니다.
So let's go and execute it. We don't have any duplicates.
27:04:10
고객 정보와 모든 테이블을 조인한 후, 테이블이 문제를 일으키지 않았고 내 데이터를 중복하지 않았다는 의미입니다.
And that means after joining all those tables with the customer info, those tables didn't cause any issues and didn't duplicate my data.
27:04:18
이것은 올바른 방향에 있는지 확인하는 매우 중요한 점검입니다.
So this is very important check to make sure that you are in the right way. All right.
27:04:23
중복에 관해서는 모든 것이 괜찮다는 의미입니다. 걱정할 필요가 없습니다. 이제 통합 문제가 있습니다.
So that means everything is fine about the duplicates. We don't have to worry about it. Now we have here an integration issue.
27:04:30
다시 실행해 보겠습니다. 데이터가 어떻게 되는지 보겠습니다.
so let's go and execute it again and now if you look to the data we have
27:04:33
성별 정보의 두 출처가 있습니다. 하나는
two sources for the gender informations one comes from
27:04:36
CRM에서 나오고 다른 하나는 ERP에서 나옵니다.
the crm and another one come from the erp so
27:04:39
이것에 대해 우리가 무엇을 할 것인지가 문제입니다.
now the question is what we're gonna do with this well we have to do
27:04:42
데이터 통합을 해야 합니다. 먼저 어떻게 하는지 보여드리겠습니다.
data integration so let me show you how i do it first
27:04:45
새 쿼리를 만들고 다른 모든 것을 제거하겠습니다.
i go and have a new query and then i'm gonna go i remove
27:04:49
두 가지 정보만 남기고 통합에 집중하기 위해 DISTINCT를 사용하겠습니다.
all other stuff and i'm gonna leave only those two
27:04:52
그래서 하나와 둘을 정렬해 보겠습니다.
informations and use a distinct just to focus on the integration and let's go and and execute it and maybe as well to do an order
27:04:59
다시 실행해 보겠습니다. 이제 모든 시나리오가 있습니다.
by so let's do one and two let's go and execute
27:05:03
때때로 일치하는 경우가 있습니다. 첫 번째 테이블에서
it again so now here we have all the scenarios and we
27:05:06
여성이고 다른 테이블에서도 여성입니다. 그러나 때때로
can see sometimes there is a matching so from the first table
27:05:09
두 테이블이 서로 다른 정보를 제공하는 문제가 발생합니다.
we have female and the other table we have as well female but sometimes
27:05:12
첫 번째 테이블에서 데이터가 있는 시나리오입니다.
we have an issue like those two tables are giving different informations and the same thing over here so this is as well an issue different informations another
27:05:20
여기에는 여성이 있지만 다른 테이블에서는 사용할 수 없습니다.
scenario where we have a data from the first table like
27:05:23
문제가 아닙니다. 첫 번째 테이블에서 가져올 수 있습니다.
here we have the female but in the other table we have not available
27:05:26
정확히 반대의 시나리오도 있습니다.
well this is not a problem so we can get it from the first
27:05:29
첫 번째 테이블에서 데이터가 없지만 두 번째 테이블에서는 사용할 수 있습니다.
table but we have as well the exact opposite scenario where
27:05:33
여기서 왜 null이 발생하는지 궁금할 수 있습니다.
from the first table the data is not available but it is available
27:05:36
두 번째 테이블에서 데이터가 없다는 것을 이해할 수 있습니다. 실버 레이어에서 모든 누락된 데이터를 처리했으며, 모든 것을 사용할 수 없음으로 대체했습니다. 그럼에도 불구하고 왜 여전히 null이 발생하고 있을까요?
from the second table and now here you might wonder why i'm getting a null over here we did handle all the missing data in the silver layer and we replace everything with not available So why we are still getting a null?
27:05:48
이 null은 테이블에서 직접 발생하지 않습니다. 테이블을 조인하기 때문에 발생합니다.
This null doesn't come directly from the tables. It just comes because of joining tables.
27:05:54
즉, CRM 테이블에 있는 고객이 ARB 테이블에는 없다는 의미입니다.
So that means there are customers in the CRM table that is not available in the ARB table.
27:06:00
그리고 만약 일치하는 항목이 없다면, 어떤 일이 발생할까요? SQL에서 null을 받게 됩니다. 이 null은 일치하는 항목이 없다는 의미입니다.
And if there is like no match, what can happen? We will get a null from SQL. So this null means there was no match.
27:06:08
그래서 우리가 이 null을 받는 이유입니다. 이는 테이블의 내용에서 발생하는 것이 아닙니다. 그리고 이것은 물론 문제입니다.
And that's why we are getting this null. It is not coming from the content of the tables. And this is, of course, an issue.
27:06:14
하지만 이제 큰 문제는 이 두 시나리오에서 어떤 일이 발생할 수 있는가입니다. 우리는 데이터를 가지고 있지만, 서로 다릅니다.
But now the big issue, what can happen for those two scenarios here? We have the data, but they are different.
27:06:20
그리고 여기서 다시 전문가에게 물어봐야 합니다. 여기서 마스터는 무엇인가요? CRM 시스템인가요, 아니면 ARP인가요?
And here again, we have to ask the experts about it. What is the master here? Is it the CRM system or the ARP?
27:06:27
그들의 답변에 따르면, 고객 정보의 마스터 데이터는 CRM이라고 말할 수 있습니다.
And let's say from their answer, we're going to say the master data for the customer information is the CRM.
27:06:33
즉, CRM 정보가 ARP 정보보다 더 정확하다는 의미입니다.
So that means the CRM informations are more accurate than the ARP information.
27:06:38
그리고 이것은 물론 고객에 관한 것입니다. 그래서 이 시나리오에서 여성과 남성이 있을 때, 올바른 정보는 첫 번째 소스 시스템의 여성입니다.
And this is only about the customers, of course. So for this scenario where we have female and male, then the correct information is the female from the first source system.
27:06:47
여기에서도 마찬가지입니다. 그리고 여기에는 남성과 여성이 있습니다.
The same goes over here. And here we have like male and female.
27:06:50
그럼 올바른 것은 남성입니다. 왜냐하면 이 소스 시스템이 마스터이기 때문입니다. 자, 이제 이 비즈니스 규칙을 만들어 봅시다.
Then the correct one is the male because this source system is the master. OK, so now let's go and build this business rule.
27:06:58
우리는 평소처럼 케이스 승리로 시작할 것입니다. 그래서 첫 번째 매우 중요한 규칙은 CRM 시스템에서 성별 정보에 데이터가 있다면, 그것을 사용하라는 것입니다.
We're going to start as usual with the case win. So the first very important rule is if we have data in the gender information from the CRM system from the master, then go and use it.
27:07:08
그래서 우리는 CRM 테이블에서 성별 정보를 확인할 것입니다.
so we're gonna go and check the agenda information from the crm table
27:07:12
고객 성별이 같지 않다면
so customer gender is not equal to
27:07:15
사용할 수 없다는 것은 남성 또는
not available so that means we have a value male or
27:07:18
여성의 값이 있다는 의미입니다. 여기서 쉼표를 추가하겠습니다.
female let me just have here a comma like this then
27:07:21
무슨 일이 발생할 수 있는지 사용해야 합니다. 그래서 우리는 사용할 것입니다.
what can happen go and use it so we're gonna use
27:07:25
마스터 CRM에서의 값은
the value from the master crm is the
27:07:28
성별 정보의 마스터입니다. 그렇지 않으면 CRM 테이블에서 사용할 수 없다는 의미입니다.
master for gender info now otherwise that means it is not available from the crm table
27:07:37
그럼 두 번째에서 정보를 사용하고 가져와야 합니다.
then go and use and grab the information from the second
27:07:40
테이블에서 우리는 ca 성별이라고 말할 것입니다.
table so we're gonna say ca gender
27:07:43
하지만 이제 여기서 조심해야 합니다.
but now we have to be careful with this over here we
27:07:46
사용할 수 없도록 변환해야 하므로 우리는
have to convert it to not available as well so we're gonna use the
27:07:50
그러니까 이것이
cowlis so if this is a
27:07:53
null이면 사용하지 마세요
null then go and use the not available like this so
27:07:57
그게 다입니다. 끝내고 싶습니다
that's it let's have an end let me just push this
27:08:00
여기서 새로운 세대라고 부릅시다
over here so let's go and call it new gen
27:08:03
지금은 실행해 보겠습니다
for now let's go and execute it and let's go and
27:08:06
다양한 시나리오를 확인해 보겠습니다
check the different scenarios all those values over
27:08:09
여기 CRM 시스템의 데이터가 있습니다
here we have data from the crm system and
27:08:12
새로운 열에 잘 나타나 있습니다
this is as well represented in the new column but now
27:08:15
두 번째 부분의 데이터가 없습니다
for the second part we don't have data from the first system
27:08:18
두 번째 시스템에서 가져오려고 합니다
so we are trying to get it from the second system so
27:08:22
첫 번째는 사용할 수 없고 가져오려고 합니다
for the first one is not available and then we try to get it
27:08:25
두 번째 소스 시스템에서 가져오고 있습니다
from the second source system so now we are activating the else
27:08:28
null이므로 cowlis가 활성화됩니다
well it is null and with that the cowlis is activated
27:08:31
null을 사용 불가능으로 바꾸고 있습니다
and we are replacing the null with not available for
27:08:34
두 번째 시나리오에서도 성별 정보가 없습니다
the second scenario as well the first search system don't
27:08:38
그래서 두 번째에서 가져오고 있습니다
have the gender information that's why we are grabbing it from
27:08:41
세 번째도 정보가 없지만 가져옵니다
the second so with that we have a female and then the
27:08:44
두 번째 소스 시스템에서 남성을 가져옵니다
third one the same thing we don't have information but we get it
27:08:47
두 소스 시스템 모두에서 사용할 수 없습니다
from the second source system we have the male and the last one it
27:08:50
하나로 두 개의 서로 다른 소스 시스템을 통합하고 있습니다
is not available in both source systems that's why we are getting not available so with that as you can see we have a perfect new column where we are
27:08:58
이것이 바로 데이터 통합이라고 부르는 것입니다
integrating two different source system in one and
27:09:01
이 정보는 소스보다 훨씬 좋습니다
this is exactly what we call data integration this
27:09:05
CRM과 소스 ARP도 포함됩니다
piece of information it is way better than the source
27:09:08
더 풍부하고 더 많은 정보를 가지고 있습니다
crm and as well the source arp it
27:09:11
그래서 다양한 소스 시스템에서 데이터를 가져오려고 합니다
is more rich and has more information and this is
27:09:14
정보를 풍부하게 하기 위해 데이터 웨어하우스에서
exactly why we try to get data from different source system in
27:09:17
데이터 웨어하우스에서 풍부한 정보를 얻기 위해
order to get rich information in the data warehouse
27:09:20
그래서 우리는 좋은 논리를 가지고 있고, 보시다시피
so with that we have a nice logic and as you can see it's way
27:09:23
별도의 쿼리에서 분리하는 것이 더 쉽습니다.
easier to separate it in separate query in order first to
27:09:27
여기서 모든 것을 복사할 것입니다.
build the logic and then take it to the original query
27:09:30
우리의 쿼리로 돌아가서 그것들을 삭제할 것입니다.
so what i'm gonna do i'm just gonna go and copy everything from here
27:09:33
정보, 성별을 삭제하고
and go back to our query i'm gonna go and delete those
27:09:36
여기서 새로운 논리를 추가할 것입니다.
informations the gender and i will put our
27:09:40
이제 우리는 새로운 멋진 열을 가지고 있습니다.
new logic over here so a comma and let's go and execute
27:09:43
우리는 중복이 없고 통합된 데이터를 가지고 있습니다.
so with that we have our new nice column now with
27:09:46
코드 레이어의 규칙은 친숙한 이름을 사용하는 것입니다.
that we have very nice objects we don't have duplicates and we have integrated data together so we took three tables and we put it in one object now the next Next step of that, we're gonna go and give nice friendly names.
27:09:58
우리는 명명 규칙을 따르고 있는지 확인해야 합니다.
The rule in the code layer that to use friendly names. And not to follow the names that we get from the source system.
27:10:04
단계별로 진행합시다. 첫 번째는 고객 ID라고 부릅시다.
And we have to make sure that we are following the rules by the naming conventions. So we are following the snake case.
27:10:10
다음은 키를 사용하지 않고 고객 번호라고 부릅시다.
So let's go and do it step by step. For the first one, let's go and call it the customer ID.
27:10:15
그것들은 고객 번호입니다. 다음은 접두사 없이 이름을 부릅시다.
And then the next one, I will get rid of using keys and so on. I'm going to go and call it customer number.
27:10:21
다음은 성입니다. 그리고 결혼 상태가 있습니다.
Because those are customer numbers. Then for the next one, we're going to call it first name without using any prefixes.
27:10:30
정확한 이름을 사용하되 접두사는 제외합니다.
And the next one, last name. And we have here marital status.
27:10:36
이것은 운송 날짜라고 부릅시다.
So I will be using the exact name, but without that prefix. And here, we're just going to call it gender.
27:10:42
마지막은 국가입니다. 이제 실행합시다.
And this one, we're going to call it courier date. And this one, birth date.
27:10:48
우리는 고객 ID, 고객 번호, 이름, 성, 결혼 상태, 성별이 있습니다.
And the last one going to be the country. So let's go and execute it. Now, as you can see, the names are really friendly.
27:10:56
이름이 정말 좋고 이해하기 쉽습니다.
So we have customer ID, customer numbers, first name, last name, material status, gender.
27:11:01
첫 두 개는 함께 있는 것이 좋습니다.
So as you can see, the names are really nice and really easy to understand. Now, the next step, I'm going to think about the order of those columns.
27:11:08
여기서 가져와서 성 뒤에 두겠습니다.
So the first two, it makes sense to have it together. The first name, last name. Then I think the country is very important information.
27:11:14
이름, 성, 국가입니다. 관련 열을 함께 그룹화하는 것이 좋습니다.
So I'm going to go and get it from here and put it exactly after the last name. It's just nicer. So let's go and execute it again.
27:11:21
여기 성별 상태가 있고, 운송 날짜와 생일이 있습니다.
So the first name, last name, country. It's always nice to group up relevant columns together, right?
27:11:26
생일과 운송 날짜를 바꿀 것입니다.
So we have here the status of the gender and so on. And then we have the career date and the birth date.
27:11:31
나는 생년월일과 경력 날짜를 바꿀 생각이야. 경력 날짜보다 더 중요해. 이렇게.
I think I'm going to go and switch the birth date with the career date. It's more important than the career date. Like this.
27:11:38
여기서 쉼표를 잊지 마세요. 다시 실행하세요. 정말 멋져 보입니다. 이제 이 객체들에 대한 매우 중요한 결정이 있습니다.
And here not forget a comma. So execute again. So it looks wonderful. Now comes a very important decision about these objects.
27:11:45
이것이 사실 테이블인가요, 아니면 차원인가요? 우리가 배운 대로 차원은 객체에 대한 설명 정보를 담고 있습니다.
Is it a fact table or a dimension? Well, as we learned, dimensions hold descriptive information about an object.
27:11:52
그리고 보시다시피, 우리는 고객에 대한 설명이 있습니다. 그래서 모든 열이 그 고객 정보를 설명하고 있습니다.
And as you can see, we have here descriptions about the customers. So all those columns are describing that customer information.
27:12:00
여기에는 거래나 이벤트가 없습니다. 그리고 측정값도 없습니다.
And we don't have here like transactions and events. And we don't have like measures and so on.
27:12:05
그래서 우리는 이 객체가 사실이라고 말할 수 없습니다. 분명히 차원입니다.
So we cannot say this object is a fact. It is clearly a dimension.
27:12:09
그래서 우리는 이 객체를 차원 고객이라고 부를 것입니다.
So that's why we're going to go and call this object the dimension customer.
27:12:13
이제 새로운 차원을 만들 때 항상 차원에 대한 기본 키가 필요합니다.
Now, there is one thing that if you are creating a new dimension, you need always a primary key for the dimension.
27:12:19
물론, 우리는 여기에서 소스 시스템에서 가져온 기본 키에 의존할 수 있습니다.
Of course, we can go over here and depend on the primary key that we get from the source system.
27:12:24
하지만 때때로 기본 키가 없는 차원을 가질 수 있습니다.
But sometimes you can have like dimensions where you don't have like a primary key that you can count on.
27:12:29
그래서 우리가 해야 할 일은 데이터 웨어하우스에서 새로운 기본 키를 생성하는 것입니다.
So what we have to do is to go and generate a new primary key in the data warehouse.
27:12:35
그리고 그 기본 키를 우리는 대체 키라고 부릅니다. 대체 키는 각 레코드를 고유하게 만들기 위해 시스템에서 생성된 고유 식별자입니다.
And those primary keys, we call it surrogate keys. Surrogate keys are system generated unique identifier that is assigned to each record to make the record unique.
27:12:44
그것은 비즈니스 키가 아닙니다. 의미가 없고 비즈니스에서 아무도 그것에 대해 알지 못합니다.
It is not a business key. It has no meaning and no one in the business knows about it.
27:12:50
우리는 그것을 데이터 모델을 연결하기 위해서만 사용합니다.
We only use it in order to connect our data model.
27:12:53
이런 식으로 우리는 데이터 모델을 연결하는 방법에 대한 더 많은 제어를 가지며 항상 소스 시스템에 의존할 필요가 없습니다.
And in this way, we have more control on how to connect our data model and we don't have to depend always on the source system.
27:13:01
대체 키를 생성하는 방법에는 여러 가지가 있으며, DDL에서 정의하는 것과 같은 방법이 있습니다.
And there are different ways on how to generate surrogate keys, like defining it in the DDL.
27:13:06
또는 이 데이터에서 윈도우 함수의 행 번호를 사용할 수도 있습니다.
or maybe using the window function row number in this data
27:13:09
저는 간단한 솔루션으로 가서 사용할 것입니다.
warehouse i'm gonna go with a simple solution where we're gonna go and use
27:13:12
윈도우 함수를 사용하여 이 차원에 대한 회로 키를 생성하는 것은 매우 간단합니다. 우리는 행 번호를 사용하겠습니다.
the window function so now in order to generate a circuit key for this dimension what we're gonna do it is very simple so we're gonna say row number over
27:13:23
그리고 여기서 우리는 무언가에 따라 정렬해야 합니다.
and here we have to order by something you
27:13:26
경력 날짜나 고객 ID, 고객 번호 등 원하는 대로 정렬할 수 있지만, 이 예에서는 고객으로 정렬할 것입니다.
can order by the career date or the customer id or the customer number whatever you want but in this example i'm gonna go and order by the customer
27:13:35
우리는 모든 대체 키가 접미사로 키가 끝나는 명명 규칙을 따라야 합니다.
id so we have to follow the naming convention that
27:13:38
이제 정보를 쿼리하러 가겠습니다.
all surrogate keys with the key at the end as a suffix
27:13:41
시작할 때 고객 키가 있고 이것은
so now let's go and query those informations and as
27:13:44
여기에는 물론 중복이 없습니다.
you can see at the start we have a customer key and this is
27:13:47
여기에는 중복이 없는 시퀀스가 있습니다.
a sequence we don't have here of course any duplicates and
27:13:51
이 대체 키는 데이터 웨어하우스에서 생성됩니다.
now this surrogate key is generated in the data warehouse
27:13:54
이 키를 사용하여 연결할 것입니다.
and we're going to use this key in order to connect the
27:13:57
이제 우리의 쿼리가 준비되었습니다.
data model so now with that our query is ready and
27:14:00
마지막 단계는 객체를 생성하는 것입니다.
the last step is that we're gonna go and create the objects
27:14:03
모든 객체는 가상으로 생성될 것입니다.
and as we decided all the objects in the gold layer are gonna be a
27:14:07
뷰를 생성하겠습니다.
virtual one so that means we're gonna go and create a view so
27:14:10
뷰 이름은 gold dot입니다.
we're gonna say create view gold dot
27:14:13
차원 이름을 따릅니다.
dim so follow the naming convention stand for
27:14:16
고객 정보를 포함할 것입니다.
the dimension and we're gonna have the customers and then
27:14:19
모든 것이 준비되었습니다.
after that we have us so with that everything
27:14:22
이제 뷰로 가보겠습니다.
is ready let's go and execute it it was successful
27:14:26
첫 번째 객체를 확인할 수 있습니다.
let's go to the views now and you can see our first
27:14:29
고객 차원이 있습니다.
object so we have the dimension customers in the
27:14:32
이 새로운 객체의 품질을 확인하겠습니다.
gold layer now as you know me in the next step of that we're gonna go and
27:14:35
새로운 쿼리를 가져오겠습니다.
check the quality of this new objects so let's go and
27:14:39
고객 뷰를 선택하겠습니다.
have a new query so select star from
27:14:42
우리의 관점에서 그들은 고객입니다.
our view them customers and
27:14:46
이제 우리는 모든 것이 이렇게 올바른 위치에 있는지 확인해야 합니다.
now we have to make sure that everything in the right position like this and
27:14:49
이제 우리는 고유성 등 다양한 검사를 수행할 수 있습니다.
now we can do different checks like the uniqueness and so on
27:14:53
하지만 성별 정보에 대해 걱정됩니다.
but i'm worried about the gender information so
27:14:56
모든 값의 구별을 해보겠습니다. 보시다시피
let's go and have a distinct of all values so as you can see
27:14:59
완벽하게 작동하고 있습니다. 우리는 오직 여성, 남성만 있습니다.
it is working perfectly we have only female male and
27:15:02
사용할 수 없는 것도 있습니다. 그래서 그게 전부입니다.
not available so that's it with that we have
27:15:05
우리의 첫 번째 새로운 차원입니다. 알겠죠?
our first new dimension okay
27:15:11
친구들, 이제 두 번째 객체를 만들어 봅시다.
friends so now let's go and build the second object we
27:15:14
제품이 있으니, 보시다시피 제품 정보는
have the products so as you can see product information is
27:15:18
두 소스 시스템 모두에서 사용할 수 있습니다. 보통 우리는
available in both source systems as usual we're going to start
27:15:21
CRM 정보로 시작할 것이고, 그 다음에 조인할 것입니다.
with the crm informations and then we're gonna go and join it
27:15:24
다른 테이블과 조인하여 카테고리 정보를 얻기 위해
with the other table in order to get the category informations
27:15:27
이 테이블에서 우리가 원하는 열입니다. 이제
so those are the columns that we want from this table now
27:15:30
이 객체들에 대한 큰 결정을 내려야 합니다. 이
we come here to a big decision about these objects these
27:15:33
객체들은 역사적 정보를 포함하고 있으며 현재의
objects contains historical informations and as well the current
27:15:37
정보는 물론 요구 사항에 따라 다릅니다. 당신이
informations now of course depend on the requirement whether you
27:15:40
역사적 정보에 대한 분석을 해야 한다면, 하지만 만약
have to do analysis on the historical informations but if you
27:15:43
그런 요구 사항이 없다면, 우리는 현재의 정보만
don't have such a requirement we can go and stay with
27:15:46
포함하면 됩니다. 그래서 모든 역사적 데이터를
only the current informations of the products so we don't have to
27:15:49
객체에 포함할 필요가 없으며 어쨌든
include all the history in the objects and it is anyway
27:15:52
여기 모델에서 배운 것처럼 우리는 기본 키를 사용하지
as we learned from the model over here we are not using the primary
27:15:55
않고 제품 키를 사용하고 있습니다. 이제 무엇을
key we are using the product key so now what
27:15:58
해야 하냐면 역사적 데이터를 필터링하는 것입니다.
we have to do is to filter out the historical data
27:16:01
그리고 현재 데이터만 유지해야 하므로 여기서
and to stay only with the current data so we're gonna have here
27:16:04
조건을 설정할 것입니다. 현재 데이터를 선택하기 위해
a where condition and now in order to select the current data what we're gonna do we're gonna go and target the end dates if the end date
27:16:12
우리가 할 것은 종료 날짜를 타겟팅하는 것입니다. 종료 날짜가
is null that means it is a current data let's take this
27:16:15
null이면 현재 데이터라는 뜻입니다. 이 예를 들어
example over here so you can see here we have three records
27:16:18
보면, 우리는 세 개의 레코드가 있습니다.
for the same product key and for the first two records
27:16:21
같은 제품 키에 대해 첫 번째 두 레코드에
we have here an information in the end dates because it is
27:16:24
종료 날짜에 대한 정보가 있습니다. 왜냐하면 그것은
historical informations but the last record over
27:16:28
역사적 정보이기 때문입니다. 하지만 마지막 레코드는
here we have it as a null and that's because this is the
27:16:31
여기에서 null로 되어 있습니다. 이것은 현재 정보입니다.
current information it is open and it's not closed
27:16:34
현재 정보를 선택하는 것은 매우 간단합니다.
yet so in order to select only the current information it
27:16:37
우리는 종료 날짜를 말할 수 있습니다.
is very simple we can say brd end date
27:16:40
현재 제품만 가져올 수 있습니다.
is null so if you go now and execute it
27:16:43
이력은 없을 것입니다.
you will get only the current products you will not
27:16:46
물론 우리는 필터에 주석을 추가할 수 있습니다.
have any history and of course we can go and add comment to it filter
27:16:49
모든 역사적 데이터를 제외합니다.
out all historical data
27:16:53
따라서 종료 날짜가 필요하지 않습니다.
and this means of course we don't need the end dates in
27:16:56
현재 데이터만 있습니다. 다음 단계는
our selection of course because it is always a null so with that
27:17:00
제품 카테고리와 결합해야 합니다.
we have only the current data now the next step is that we
27:17:03
ERP에서 가져와야 합니다.
have to go and join it with the product categories
27:17:06
마스터 정보는 CRM입니다.
from the erp and we're going to use here the id so
27:17:09
모든 나머지는 보조적일 수 있습니다.
as usual the master information is the crm
27:17:12
왼쪽 조인을 사용하여 데이터를 잃지 않도록 합니다.
and everything else can be secondary that's why i
27:17:16
일치하는 데이터가 없으면 필터링하지 않습니다.
use the left join just to make sure i'm not losing
27:17:19
데이터를 잃게 됩니다.
i'm not filtering any data because if there is no match
27:17:22
왼쪽 조인으로 실버 ERP와 카테고리를 연결합니다.
then we lose data so left join silver
27:17:25
이것을 PC라고 부르겠습니다.
erp and the category so let's call
27:17:28
키를 사용하여 조인합니다.
it pc and now what we're gonna do we're gonna go and join
27:17:31
카테고리 ID는 PC ID와 같습니다.
it using the key so pn from the crm
27:17:35
두 번째 테이블에서 열을 선택해야 합니다.
we have the category id equal to pc id
27:17:38
PC와 카테고리를 가져옵니다.
and now we have to go and pick columns from the second table
27:17:41
매우 중요한 PC와 하위 카테고리가 있습니다.
so it's gonna be the pc we have the category
27:17:44
유지보수를 가져올 수 있습니다.
very important pc we have the subcategory
27:17:48
이와 같은 방식으로 진행합니다.
and we can go and get the maintenance
27:17:51
쿼리를 실행하여 모든 열을 가져옵니다.
so something like this let's go and
27:17:54
쿼리와 함께 모든 열이 나옵니다.
query and with that we have all those columns comes
27:17:57
첫 번째 테이블에서 세 개가 나오고
from the first table and those three comes from the
27:18:00
두 번째 테이블에서 모든 제품 정보를 수집했습니다.
second so with that we have collected all the product informations from
27:18:04
두 소스 시스템에서 다음 단계는
the two source systems now the next step is we have
27:18:07
이 결과의 품질을 확인하는 것입니다.
to go and check the quality of these results and
27:18:10
물론 매우 중요한 것은 고유성을 확인하는 것입니다.
of course what is very important is to check the uniqueness so
27:18:14
우리가 할 일은 다음 쿼리를 실행하는 것입니다.
what we're gonna do we're gonna go and have the following query i
27:18:17
제품 키가 고유한지 확인하고
want to make sure that the product key is unique because we're gonna use it later in order to join the table with the sales so from and then we have to have group by
27:18:30
그룹별로 확인하겠습니다.
product key and we're gonna say having accounts
27:18:33
하나보다 높은 계정을 확인해 보겠습니다.
higher than one so let's
27:18:36
완벽하게 중복이 없습니다.
go and check perfect we don't have any duplicates the
27:18:39
두 번째 테이블이 조인에 중복을 발생시키지 않았습니다.
second table didn't cause any duplicates for our join and as well this means we don't have historical data and each product is only one records
27:18:48
중복이 없어서 정말 기쁩니다.
and we don't have any duplicates so i'm really happy about
27:18:51
그렇다면 다시 쿼리해 보겠습니다.
that so let's go and query again now of course the
27:18:55
통합할 것이 있는지 확인해 보겠습니다.
next step do we have anything to integrate together do
27:18:58
같은 정보가 두 번 있습니까? 없습니다.
we have the same information twice well we don't have
27:19:01
다음 단계는 관련 정보를 그룹화하는 것입니다.
that the next step is that we're gonna go and group up
27:19:04
제품 ID, 제품 키, 제품을 말하겠습니다.
the relevant informations together so i'm gonna say the product
27:19:07
이름이 함께 있습니다.
id then the product key and the product
27:19:11
모든 세 가지 정보가 함께 있습니다.
name are together so all those three informations are
27:19:14
그 후 모든 카테고리 정보를 넣을 수 있습니다.
together and after that we can put all the category informations
27:19:17
카테고리 ID와 카테고리 자체를 함께 할 수 있습니다.
together so we can have the category id the category
27:19:20
서브카테고리를 쿼리해 보겠습니다.
itself the subcategory let me just query
27:19:24
결과를 확인해 보겠습니다.
and see the results so we have the product id key name
27:19:27
카테고리 ID 이름과 서브카테고리가 있습니다.
and then we have the category id name and the subcategory
27:19:31
그리고 나서 유지보수를 추가할 수도 있습니다.
and then maybe as well to put the maintenance after
27:19:34
하위 카테고리는 이렇게 되고, 제품에 대해 생각합니다.
the subcategory like this and i think the product
27:19:37
비용과 라인은 끝에 남아 있을 수 있으니 확인해 보겠습니다.
cost and the line can start could stay at the end so let me just check so those three four informations about the category and then we have have the cost line and the start date.
27:19:47
정말 기쁩니다. 다음 단계는 열에 친숙한 이름을 부여하는 것입니다.
I'm really happy with that. The next step, we're going to go and give nice names, friendly names for those columns.
27:19:52
첫 번째부터 시작해 봅시다. 이것은 제품 ID입니다.
So let's start with the first one. This is the product ID. The next one can be the product number.
27:20:00
나중에 대체 키를 위한 키가 필요합니다. 그리고 제품 이름이 있습니다.
We need the key for the surrogate key later. And then we have the product name.
27:20:05
그리고 나서 카테고리 ID와 카테고리가 있습니다.
And after that, we have the category ID and the category.
27:20:11
이것은 하위 카테고리입니다. 다음 것은 그대로 유지됩니다.
And this is the subcategory. And then the next one is going to stay as it is. I don't have to rename it.
27:20:17
다음은 비용과 제품 라인이 될 것이고, 마지막은 시작 날짜입니다.
The next one is going to be the cost and the product line. And the last one is going to be the start date.
27:20:24
가서 실행해 봅시다. 이제 출력을 아주 잘 볼 수 있습니다.
So let's go and execute it. Now we can see very nicely the output.
27:20:29
열에 대한 친숙한 이름들이 보이고, 훨씬 더 좋아 보입니다.
all those friendly names for the columns and it looks
27:20:32
이전보다 훨씬 더 좋아 보이고, 설명할 필요도 없습니다.
way nicer than before i don't have even to describe those
27:20:35
정보는 이름이 완벽하게 설명하고 있습니다.
informations the name describe it so perfect now the
27:20:38
다음 큰 결정은 여기서 무엇이 있는지입니다.
next big decision is what do we have here do we have a fact
27:20:42
사실인지 차원인지, 여러분은 어떻게 생각하나요?
or dimension what do you think well as you can see here again
27:20:45
제품에 대한 많은 설명이 있습니다.
we have a lot of descriptions about the products so
27:20:48
모든 정보는 비즈니스 객체 제품을 설명하고 있습니다.
all those informations are describing the business objects products we don't have like here transactions events a lot of different keys and
27:20:57
여기에는 사실이 없고 차원이 있습니다.
ideas so we don't have really here a fact we have a dimension
27:21:00
각 행은 정확히 하나의 객체를 설명합니다.
each row is exactly describing one object
27:21:04
하나의 제품을 설명하고 있습니다. 그래서 이것은 차원입니다.
describing one product that's why this is a
27:21:07
차원이므로 기본 키를 생성해야 합니다.
dimension okay so now since this is a dimension we have
27:21:10
대체 키를 생성해야 하며, 고객을 위해 했던 것처럼 창 함수 행 번호를 사용할 것입니다.
to go and create a primary key for it well actually the surrogate key and as we have done it for the customers we're going to go and use the window function row number in order to generate it
27:21:20
데이터를 저장해야 하며, 시작 날짜로 진행하겠습니다.
over and then we have to store the data i will go with the start date so let's go with the start
27:21:25
날짜와 제품 키도 있습니다.
dates and as well the product key
27:21:29
우리는 그것에 이름을 부여할 것입니다.
and we're gonna give it the name products
27:21:32
좋아요, 이렇게 해서 실행해 봅시다.
okay like this so let's go and execute it
27:21:36
이제 우리는 각 제품에 대한 기본 키를 생성했습니다.
with that we have now generated a primary
27:21:39
데이터 모델을 연결하기 위해 사용할 것입니다.
key for each product and we're gonna be using it
27:21:42
이제 다음 단계는 뷰를 구축하는 것입니다.
in order to connect our data model all right now the next step
27:21:45
그래서 우리는 뷰를 생성하겠다고 말할 것입니다.
is that we're gonna go and build the view so we're gonna say create
27:21:49
우리는 금과 차원 제품을 말할 것입니다.
view we're gonna say gold and dimension products
27:21:53
그럼 이제 우리를 만들어 봅시다.
and then us so let's go and create our
27:21:56
객체를 만들고 이제 뷰를 새로 고치면
objects and now if you're going to refresh the views you will
27:21:59
두 번째 객체, 두 번째 차원을 볼 수 있습니다.
see our second object the second dimension so
27:22:02
우리는 금 레이어에 차원 제품이 있습니다.
we have here in the gold layer the dimension products and as
27:22:05
보통 우리는 이 뷰를 살펴볼 것입니다.
usual we're gonna go and have a look to this view just
27:22:09
모든 것이 괜찮은지 확인하기 위해서입니다.
to make sure that everything is fine so then products so let's execute it and by looking to the data everything looks nice so with With that, we have now two dimensions.
27:22:24
좋아요, 친구들. 우리는 많은 것을 다뤘습니다.
All right, friends. So with that, we have covered a lot of stuff. So we have covered the customers and the products.
27:22:28
우리는 고객과 제품을 다뤘습니다.
And we are left with only one table where we have the transactions, the sales.
27:22:34
우리는 거래와 판매가 있는 하나의 테이블만 남았습니다.
And for the sales information, we have only data from the CRM. We don't have anything from the ERP. So let's go and build it.
27:22:40
판매 정보는 CRM의 데이터만 있습니다.
Okay, so now I have all those informations. And now, of course, we have only one table. We don't have to do any integrations and so on.
27:22:47
우리는 ERP의 데이터가 없습니다.
and now we have to answer the big question do we have here a dimension or
27:22:50
좋아요, 이제 모든 정보를 가지고 있습니다.
effects well by looking to those details we can see
27:22:53
우리는 통합을 할 필요가 없습니다.
transactions we can see events we have a lot of
27:22:56
이제 큰 질문에 답해야 합니다.
dates and formations we have as well a lot of measures and
27:22:59
여기 차원이 있는지 확인해야 합니다.
metrics and as well we have a lot of ids so it is
27:23:02
상세 정보를 보면 거래가 있습니다.
connecting multiple dimensions and this is exactly a perfect setup for effects so we're gonna go and use those informations as effects and of course as we learned the fact is connecting multiple dimensions
27:23:15
우리는 많은 날짜와 형식이 있습니다.
we have to present in this fact the surrogate keys that
27:23:18
측정항목과 ID가 많이 있습니다.
comes from the dimensions so those two informations the
27:23:21
이것은 여러 차원을 연결하는 것입니다.
product key and the customer id those informations
27:23:25
소스 시스템에서 오는 정보로, 연결하고자 합니다.
comes from the source system and as we learned we want to connect
27:23:28
대체 키를 사용하여 데이터 모델을 연결하고자 합니다.
our data model using the surrogate keys so what we're gonna
27:23:31
대체 키로 두 정보를 교체할 수 있습니다.
do we can replace those two informations with the surrogate
27:23:34
우리가 생성한 키로, 이를 위해 두 차원을 조인해야 합니다.
keys that we have generated and in order to do that we have to go and join now the two dimensions in order to get the surrogate
27:23:42
키를 얻기 위해 테이블을 조인하고 있습니다.
key and we call this process of course data lookup
27:23:45
정보를 얻기 위해 테이블을 조인합니다.
so we are joining the tables in order only to get one information
27:23:48
트랜잭션을 잃지 않기 위해 먼저
so let's go and do that we will go with the left join of course
27:23:51
제품 키와 조인할 것입니다.
not to lose any transaction so first
27:23:54
대체 키가 없습니다.
we're gonna go and join it with the product key now of course in the silver layer
27:23:58
금 계층에서 대체 키가 있습니다.
we don't have any surrogate keys we have it
27:24:01
사실 테이블을 위해 두 계층을 조인할 것입니다.
in the gold layer so that means for the fact table we're gonna be joining the silver layer together with the gold layer so gold dots and then the
27:24:10
차원 제품을 pr이라고 부를 것입니다.
dimension products and i'm gonna just call it
27:24:13
제품 키와 함께 sd를 조인할 것입니다.
pr and we're gonna join the sd using
27:24:16
차원에서 제품 번호와 함께
the product key together with the product
27:24:19
차원에서 필요한 정보는
number from the dimension and
27:24:22
회로 키입니다.
now the only information that we need from the dimension is
27:24:26
제품 키를 말하고, 이 정보를 제거할 것입니다.
the key the circuit key so we're gonna go over here and
27:24:29
생성한 대체 키가 필요합니다.
say product key and what i'm gonna do i'm gonna go and remove this information from here because we don't need it We don't need the original product key from the source system.
27:24:38
고객에 대해서도 같은 일이 발생할 수 있습니다.
We need the surrogate key that we have generated in our own in this data warehouse. So the same thing can happen as well for the customer.
27:24:46
금 고객 차원입니다.
So gold dimension customer.
27:24:49
정보를 얻기 위해 조회를 하고 있습니다.
Again, we are doing here a look up in order to get the information on SD.
27:24:54
이 ID를 사용하여 조인합니다.
So we are joining using this
27:24:57
이것은 고객 ID입니다.
ID over here equal to that customer ID
27:25:02
대체 키가 필요합니다.
because this is a customer ID and what we're going to do the
27:25:05
고객 키와 ID를 삭제할 것입니다.
same thing we need the surrogate key the
27:25:08
고객 키가 필요하고 ID를 삭제할 것입니다.
customer key and we're going to delete the ID because
27:25:11
이제 우리는 대체 키를 가지고 있으므로 필요하지 않습니다.
we don't need it now we have the surrogate key so now let's go and
27:25:14
이제 우리는 사실 테이블에서 두 개의 키를 가지고 있습니다.
execute it and now with that we have in our fact table the two keys from the dimensions and now this can
27:25:21
데이터 모델을 연결하는 데 도움이 됩니다.
help us to connect the data model to connect the facts with
27:25:24
차원과 사실을 연결하는 것이 매우 필요합니다.
the dimensions so this is very necessary step building the
27:25:27
사실 테이블을 구축하는 데 필요한 단계입니다.
fact table you have to boot the surrogate keys from the dimensions
27:25:31
사실을 구축하는 것이 실제로 가장 어려운 부분이었습니다.
in the facts so that was actually the hardest part
27:25:34
이제 다음 단계는 친숙한 이름을 부여하는 것입니다.
building the facts now the next step all what you have to do is to
27:25:37
주문 번호와 대체 키를 부여합니다.
go and give friendly names so we're going to go over here and say
27:25:40
이미 친숙하므로 이것이
order number then the surrogate keys
27:25:43
주문 날짜이고 다음은 배송이 될 것입니다.
are already friendly so we're going to go over here and say this is
27:25:46
날짜와 다음은 만기입니다.
the order date and the The next one going to be shipping
27:25:50
날짜와 다음 기한
date and then the next one due
27:25:54
날짜와 판매량, 판매 금액, 수량, 마지막으로 가격입니다.
date and the sales going to be I'm going to say sales amount the quantity and the final one is the price.
27:26:04
이제 실행하고 결과를 살펴보겠습니다.
So now let's go and execute it and look to the results.
27:26:07
보시다시피 열이 매우 친숙하게 보이고, 열의 순서에 대해서는 다음 스키마를 사용합니다.
So now as you can see the columns looks very friendly and now about the order of the columns we use the following schema.
27:26:14
먼저 사실 테이블에는 모든 차원에서 가져온 대체 키가 있습니다. 그 다음으로 모든 날짜가 있습니다.
So first in the fact table, we have all the surrogate keys from the dimensions. Then second, we have all the dates.
27:26:21
마지막으로 모든 측정값과 메트릭을 사실의 끝에 그룹화합니다. 그래서 이것이 사실에 대한 쿼리입니다.
And at the end, you group up all the measures and the metrics at the end of the facts. So that's it for the query for the facts.
27:26:28
이제 구축할 수 있습니다. 그래서 금 레이어에서 뷰 gold를 생성하겠습니다.
Now we can go and build it. So we're going to say create a view gold in the gold layer.
27:26:35
이번에는 facts 언더스코어를 사용할 것이고, sales라고 부를 것입니다. 그리고 우리를 잊지 마세요. 그래서 이게 전부입니다.
And this time we're going to use the facts underscore. And we're going to go and call it sales. And then don't forget about us. So that's it.
27:26:42
가서 생성해 봅시다. 완벽합니다. 이제 사실을 볼 수 있습니다. 그래서 우리는 금 다이아몬드에 세 개의 객체가 있습니다.
Let's go and create it. Perfect. Now we can see the facts. So with that, we have three objects in the gold dagger.
27:26:48
두 개의 차원과 하나의 사실이 있습니다. 이제 다음 단계는 연료의 품질을 확인하는 것입니다.
We have two dimensions and one facts. And now, of course, the next step is that we're going to go and check the quality of the fuel.
27:26:56
간단한 선택 사실 판매를 해봅시다. 이제 결과를 확인하면서 실행해 보겠습니다.
So let's have a simple select fact sales. So let's execute it now by checking the results.
27:27:02
쿼리의 결과와 정확히 같고 모든 것이 멋져 보입니다. 좋습니다.
You can see it is exactly like the results from the query and everything looks nice. Okay.
27:27:08
이제 사실을 구축한 후에 제가 보통 하는 한 가지 더는 전체 데이터 모델을 연결해 보려는 것입니다.
So now one more thing that I usually do after building a fact is try to connect the whole data model
27:27:14
문제를 찾기 위해 전체 데이터 모델을 연결해 보겠습니다.
order to find any issues so let's go and do that we will do just
27:27:17
차원과 간단한 왼쪽 조인을 하겠습니다.
simple left join with the dimensions so
27:27:20
골드 차원 고객 c
gold dimension customers c
27:27:24
키를 사용할 것입니다.
and we will use the keys
27:27:27
고객 키가 null인 경우 일치하는 항목이 없습니다.
and then we're gonna say where
27:27:30
이제 실행해 보겠습니다.
customer key is null so there is no matching
27:27:33
결과에서 아무것도 얻지 못하고 있습니다.
so let's go and execute it and with
27:27:36
모든 것이 완벽하게 일치하고 있습니다.
that as you can see in the results we are not getting anything that means everything
27:27:40
제품과도 같은 작업을 할 수 있습니다.
is matching perfectly and we can do as well the same
27:27:43
제품과 왼쪽 조인을 하겠습니다.
thing with the products so left
27:27:46
제품 키와 조인합니다.
join gold then products p
27:27:49
사실의 제품 키와 연결합니다.
on product key and
27:27:53
차원에서 제품 키를 확인해 보겠습니다.
then we connect it with the facts product key and
27:27:56
이렇게 연결할 수 있는지 확인하고 있습니다.
then we can go and check the product key from the dimension
27:28:00
차원 제품과 사실을 연결할 수 있는지 확인해 보겠습니다.
like this so we are checking whether we can connect the
27:28:03
이제 다음 단계로, 사용자에게 명확한 문서를 제공해야 합니다.
facts together with the dimension products let's go and check and as you can see as well we are not getting anything and this is all Alright so with that we have now SQL codes that is tested and as well creating the code layer.
27:28:15
이제 다음 단계로, 데이터 모델을 사용하기 위한 문서를 작성해야 합니다.
Now in the next step as you know in our requirements we have to make clear documentations for the end users in order to use our data model.
27:28:22
스타 스키마의 데이터 모델을 그려보겠습니다.
So let's go and draw a data model of the start schema.
27:28:29
테이블을 검색해 보겠습니다.
So let's go and draw our data model. Let's go and
27:28:32
기본 키가 무엇인지 말할 수 있는 테이블을 선택하겠습니다.
search for a table and now what I'm gonna do I'm gonna go and take this
27:28:35
전방 키가 무엇인지 말하고 약간 변경하겠습니다.
one where i can say what is the primary key
27:28:39
디자인을 약간 변경하겠습니다.
and what is the front key and i'm gonna go and change a little
27:28:42
이 색상으로 변경하고 크기를 조정하겠습니다.
bit the design so it's gonna be rounded and let's say i'm
27:28:45
크기를 16으로 만들고 모든 항목을 선택하겠습니다.
gonna go and change to this color and maybe go to the size
27:28:48
크기를 16으로 만들고 범위를 늘리겠습니다.
make it 16 and then i'm gonna go and select all the
27:28:51
열을 16으로 설정하고 크기를 늘린 다음 범위로 이동하여 39로 늘릴 수 있습니다. 이제 첫 번째 테이블을 조금 확대해 보겠습니다.
columns and make it as well 16 just increase the size and then go to our range and we can go and increase it 39 so now let's Let's go and zoom in a little bit for the first table.
27:29:03
목표 차원 고객이라고 부르고 이렇게 조금 더 크게 만들어 보겠습니다.
Let's go and call it goals dimension customers and make it a little bit bigger like this.
27:29:09
이제 여기에서 기본 키를 정의하겠습니다. 고객 키입니다. 그리고 우리가 할 다른 작업은 무엇인가요?
And now we're going to go and define here the primary key. It is the customer key. And what else we're going to do.
27:29:14
차원에 있는 모든 열을 나열할 것입니다. 조금 귀찮지만 결과는 훌륭할 수 있습니다. 고객 ID가 무엇인지 확인해 보겠습니다.
We're going to go and list all the columns in the dimension is a little bit annoying, but the results can be awesome. So what do we have that customer ID?
27:29:21
고객 번호가 있고, 그 다음에 이름이 있습니다.
We have the customer number, and then we have the first name.
27:29:27
새로운 장미를 원하신다면 이렇게 잡을 수 있습니다.
in case you want a new rose so you can hold
27:29:30
ctrl과 enter를 눌러 다른 열을 추가할 수 있습니다.
ctrl and enter and you can go and add the other columns so
27:29:33
이제 비디오를 일시 정지하고 두 개의 차원을 생성하세요.
now pause the video and then go and create the two dimensions the
27:29:37
고객과 제품을 추가하고 우리가 만든 모든 열을 추가하세요.
customers and the products and add all the columns that
27:29:40
우리가 만든 뷰에 있습니다.
you have built in the view we
27:29:47
이제 두 가지 차원이 생겼으니 세 번째는 사실 테이블이 될 것입니다. 사실 테이블은 예를 들어 파란색으로 다르게 할 것이고, 중앙에 배치할 것입니다. 이런 식으로요.
come back so now i have those two dimensions the third one gonna be the fact table now for the fact table i'm gonna go with different color for for example, the blue and I'm going to go and put it in the middle, something like this.
27:29:59
그래서 우리는 금 사실이라고 말할 것입니다.
so we're gonna say gold facts
27:30:02
판매이고 여기에는 기본 키가 없습니다.
sales and here for that we don't have primary
27:30:05
그래서 우리는 삭제하고 모든
key so we're gonna go and delete it and i have to go and add all the
27:30:08
사실의 열을 추가해야 합니다. 주문 번호, 제품
columns of the facts so order number products
27:30:11
키, 고객 키, 알겠습니다.
key customer key okay all right
27:30:14
완벽합니다. 이제 우리가 할 수 있는 것은 외래
perfect now what you can do we can go and add the foreign
27:30:17
키 정보를 추가하는 것입니다. 제품 키는 제품에 대한 외래 키이므로 fk1이라고 하고 고객 키는
key information so the product key is a foreign key for the products so we're gonna say fk1 and the customer key gonna be
27:30:24
고객에 대한 외래 키가 될 것입니다. 그래서 fk2이고 물론
the foreign key for the customers so fk2 and of course you
27:30:27
그것을 위해 간격을 늘릴 수 있습니다. 알겠죠? 이제
can go and increase the spacing for that okay so now
27:30:30
테이블을 만든 후 데이터 모델링의 다음 단계는
after we have the tables the next step in data modeling is to
27:30:33
이 테이블 간의 관계를 설명하는 것입니다. 이는
go and describe the relationship between these tables this
27:30:36
보고 및 분석에 매우 중요합니다. 데이터 모델을 어떻게 사용할지 이해하기 위해
is of course very important for reporting and analytics in order
27:30:40
우리는 서로 다른 유형의 관계가 있습니다. 일대일, 일대다, 그리고 스타 스키마 데이터 모델에서의 관계는
to understand how i'm gonna go and use the data model and we
27:30:43
이렇습니다.
have different types of relationships we have one-to-one one-to-many and in star schema data model the relationship between
27:30:49
차원과 사실 간의 관계는 일대다입니다.
the dimension and the fact is one too many and that's
27:30:52
고객 테이블에는 특정 고객에 대한
because in the table customers we have for a specific customer
27:30:55
단일 레코드만 존재하지만 사실 테이블에서는
only one record describing the customer but in the
27:30:58
고객이 여러 레코드에 존재할 수 있습니다.
fact table the customer might exist in multiple records
27:31:01
고객이 여러 번 주문할 수 있기 때문입니다.
and that's because customers can order multiple times
27:31:04
그래서 사실적으로는 다수이며
so that's why in fact it is many and in the
27:31:07
차원 측에서는 하나입니다. 이제 모든 관계를 보기 위해
dimension side it is one now in order to see all those relationships we're
27:31:11
왼쪽 메뉴로 가겠습니다. 여기 엔티티
gonna go to the menu to the left side and as you can see we have here entity
27:31:14
관계가 있으며 이제 다양한 유형의 화살표가 있습니다.
relations and now you have different types of arrows
27:31:17
예를 들어, 우리는 0에서 다수, 1에서 다수, 1
so for example we have zero to many one to many one
27:31:21
에서 1 및 다양한 유형의 관계가 있습니다.
to one and many different types of relations so
27:31:24
이제 어떤 것을 선택할지 결정하겠습니다. 이 항목을 선택하면
now which one we're gonna take we're gonna go and pick with this one so it says
27:31:27
하나가 필수입니다. 즉, 고객이 존재해야 합니다.
one mandatory so that means the customer must exist
27:31:31
차원 테이블에서 다수이지만 선택 사항입니다.
in the dimension table too many but it is optional so
27:31:34
여기 세 가지 시나리오가 있습니다. 고객이 아무것도 주문하지 않았거나
here we have three scenarios the customer didn't order anything or
27:31:37
고객이 한 번만 주문했거나 고객이
the customer did order only once or the customer
27:31:40
여러 가지를 주문했을 수 있습니다. 그래서 사실 테이블에서
did order many things so that's why in the fact table
27:31:43
선택 사항입니다. 이 항목을 선택하여 배치하겠습니다.
it is optional so we're gonna take this one and place it over
27:31:46
여기에서 이 부분을 연결하겠습니다.
here so we're gonna go and connect this part
27:31:49
고객 차원 및 여러 부분에
to the customer dimension and the many parts
27:31:53
사실에 연결합니다. 사실, 고객에 대해 수행해야 합니다.
to the facts well actually we have to do it on the customers
27:31:56
그래서 이를 통해 차원과
so with that we are describing the relationship between the dimensions and
27:32:00
사실 간의 관계를 설명하고 있습니다. 하나는 필수입니다.
fact with one to many one is mandatory for
27:32:03
고객 차원에 대해 다수는 선택 사항입니다.
the customer dimension and many is optional to the
27:32:06
사실에 대해 동일한 이야기가 제품에도 적용됩니다.
facts so we have the same story as well for the products so
27:32:09
사실의 많은 부분과 하나가 간다
the many parts to the facts and the one goes
27:32:13
제품으로, 연결할 때마다 이렇게 보일 것입니다
to the products so it's going to look like this each time you are connecting
27:32:16
사실 테이블에 대한 새로운 차원, 보통 하나입니다
new dimension to the fact table it is usually one
27:32:20
다대다 관계로, 원하는 것을 추가할 수 있습니다
to many relationship so you can go and add anything you want
27:32:23
예를 들어, 복잡한 계산이 있는 경우
to this model like for example a text like explaining something
27:32:26
여기에서 이 정보를 작성할 수 있습니다, 예를 들어
for example if you have some complicated calculations and so
27:32:30
여기에서 판매 계산이라고 말할 수 있습니다
on you can go and write this information over here so for example
27:32:33
조금 더 작게 만들 수 있으니 18로 가겠습니다
we can say or here sales calculation we
27:32:36
여기에서 그에 대한 공식을 작성할 수 있습니다
can make it a little bit smaller so let's go with 18
27:32:39
판매는 수량 곱하기
so we can go and write here the formula for that
27:32:42
가격과 함께, 이것을 조금 더 크게 만듭니다
so sales equal quantity multiplied
27:32:46
정말 좋은 정보입니다
with the price and make this a little bit bigger
27:32:49
이를 데이터 모델에 추가할 수 있고, 연결할 수 있습니다
so it is really a nice info that
27:32:52
열에 연결할 수 있으니, 예를 들어 이 화살표를 가져갑니다
we can add it to the data model and even we can go and link it
27:32:55
이렇게 놓고 열에 연결합니다
to the column so we can go and take this arrow for example
27:32:58
그렇게 하면 비즈니스 규칙에 대한 좋은 설명이 있습니다
put it like this and link it to the column and
27:33:01
또는 계산에 대해 설명을 추가할 수 있습니다
with that you have as well nice explanation about the business rule
27:33:05
데이터 모델에 추가하여 누구나 명확하게 이해할 수 있도록 합니다
or the calculation so you can go and add any descriptions that
27:33:08
데이터 모델에 추가하여 누구나 명확하게 이해할 수 있도록 합니다
you want to the data model just to make it clear for anyone that is
27:33:11
데이터베이스에 세 개의 테이블만 있는 것이 아닙니다
using your data model so with that you don't have only like three
27:33:15
어떤 종류의 문서화와 설명이 있습니다
tables in the database you have as well like some kind
27:33:18
데이터 모델이 어떻게 구축되었는지 볼 수 있습니다
of documentations and explanation in one click we
27:33:21
정말 멋진 데이터 모델이 있고, 다음 단계는 빠르게 데이터 카탈로그를 만들 것입니다
can see how the data model is built and how you can connect the tables together it is amazing really for all users of your data model all right so now with that we have
27:33:30
좋습니다, 그래서 데이터 모델이 있고
really nice data model and now the next step we're gonna go and create quickly a data catalog
27:33:39
좋습니다, 그래서 데이터 모델이 있고
all right great so with that we have a data model and we can say
27:33:42
우리는 데이터 제품이라고 하는 것이 있으며
we have something called a data product and we will be sharing
27:33:45
이 데이터 제품을 다양한 유형의 사용자와 공유할 것입니다.
this data product with different type of users and
27:33:48
모든 데이터 제품이 절대적으로 필요한 것이 있습니다.
there is something that every data product absolutely
27:33:51
그것은 데이터 카탈로그입니다. 데이터 모델, 열, 테이블, 아마도 테이블 간의 관계에 대해 설명할 수 있는 문서입니다.
needs and that is the data catalog it is a document that can describe everything about your data model, the columns, the tables, maybe the relationship between the tables as well.
27:34:01
그것으로 모든 사람이 데이터 제품을 명확하게 이해할 수 있습니다.
And with that, you make your data product clear for everyone.
27:34:04
그렇게 하면 그들이 데이터 제품에서 더 많은 통찰력과 보고서를 도출하기가 훨씬 쉬워질 것입니다.
And it's going to be for them way easier to derive more insights and reports from your data product.
27:34:10
가장 중요한 것은 무엇일까요? 시간 절약입니다. 그렇게 하지 않으면 어떤 일이 일어날 수 있을까요?
And what is the most important one? It is time saving, because if you don't do that, what can happen?
27:34:15
각 소비자, 데이터 제품의 각 사용자는 이 열이 무엇을 의미하는지에 대해 같은 질문을 계속할 것입니다.
Each consumer, each user of your data products will keep asking you the same questions about what do you mean with this column?
27:34:22
이 테이블은 테이블 A와 테이블 P를 어떻게 연결하는지에 대한 것입니다.
is this table how to connect the table a with the table p and
27:34:25
당신은 계속해서 자신을 반복하고 설명하게 될 것입니다. 그래서 대신
you will keep repeating yourself and explaining stuff so instead
27:34:28
데이터 카탈로그, 데이터 모델을 준비합니다.
of that you prepare a data catalog a data model and
27:34:32
사용자에게 모든 것을 함께 전달하면 많은 시간과 스트레스를 절약할 수 있습니다.
you deliver everything together to the users and with that you are saving
27:34:35
데이터 카탈로그를 만드는 것이 귀찮은 것은 알지만
a lot of time and stress i know it is annoying to create
27:34:38
투자이자 모범 사례입니다.
a data catalog but it is investment and best practices
27:34:41
이제 하나를 만들어 봅시다. 문서 폴더에 데이터 카탈로그라는 새 파일을 만들었습니다.
so now let's go and create one okay so now in order to do that i've created a new file called data catalog in the folder documents and here what we can do is very straightforward we're going to make a section for each table in the code layer.
27:34:53
예를 들어, 여기에는 고객 차원 테이블이 있습니다. 먼저 이 테이블을 설명해야 합니다.
So for example, we have here the table dimension customers. What you have to do first is to describe this table.
27:34:58
고객에 대한 세부정보를 저장한다고 말하고 있습니다.
So we are saying it stores details about the customers with
27:35:01
인구 통계 및 지리적 데이터를 포함하므로 테이블에 대한 간단한 설명을 제공합니다.
the demographics and geographics data so you give a short
27:35:04
그 후 이 테이블 안에 있는 모든 열을 나열하고, 데이터 유형도 포함할 수 있습니다.
description for the table and then after that you're gonna go and
27:35:08
하지만 가장 중요한 것은 각 열에 대한 설명입니다.
list all your columns inside this table and maybe as well the data
27:35:11
따라서 매우 간단한 설명을 제공합니다.
type but what is way important is the description for
27:35:14
예를 들어 고객의 성별입니다. 이제 가장 좋은 방법 중 하나는
each column so you give a very short description like
27:35:17
열을 설명하는 것입니다. 예를 제공하면
for example here the gender of the customer and now one of the best
27:35:20
열의 목적을 빠르게 이해할 수 있습니다.
practices of describing a column is to give examples because
27:35:24
예를 통해 쉽게 이해할 수 있습니다.
you can understand quickly the purpose of the columns by
27:35:27
열의 목적을 빠르게 이해할 수 있습니다.
just seeing an example right so here we are saying we can find inside
27:35:30
남성과 여성, 사용 불가를 찾을 수 있습니다.
it male female and not available so with that the
27:35:33
소비자는 즉시 이해할 수 있습니다.
consumer of your table can immediately understand aha it will not be
27:35:36
M이나 F가 아니라 친숙한 값이 될 것입니다.
an m or an f it's gonna be a full friendly value
27:35:39
테이블의 내용을 쿼리할 필요 없이
without having them to go and query the content of the table they
27:35:42
그 열의 목적을 빠르게 이해할 수 있습니다.
can understand quickly the purpose of that column so with that we have a full description for all the columns of our dimension the same thing we're gonna do
27:35:50
제품에 대한 설명을 다시 작성할 것입니다.
for the products so again a description for the table and
27:35:53
사실에 대한 설명도 포함됩니다.
as well a description for each column and the same thing for
27:35:56
데이터 카탈로그를 갖게 됩니다.
the facts so that's it with that you have like a data
27:35:59
비즈니스 사용자나 데이터 분석가가
catalog for your data products at the code layer and with that
27:36:02
코드 레이어의 내용을 더 잘 이해할 수 있습니다.
the business user or the data analyst have better and clear
27:36:05
데이터 흐름 다이어그램을 작성할 것입니다.
understanding of the content of your code layer all right my friends so that's all for the data catalog in the next step we're going to go back to draw where we're going to finalize
27:36:15
데이터 흐름 다이어그램을 확장할 것입니다.
the data flow diagram so let's go okay
27:36:21
이번에는 골드 레이어를 위해서입니다.
so now we're gonna go and extend our data flow diagram but
27:36:24
실버 레이어의 전체를 복사합니다.
this time for the gold layer so now let's go and copy the
27:36:28
옆에 나란히 배치할 것입니다.
whole thing from the silver layer and put it over here side
27:36:31
색상을 변경할 것입니다.
by side and of course we're gonna go and change the coloring to
27:36:34
이것이 골드 레이어입니다.
the gold and now we're gonna go and rename stuff
27:36:37
이 테이블을 이렇게 둘 수는 없습니다.
so this is the gold layer but now
27:36:40
새로운 데이터 모델이 있습니다.
of course we cannot leave those tables like this we have completely
27:36:43
판매 사실과 고객 차원이 있습니다.
new data model so what do we have over here we have the
27:36:46
제품 차원도 있습니다.
fact sales we have dimension customers
27:36:50
이제 모든 것을 제거할 것입니다.
and as well we have dimension products
27:36:53
세 개의 테이블만 남습니다.
so now what i'm gonna do i'm gonna go and remove all those stuff
27:36:56
세 개의 테이블을 중앙에 배치할 것입니다.
we have only three tables and let's go and put those three
27:37:00
여기 중앙에 테이블을 놓아야 합니다.
tables somewhere here in the center so now what you have to do is to
27:37:03
이제 연결을 시작해야 합니다.
go and start connecting those stuff i'm gonna go with
27:37:06
이 화살표는 직접 연결을 나타냅니다.
this arrow over here direct connection and start
27:37:09
판매 세부정보는 사실 테이블로 연결됩니다.
connecting stuff so the sales details goes to
27:37:12
사실 테이블을 여기 두고 차원 고객을 추가합니다.
the fact table maybe put the fact table over here and then we
27:37:15
고객 정보는 CRM에서 가져옵니다.
have the dimension customer this comes from the crm customer info and we have two tables
27:37:21
ERP에서 위치 정보를 가져옵니다.
from the erp it comes from this table as
27:37:24
제품에 대해서도 동일하게 적용됩니다.
well and the location from the erp
27:37:27
제품 정보와 카테고리에서 가져옵니다.
now the same thing goes for the products it
27:37:31
ERP에서 가져옵니다. 여기 교차 화살표가 있습니다.
comes from the product info and comes from the categories
27:37:34
모든 것을 선택하고 말할 수 있습니다.
from the erp now as as you can see here we have cross arrows
27:37:37
선이 간격을 두고 점프합니다.
so what you can do we can go and select everything and we can say
27:37:40
이것은 화살표를 더 나은 개별로 만듭니다.
line jumps with a gap and this makes it a
27:37:43
예를 들어 데이터 출처를 묻는다면,
little bit like better individual for the arrows so now for
27:37:46
이 다이어그램을 열어 알려줄 수 있습니다.
example if someone asks you where the data come from for the
27:37:50
이것은 실버 레이어에서 가져온 것입니다.
dimension products you can open this diagram and tell them
27:37:53
CRM의 제품 정보와 ERP의 카테고리 두 개의 테이블이 있습니다.
okay this comes from the silver layer we have like
27:37:56
매우 간단합니다. 전체를 만들었습니다.
two tables the product info from the crm and as well the categories from the erp and those several tables comes from the bronze layer and you can see the product info comes from the CRM and the category comes from the ERP.
27:38:08
우리 데이터 웨어하우스의 데이터 계보를 만들었습니다.
So it is very simple we have just created a full
27:38:11
좋습니다. 멋진 데이터 흐름 다이어그램과 데이터 계보가 있습니다.
data lineage for our data warehouse from the sources into the different layers in our data warehouse and data lineage is this really amazing documentation that can help not only your users but as well the developers.
27:38:22
데이터 흐름을 완료했습니다. 정말 성취감을 느낍니다.
All right so with that we have very nice data flow diagram and a data lineage.
27:38:25
이제 마지막 작업에 도달했습니다.
All right so we have completed the data flow it's really feel like progress like achievement as we are clicking through all those
27:38:32
데이터 웨어하우스를 구축하는 마지막 작업입니다.
tasks and now we come to the last task in building the data
27:38:35
작업을 커밋할 것입니다.
warehouse where we're going to go and commit our work in the get
27:38:38
레포 괜찮아
repo okay
27:38:43
이제 프로젝트에 스크립트를 넣어보겠습니다. 스크립트로 가겠습니다.
so now let's put our scripts in the project so we're going to go to the scripts
27:38:46
여기에는 동상, 은상, 금상은 없지만 있습니다.
over here we have here bronze silver but we don't have a gold so
27:38:49
새 파일을 만들겠습니다. gold 슬래시가 필요합니다.
let's go and create a new file we're going to have gold slash and
27:38:53
ddl gold.sql이라고 하겠습니다. 이제 뷰를 붙여넣겠습니다.
then we're going to say ddl gold dot sql so now we're going to go and paste our views so we have here our three views and as usual at the
27:39:01
뷰의 목적을 설명할 수 있습니다. 생성하겠습니다.
start we can describe the purpose of the views so we are saying create
27:39:05
골드 뷰 이 스크립트는 코드에 대한 뷰를 생성할 수 있습니다.
gold views this script can go and create views for the code
27:39:08
여기서 코드가 최종 차원을 나타냅니다.
there and the code there represent the final dimension and
27:39:11
팩트 테이블, 스타 스키마 각 뷰는 변환을 수행합니다.
fact tables the star schema each view perform transformations
27:39:14
서버 레이어의 데이터를 조합하여 비즈니스 준비 데이터 세트를 생성합니다.
and combination data from the server layer to produce
27:39:17
이 뷰는 분석 및 보고에 사용할 수 있습니다. 그래서 커밋하겠습니다.
business ready data sets and those views can be used for analytics and reporting so that sense let's go and commit it okay so with that as you can see we have the bronze
27:39:27
은상, 모든 ETL과 스크립트가 있습니다.
the silver so we have all our etls and scripts
27:39:30
저장소에 이제 골드 레이어도 추가하겠습니다.
in the repository and now as well for the gold layer
27:39:33
우리가 사용했던 모든 품질 검사를 추가하겠습니다.
we're going to go and add all those quality checks that we have used
27:39:37
차원과 팩트를 검증하기 위해 테스트로 가겠습니다.
in order to validate the dimensions and fact so
27:39:40
여기서 새 파일을 만들겠습니다.
we're going to go to the test over here and we're going to go and create a new file
27:39:43
품질 검사 골드가 될 것입니다.
it's going to be quality checks gold
27:39:46
파일 유형은 SQL입니다. 품질 검사를 붙여넣겠습니다.
and the file type is sql so now let's go and paste our quality checks so we have the check for the fact the two dimensions and as well an explanation about the scripts.
27:39:56
코드 레이어의 무결성과 정확성을 검증하고 있습니다.
So we are validating the integrity and the accuracy of the code layer.
27:40:00
회로 키의 고유성을 확인하고 데이터 모델을 연결할 수 있는지 확인합니다.
We are checking the uniqueness of the circuit keys and whether we are able to connect the data model.
27:40:04
그것을 Git에 넣고 변경 사항을 커밋하겠습니다.
So let's put that as well in our Git and commit the changes.
27:40:08
새 품질 검사가 생기면 스크립트에 추가하겠습니다.
And in case we come up with a new quality checks, we're going to go and add it to our script here.
27:40:13
ETL을 수정하거나 각 ETL 후에 스크립트가 실행되도록 확인하는 것이 중요합니다.
So those checks are really important if you are modifying the ETLs or you want to make sure that after each ETL, those scripts should run and so on.
27:40:20
골드 레이어에서 모든 것이 괜찮은지 확인하는 품질 게이트와 같습니다.
It is like a quality gate to make sure that everything is fine in the gold layer. Perfect. So now we have our code in our repository.
27:40:28
이제 코드가 저장소에 있습니다. 친구들, 이제 해야 할 일은 Git 저장소를 마무리하는 것입니다.
Okay, friends. So now what you have to do is to go and finalize the get repo.
27:40:32
예를 들어, 프로젝트 동안 만든 모든 문서를 docs에 업로드할 수 있습니다.
So for example, all the documentations that you have created during the projects, we can go and upload them in the docs.
27:40:38
예를 들어, 여기에서 아키텍처, 데이터 흐름, 데이터 통합, 데이터 모델 등을 볼 수 있습니다.
So for example, you can see here that architecture, the data flow, data integration, data model and so on.
27:40:43
페이지를 편집할 때마다 작업을 커밋하고 해당 버전을 가질 수 있습니다.
So that each time you edit those pages, you can commit your work and you have like a version of that.
27:40:49
또 다른 방법은 읽어보기를 가는 것입니다.
And another thing that you can do is that you go to the read me.
27:40:52
예를 들어, 여기에서 프로젝트 개요와 몇 가지 중요한 링크를 추가했습니다.
Like for example, over here, I have added that project overview, some important links
27:40:57
그리고 데이터 아키텍처와 아키텍처에 대한 간단한 설명도 추가했습니다.
and as well the data architecture and a little description of the architecture of course.
27:41:01
그리고 물론, 자신에 대한 몇 마디와 다양한 소셜 미디어의 중요한 프로필을 추가하는 것을 잊지 마세요.
And of course, don't forget to add a few words about yourself and important profiles in the different social medias. All right, my friends.
27:41:08
이로써 우리는 작업을 커밋하고 마지막 에픽인 골드 레이어를 마무리했습니다.
So with that, we have committed our work and as well closed the last epic building the gold layer.
27:41:14
이로써 데이터 웨어하우스를 구축하는 모든 단계를 완료했습니다.
And with that, we have completed all the phases of building a data warehouse.
27:41:19
모든 것이 100% 완료되었고, 정말 기분이 좋습니다.
Everything is 100% and this feels really nice. All right, my friends.
27:41:23
이로써 첫 번째 유형의 SQL 프로젝트인 데이터 웨어하우징 프로젝트를 다루었습니다.
So with that, we have covered the first type of SQL projects, the data warehousing project, This is usually a very complex project that you can get involved in a company.
27:41:31
데이터 엔지니어가 되고 싶다면 정말 놀라운 프로젝트입니다.
And this is really amazing project if you are planning to be a data engineer. But of course, if you are a data analyst, you might end up as well building warehouses.
27:41:39
이제 SQL의 두 번째 유형의 프로젝트를 위해 모든 준비가 완료되었습니다.
So now we have everything prepared for the second type of project in SQL. We will deep dive now into the exploratory data analyzers.
27:41:46
이제 데이터 프로파일링이라는 작업을 수행할 것입니다.
So let's go. And now here we're going to cover the second type of projects where we're going to use our basic SQL skills
27:41:56
모든 데이터 세트의 측면을 이해하려고 합니다.
in order to do something called data profiling where we're gonna try to understand all the aspects of our data sets using simple aggregations like the sum average count and as well we will be using techniques like some queries
27:42:12
모든 데이터 프로젝트의 첫 번째 단계는 데이터 세트가 필요하다는 것입니다.
all right my friends so the first step in any data project is that we
27:42:15
이전 프로젝트에서 SQL 데이터 웨어하우스를 구축한 경우 모든 것이 준비되어 있습니다.
need data sets if you have done the previous project where we have built
27:42:19
그것을 건너뛰었다면, 제가 여러분을 위해 파일을 준비했습니다.
the sql data warehouse then you have everything the data and the database so you don't have to worry about it but if you skip that which
27:42:26
데이터베이스를 만들기 위해 데이터를 가져오겠습니다.
i don't recommend i still have prepared for you the files and
27:42:29
설명에 있는 링크로 가면 됩니다.
the database so let's get the data and create our database all
27:42:32
다운로드로 가고, 제 뉴스레터를 구독할 수 있습니다.
right so now if you go to the link in the description we're gonna go to the
27:42:35
여기에서 SQL 과정 자료가 있고 링크도 있습니다.
downloads and of course you can subscribe to my newsletter and
27:42:38
데이터 분석 프로젝트를 위한 링크로 가겠습니다.
then here we have the sql course materials and here we have a link
27:42:42
서버 다운로드와 같은 중요한 링크가 있습니다.
for data analytics projects let's go to the link and now here
27:42:45
SQL을 작성할 관리 스튜디오로 가겠습니다.
you have some important links like downloading the server the
27:42:48
여기에는 Git 저장소에 대한 링크도 있습니다.
management studio where we're gonna write our sqls and as well
27:42:51
git 저장소에 대한 링크가 있으며 매우
there is a link to the git repository and as well what is very
27:42:54
중요한 것은 모든 프로젝트 파일을 다운로드하는 것이므로 클릭하십시오
important is to download all the project files so click on
27:42:57
그것을 다운로드하고 모든 파일을 지금 추출하여
that and download all the files now extract the file and put it
27:43:00
PC의 안전한 곳에 두십시오. 이제 그 안에 모든
somewhere safe at your pc and now inside it you can find all
27:43:03
스크립트와 데이터 세트를 찾을 수 있습니다. 이제
the scripts and the data sets now there is like three ways on how
27:43:06
데이터베이스를 SQL 서버에서 생성하는 방법은 세 가지가 있습니다.
to create the database in sql server so the first one
27:43:09
첫 번째 방법은 스크립트를 실행하는 것입니다. 여기 스크립트로 가면
is by executing scripts if you go to the scripts over here
27:43:13
첫 번째로 init database라는 파일이 있습니다. 그 안으로 들어가서 전체를 복사한 다음
the first one we have a file called init database just go inside it and copy the whole thing and then let's go to
27:43:19
SQL 서버로 가서 새 쿼리를 만들고
sql server now make a new query and make
27:43:22
마스터 데이터베이스로 전환했는지 확인하고
sure you switch to the master database and
27:43:26
전체 코드를 붙여넣습니다. 지금 여기서 하는 것은
then paste the whole code so now what you are doing here is we
27:43:29
새 데이터베이스를 만들고 스키마를 생성하며
are creating a new database we are creating a schema and
27:43:32
우리가 사용할 세 개의 매우 중요한 테이블을 만드는 것입니다.
then three very important tables that we're going to use in
27:43:35
데이터 분석에 사용합니다. 이제 이 스크립트에서
our data analyzes now there is like only one thing that you have to
27:43:39
변경해야 할 유일한 것은 파일의 경로입니다.
change in this script and that is the path
27:43:42
그것을 완료한 후 전체 스크립트를 실행하십시오. 이제 모든 것이 완료되었습니다.
of the files and once you have done that just go
27:43:45
데이터가 삽입되었습니다. 이제 왼쪽으로 가면
and execute the whole script and now you can see everything is done
27:43:48
데이터베이스로 가서 새로 고침하면
and there is like data inserted now if you go to the left side
27:43:51
data warehouse analytics라는 새 데이터베이스를 찾을 수 있습니다.
to the database and refresh you can find a
27:43:54
테이블로 들어가면 세 개의 테이블을 찾을 수 있습니다.
new database called data warehouse analytics and if
27:43:57
고객, 제품 및 판매 테이블입니다. 이것이
you go inside the tables you will find our three
27:44:00
데이터베이스를 생성하는 한 가지 방법입니다. 두 번째 방법은
tables customer products and sales so this
27:44:03
여기 데이터베이스로 가서 마우스 오른쪽 버튼을 클릭하고
is one way on how to create the database the second method is
27:44:07
새 데이터베이스를 생성하는 것입니다. 예를 들어 data warehouse라고 부릅시다.
to go to the databases over here right click on it and
27:44:10
analytics라고 부를 것이며 두 번째로 부를 것입니다.
say a new database and for example let's call it data warehouse
27:44:13
분석을 두라고 부를게요
analytics i'm gonna call it two because
27:44:16
이미 하나가 있고 확인을 클릭하면
i have already one and then click ok and with that you have
27:44:19
새 데이터베이스가 생깁니다. 이제 할 일은
a new database so what we're gonna do now we're gonna right
27:44:22
그것을 클릭하고 작업으로 가서 가져오기
click on it and then go to tasks and then import
27:44:26
평면 파일을 가져옵니다. 이제 할 수 있는 것은
flat file and now what we can do we're gonna go and import
27:44:29
CSV 파일을 새 데이터베이스로 가져오는 것입니다.
the csv files to our new database so
27:44:32
다음으로 가고 파일을 찾아야 합니다.
we can go next and then you have to go and locate your files
27:44:35
여기 어딘가에 있습니다. 데이터
i have them somewhere over here so data
27:44:38
세트 CSV 파일에 집중해야 합니다.
sets csv files and we have to focus on the gold
27:44:42
테이블을 선택하고 다음으로 가겠습니다.
tables so i'm gonna go and select this one and then next
27:44:45
이제 데이터 개요를 보고 있습니다. 다음으로
now i'm just getting an overview of my data so next
27:44:48
오류가 발생하지 않도록 확인하겠습니다.
now just to make sure that you are not getting any error i'm gonna go
27:44:51
널을 허용하고 그게 전부입니다. 다음으로
and allow nulls and that's all so next
27:44:54
마무리하고 데이터가 삽입되었습니다.
and finish so perfect the data has been inserted
27:44:58
이제 데이터베이스 테이블로 가겠습니다.
now let's go to our database tables and as
27:45:01
여기 새 테이블이 있습니다. 이 작업을 반복해야 합니다.
you can see we have here our new table so you have to go and repeat this
27:45:04
데이터를 잘 가져오기 위해 세 번 반복해야 합니다.
three times in order to import the data well you can use this
27:45:07
첫 번째 방법이 작동하지 않으면 이 방법을 사용하세요.
method if the first method didn't work but i really recommend you
27:45:11
데이터베이스를 생성하기 위해 스크립트를 사용하세요.
to use the script in order to create the database the
27:45:14
세 번째 방법은 데이터베이스를 복원하는 것입니다.
third way is to go and restore the database itself
27:45:17
이제 어떻게 할 것인지 데이터 세트로 다시 가겠습니다.
now how we're gonna do it we can go again to the data sets and
27:45:20
여기 데이터베이스 백업이 있습니다.
as you can see we have here a database backup so as you can see
27:45:23
여기 pak 파일이 있습니다. 이제 해야 할 일은
we have here a pak file so now what you have to do is to
27:45:26
복사하고 데이터베이스 위치로 가는 것입니다.
go and copy that and then we're gonna go to the database location
27:45:30
SQL 서버를 설치한 위치에 따라 다릅니다.
so it really depends where you have installed the sql server
27:45:33
그래서 현재 나는 여기 프로그램 파일 마이크로소프트 SQL에 설치했습니다.
so currently i have it here program files microsoft sql
27:45:36
서버와 그 다음 익스프레스 MSQL 백업
server and then the express msql backup
27:45:39
여기에 파일을 배치해야 합니다. 그래서 나는 여기 데이터 웨어하우스 분석 백업이 있습니다. 이제 해야 할 일은 데이터베이스를 마우스 오른쪽 버튼으로 클릭하고
and you have to place the file over here so i have it here data warehouse analytics backup and now all what you have to do is to right click on the database and then say
27:45:48
데이터베이스 복원을 선택한 다음 장치 3으로 이동합니다.
restore database and then we're gonna go to the device three
27:45:51
포인트를 추가하겠다고 말하고 이제 우리의
points and we're gonna say add and now you can see our
27:45:55
데이터베이스 데이터 웨어하우스 분석을 볼 수 있습니다. 우리가
database data warehouse analytics once we
27:45:58
확인하고 확인을 누르면 이미 가지고 있기 때문에
say okay and then okay and now since i have it already i
27:46:01
오류가 발생하지만 확인을 클릭하면 전체 데이터베이스
will get an error but once i click okay the whole database
27:46:04
스크립트를 실행하지 않고 복원할 수 있습니다. 그래서 프로젝트의 데이터베이스를 만드는 세 가지 방법입니다. 만약 당신이 나와 함께 데이터 웨어하우스 프로젝트를 만들었다면, 당신은 그것을 할 필요가 없습니다. 우리는 함께 그것을 만들었습니다.
can be restored without running any scripts so those are the three ways on how to create the database of the projects and if you have built with me the data warehouse projects before you don't have to do it because we have built that together.
27:46:16
비디오를 일시 정지하고 프로젝트에 대한 데이터를 가져오세요.
So pause the video and get the data for the projects.
27:46:24
좋아요, 친구들, 그래서 우리는 비밀, 내가 보통 데이터 세트를 분석할 때 사용하는 작은 트릭으로 시작할 것입니다.
All right, my friends, so we're going to start with a secret, a little trick that I usually do by analyzing any data sets.
27:46:30
그러니 시작하기 전에 커피 한 잔을 마십시다. 정말 뜨겁습니다.
So let's start with a little coffee before we start. This is really hot.
27:46:35
좋아요, 비밀은 내가 어떤 프로젝트의 데이터 세트를 볼 때, 데이터가 항상 차원과 측정으로 나뉘어져 있다는 것입니다.
Okay, so the secret says, as I'm looking to any data sets in any projects, I see the data always divided between dimensions and measures.
27:46:46
무슨 진리인가요? 당신은 파란 알약을 먹고 빨간 알약을 먹습니다. 내가 제공하는 것은 진리뿐입니다, 그 이상은 아닙니다.
What truth? You take the blue pill, you take the red pill. All I'm offering is the truth, nothing more.
27:46:54
당신이 나처럼 데이터를 차원과 측정으로 본다면, 당신은 어떤 프로젝트에서든 무한한 통찰력을 생성할 수 있습니다.
If you see your data like me as dimensions and measures, you can generate like endless amount of insights from any projects, from any datasets.
27:47:03
그리고 나는 항상 이야기하는 프로젝트를 통해 나를 찾을 수 있을 것입니다. 측정과 차원에 대해.
And you will find me through the projects that I'm always speaking about, measures and dimensions.
27:47:08
그래서 나는 보통 어떻게 하는지 보여줄 것입니다. 보통 어떤 프로젝트의 데이터 세트를 보면 여러 열과 행이 있습니다.
So I'm going to show you how I usually do it. So now usually by looking to any data sets in any projects, so you have like multiple columns and rows.
27:47:15
여기서 나는 데이터가 항상 두 가지 범주로 나뉘어져 있다는 것을 봅니다. 차원 또는 측정입니다.
Here I see the data always split into two categories, either a dimension or a measure.
27:47:20
이제 물론 질문은 내 열이 차원인지 측정인지입니다.
And now of course the question is here, is my column a dimension or a measure?
27:47:25
그것을 하나의 범주에 할당하기 위해서는 첫 번째 질문을 해야 합니다. 그것이 숫자 값인가요?
Well, in order to assign it to one of those categories, you have to ask the first question, is it a numeric value?
27:47:32
아니라면, 문자열이나 날짜 또는 다른 데이터 유형이 있습니다.
If it's not, so you have like string or date or any
27:47:35
그렇다면 그것은 차원입니다. 그리고 만약 그것이
other data type, then it is a dimension and if it
27:47:38
숫자라면 두 번째 질문을 해야 합니다. 그것을 집계하는 것이 의미가 있나요?
is yes in numeric then you have to ask the second question does
27:47:42
두 질문 모두에 대한 대답이 예라면, 그것은 숫자이고
it make sense to aggregate it so if the answer for
27:47:46
집계하는 것이 의미가 있다면 그것은 측정입니다. 그렇지 않다면.
both questions is yes it is numeric and it
27:47:49
그것을 집계하는 것이 의미가 있으므로, 이는 측정값입니다.
makes sense to aggregate it then it is a measure otherwise
27:47:52
이것은 차원입니다. 이제 연습하고 몇 가지 예를 들어보겠습니다.
it is a dimension now let's practice and have some examples
27:47:55
이제 카테고리 열의 값을 살펴보면,
so now by looking to the values of the column category you
27:47:58
모든 값이 문자이므로 숫자가 아닙니다.
can see all the values are characters so it is not
27:48:01
즉, 이 열은 차원입니다. 이제 다른 열을 살펴보겠습니다. 판매 금액이 있습니다.
numeric that means this column is a dimension so
27:48:04
이제 값을 보면 숫자이며, 집계하는 것이 의미가 있습니다.
it is very simple let's take another column we have the sales amount
27:48:08
그 값들을 집계하는 것이 의미가 있으므로, 총합을 구할 수 있습니다.
so now as you can see the values are numeric and as well it
27:48:11
판매량 또는 평균 판매량 등을 구할 수 있으므로, 이는 충족됩니다.
makes sense to aggregate those values we can get the total
27:48:14
두 가지 조건을 모두 충족합니다. 숫자이며 집계하는 것이 의미가 있습니다.
sales or the average sales and so on so it fulfills
27:48:17
그렇기 때문에 판매량은 측정값이라고 말합니다. 이제 제품 이름의 값을 확인하면, 모든 값이 문자와 이름이므로 숫자가 아닙니다.
both of the conditions it is numeric and it makes sense to aggregate
27:48:20
그렇기 때문에 판매량은 측정값이라고 말합니다. 이제 제품 이름의 값을 확인하면, 모든 값이 문자와 이름이므로 숫자가 아닙니다.
it that's why we say sales is a measure now if you're checking the values of the product name you can see that all of them are characters and names so it is not numeric that That means the product is a dimension.
27:48:32
이제 다음으로 넘어가면, 수량이 있습니다. 값은 숫자이며, 집계하는 것이 의미가 있습니다.
Moving on to the next one, we have the quantity. The values are numeric and as well, it makes sense to aggregate it.
27:48:38
모든 값을 요약하여 총 수량을 얻을 수 있습니다. 따라서 수량은 측정값입니다.
Can summarize all those values to have that total quantity. So quantity is a measure.
27:48:42
이제 생년월일의 값을 살펴보면, 이는 날짜 정보입니다. 숫자가 아닙니다.
Now if you are looking to the values of the birth date, you can see this is a date information. It is not numeric.
27:48:47
즉, 이는 차원입니다. 하지만 생년월일에서 나이를 계산하면, 고객의 나이는 숫자가 되고 집계하는 것이 의미가 있습니다.
So that means it is a dimension, right? But if you calculate the age from the birth dates, age of the customer going to be in numeric and it makes sense to aggregate it.
27:48:58
예를 들어, 고객의 평균 나이를 찾는 것입니다. 차원에서 숫자 값을 도출하면, 이를 주요 값으로 사용할 수 있습니다.
For example, finding the average age of customers. So if we derive a numeric value from a dimension, then we can use it as a major.
27:49:07
따라서 나이는 주요 값입니다. 이제 정말 까다로운 것에 대해 이야기해 보겠습니다. 이것은 ID입니다.
So age is a major. And now we come to something real tricky. This is the ID.
27:49:12
예를 들어, 고객 ID를 확인하면, 모든 값이 숫자임을 알 수 있습니다. 따라서 첫 번째 조건이 충족됩니다.
So for example, if you are checking the customer ID, you can see all those values are numeric. So the first condition is fulfilled.
27:49:19
이제 매우 중요한 질문입니다. ID를 집계하는 것이 의미가 있나요? 그 ID는 고객의 고유 식별자입니다.
Now the very important question, does it make sense to aggregate the IDs? Well, those IDs are unique identifier for a customer.
27:49:26
그 평균을 찾으면 도움이 되지 않습니다. 하나의 사용 사례를 생각할 수 없습니다.
and if you find like the average of that it is not like
27:49:29
고객 ID를 집계하는 것은 도움이 되지 않습니다. 평균을 구하는 것처럼요.
helpful right i cannot think of one use case of
27:49:32
모든 아이디어의 평균을 내거나 아이디어를 요약하는 것과 같습니다.
aggregating the customer id like having the average
27:49:36
그래서 집계하는 것은 의미가 없습니다. 그렇기 때문에
of all those ideas or summarizing the ideas
27:49:39
고객의 ID를 차원으로 간주할 수 있습니다.
so it makes no sense to aggregate it that's why
27:49:42
측정값이 아니라, 보시다시피 매우 간단합니다.
we can consider the id of a customer as a dimension
27:49:45
고객의 ID를 차원으로 고려할 수 있습니다.
not as a measure so as you can see it is very simple if it
27:49:48
측정값이 아닌 차원으로 볼 수 있습니다.
is numeric and it makes sense to aggregate then it is
27:49:51
측정값이 아닌 차원입니다.
measure otherwise it is a dimension and this is the
27:49:54
데이터 분석의 기초입니다.
foundations of any data analytics if you see your data as dimensions and measures you can generate a lot of use cases and insights from your data sets.
27:50:04
이제 차원과 측정값에 대해 혼란스러울 수 있습니다.
Now, I totally understand if you are still confused about dimensions and measures, and you might be asking, why do I need measures and dimensions?
27:50:11
데이터 분석을 하거나 데이터 세트를 탐색할 때
Well, if you are doing any type of data analysis, or you are exploring any data sets, you will be end up always like grouping up the data by something like you are grouping the data by
27:50:20
국가별로 데이터를 그룹화하는 것입니다.
countries or grouping the data by for example products
27:50:24
또는 카테고리이므로 우리는 차원이 필요합니다.
or categories so we need dimensions to
27:50:27
데이터를 그룹화하고 다른 사이트에서는 질문을 하게 될 것입니다.
group up our data and in the other sites you will be asking questions
27:50:30
얼마나, 몇 개, 무엇의 총합은 얼마인가와 같은 질문입니다.
like how much how many what is the total of something
27:50:33
그래서 항상 무언가를 집계하거나 계산해야 합니다.
so you always need to aggregate or calculate something right and
27:50:37
그것을 위해서는 측정값이 필요하므로 우리는 측정값이 필요합니다.
for that you need the measure so we need the measures in order to
27:50:40
질문에 답하기 위해서 얼마나 많은지, 얼마나 많은지, 그리고 우리는 데이터를 무언가로 그룹화하기 위해 차원이 필요합니다. 그래서 거의 모든 유형의 데이터 분석에서는 차원과 측정값이 필요합니다.
answer the question how many and how much and we need the dimensions in order to group up the data by something so So that's why almost in any type of data analysis, you need dimensions and measures.
27:50:52
그리고 프로젝트가 진행됨에 따라 이것이 더 명확해질 것입니다. 자, 이제 프로젝트 로드맵을 안내하겠습니다.
And this is going to be more clear as we progress in the projects. All right, so now I'm going to walk you through the project roadmap.
27:50:58
그리고 그것을 여섯 단계로 나누었습니다. 그래서 우리는 데이터베이스, 차원, 측정값, 날짜와 같은 다양한 탐색을 할 것입니다.
And I have split that into six steps. So we're going to do different types of explorations like the database, dimensions, measures, dates.
27:51:05
그리고 우리는 크기와 순위와 같은 기본 분석을 할 것입니다. 자, 프로젝트의 첫 번째 단계부터 시작해 보겠습니다.
And we're going to do some basic analysis like the magnitude and the ranking. So let's start with the first step in our projects.
27:51:11
데이터베이스 탐색을 할 것입니다. 예를 들어, 팀에 합류하고 데이터베이스에 접근하게 되었다고 가정해 보겠습니다.
We're going to do database exploration. So let's say that you have joined the team and you got an access to a database.
27:51:21
제가 보통 하는 첫 번째 일은 데이터베이스의 구조를 탐색하는 것입니다.
The first thing that I usually do is that I explore the structure of the database.
27:51:25
데이터베이스 테이블, 뷰, 열에 대한 기본적인 이해를 갖기 위해서입니다.
Just to have basic understandings about the database tables, the views, columns.
27:51:30
우리가 10개의 테이블에 대해 이야기하고 있습니까, 아니면 수백 개의 테이블에 대해 이야기하고 있습니까? 그래서 데이터베이스에 인사하기 위해 몇 가지 쿼리만 필요합니다.
Are we talking about like 10 tables, hundreds of tables? So it is just a few queries in order to say hello to the database.
27:51:37
자, 이제 SQL로 가서 프로젝트의 데이터베이스를 탐색해 보겠습니다. 자, 어떻게 할까요?
So now let's go to SQL and explore the database of our project. So now how are we going to do it?
27:51:42
여기 왼쪽으로 가서 데이터베이스의 객체를 클릭하여 테이블, 뷰, 열 등을 탐색할 수 있습니다.
Either you go to the left side over here and start clicking the objects of your database. and explore the tables, views, columns, and so on.
27:51:49
아니면 제가 보통 하는 더 나은 방법은 쿼리를 사용하여 데이터베이스를 탐색하는 것입니다.
Or a better way that I usually do is that I explore the database using a query.
27:51:54
우리가 할 수 있는 것은 시스템 테이블에서 데이터를 선택하는 것입니다. 왜냐하면 데이터베이스는 테이블과 객체에 대한 메타데이터 정보를 저장하기 때문입니다.
So what we can do, we can go and select data from the system tables because the database stores metadata information about our tables and objects.
27:52:03
그래서 우리는 정보 스키마를 목표로 할 것입니다. 이것은 데이터베이스의 내부 스키마로, 메타데이터와 데이터베이스 구조를 탐색하기 위해 여러 테이블과 뷰가 있습니다.
So we're gonna target an information schema. This is an internal schema in the database where we have like multiple tables and views to explore the metadata and the structure of our database.
27:52:14
예를 들어, 테이블을 살펴볼 수 있습니다. 그러니 쿼리를 실행해 봅시다. 그러면 테이블 목록이 나옵니다.
So, for example, we can go with the tables. So, let's go and query it. And with that, you have a list of tables.
27:52:22
그렇게 하면 카탈로그, 스키마 및 테이블 이름과 같은 여러 정보를 볼 수 있습니다.
And with that, you can see multiple informations like a catalog, the schema, and the table names.
27:52:27
여기에서 객체 유형, 즉 테이블인지 뷰인지 확인할 수 있습니다.
And you can see over here the object type, whether it is a table or a view.
27:52:31
데이터 웨어하우스 프로젝트를 함께 진행했다면 많은 테이블을 찾을 수 있습니다.
If you've done the data warehouse project with me, then you will find a lot of tables.
27:52:36
하지만 데이터 분석만 하고 있다면 세 개의 테이블만 볼 수 있습니다. 즉, 고객, 제품 및 판매입니다.
But if you are just doing the data analysis, you will see only those three tables. So, customers, products, and sales.
27:52:43
그렇게 하면 데이터베이스에 약 15개의 테이블 또는 3개의 테이블이 있음을 알 수 있습니다.
So with that we can see in our database there are like around 15 tables or 3 tables.
27:52:48
출력에서 데이터베이스 이름, 스키마 및 모든 테이블 목록을 볼 수 있습니다.
Now in the output you can see the database name, the schema and a list of all tables.
27:52:54
그리고 우리가 만든 데이터베이스를 사용하고 있다는 것을 잊지 마세요.
And of course don't forget that you are using the database that we created.
27:52:58
그렇게 하면 데이터베이스 내의 모든 테이블에 대한 빠른 목록을 얻을 수 있습니다.
So with that we have a nice quick list with all tables inside our database.
27:53:02
다음 단계로, 데이터베이스 내의 열이 무엇인지 확인해 보겠습니다.
Now the next step we can go and drill down and check what are the columns that we have inside our database.
27:53:07
그에 대해 같은 스키마를 타겟팅할 수 있습니다.
And for that we can as well target the same schema.
27:53:11
정보 스키마에서 모든 열을 선택합니다.
so select star from information schema and
27:53:14
매우 간단하니 테이블 열로 이동합시다.
it is very simple so we're gonna go to the table columns so
27:53:17
이제 실행해 보겠습니다. 그러면 많은 정보가 표시됩니다.
let's go and execute it and now we will see a
27:53:20
여기에서 많은 정보가 표시되며, 데이터베이스에 약 101개의 열이 있습니다.
lot of informations over here so we can see in our database
27:53:23
우리는 약 101개의 열이 있습니다.
we have around 101 columns so
27:53:27
그것으로 우리는 데이터베이스에 있는 모든 열과 내가 보통 하는 것은 특정 테이블에 대해서만 열을 선택하는 것입니다. 그래서 우리는 테이블 이름이 같다고 말할 수 있습니다.
with that we can see all the columns available in our database and what i usually do with that i go and select the columns only for specific table so we We can say where table name equal.
27:53:40
예를 들어 고객 차원을 가져옵시다. 그래서 전체를 쿼리해 봅시다.
Let's get for example the dimension customers. So let's query the whole thing.
27:53:44
그것으로 우리는 이 차원 안에 10개의 열이 있음을 알 수 있습니다.
And with that we can see we have 10 columns inside this dimension.
27:53:48
그리고 이것이 우리 테이블이나 뷰 안에서 열이 정렬되는 방식입니다.
And this is how the columns are sorted inside our table or view.
27:53:52
그리고 우리는 각 열에 대한 모든 메타데이터 정보를 볼 수 있습니다.
And we can see all the metadata information about each column.
27:53:56
이제 보시다시피 우리는 데이터베이스의 구조를 탐색하고 있습니다.
So now as you can see we are now exploring the structure of our database.
27:54:00
이것은 데이터베이스와 프로젝트에 대한 개요를 얻는 데 정말 유용합니다.
And this is really helpful to get an overview of the database and the projects.
27:54:04
우리는 20개의 테이블 또는 수백 개의 테이블에 대해 이야기하고 있습니다.
we're talking about like 20 tables or hundreds of
27:54:08
그리고 우리는 열의 이름을 빠르게 볼 수 있습니다.
tables and we can quickly see the naming of the columns
27:54:11
이 표는 정말 중요한 느낌을 주기 위해 필요합니다.
the tables this is really important to get a feeling about
27:54:14
프로젝트와 기초를 설정합니다.
the projects and sets the foundations for
27:54:17
이제 데이터베이스 구조를 탐색했으니 실제 데이터에 들어갈 수 있습니다.
exploring the data inside those tables all right friends so with that we have done the first step we have explored the database structure and now we can start diving into the actual data.
27:54:27
먼저 탐색할 수 있는 것은 차원입니다.
The first thing that we can explore is the dimensions.
27:54:34
차원 탐색에서 할 일은 데이터베이스 내 각 차원의 고유 값을 식별하는 것입니다.
Okay, so what we're gonna do with the dimension exploration, all what you have to do is to go and identify the unique values of each dimension that we have inside our database.
27:54:43
이것은 카테고리, 국가, 제품 유형을 이해하는 데 도움이 됩니다.
This can help us to understand what are the categories, which countries, what are the product types that we have inside our database.
27:54:49
이를 위해 SQL 키워드 distinct와 함께 차원을 사용하면 됩니다.
And we have a very simple formula for that. So all what you need is the SQL keyword distinct together with any dimension in your like distinct country, distinct category.
27:54:59
예를 들어, 차원인 열을 확인하면 많은 값과 반복되는 항목을 볼 수 있습니다.
So for example, if you are checking any column that is dimension, you can see a lot of values and repeating stuff.
27:55:04
하지만 distinct 열을 사용하면 어떤 일이 발생할까요? 모든 고유 값 목록을 얻을 수 있습니다.
But now once you say distinct column, what can happen? You will get a list of all unique values.
27:55:09
이로 인해 세 가지 다른 유형이 있다는 것을 빠르게 이해할 수 있습니다.
And with that, you can understand quickly how I have three different types.
27:55:13
차원이 세 가지 값인지 백 가지 값인지 확인할 수 있습니다.
So I have ABC and this as well can help you to understand the granularity of your dimension.
27:55:18
이제 데이터베이스 내 차원 값을 탐색해 보겠습니다.
Does the dimension has like three values or hundred value? So it's very simple. Let's go and analyze our dimensions.
27:55:24
첫 번째 테이블인 고객부터 시작하겠습니다.
Okay, so now let's explore the dimension values inside our database. So let's start with the first table, the customers.
27:55:30
이 열을 확인하면 흥미로운 차원인 국가를 찾을 수 있습니다.
And if you check those columns, we have to find an interesting dimension, like for example, the country.
27:55:35
이제 고객이 오는 모든 국가를 탐색할 수 있습니다.
So now what you can do, we can go and explore all the countries our customers come from. So let's go and do that. It is very simple.
27:55:42
distinct를 선택하고, 고객 테이블에서 국가 차원을 가져옵니다.
Select distinct. And then we have our column, the dimension, country from our table, customers.
27:55:47
이제 실행해 보겠습니다. 결과를 보면 여섯 개의 국가가 있습니다.
So let's go and execute it. And with that, we can see the result. We have six countries.
27:55:52
이는 지리적 분포를 이해하는 데 정말 좋습니다.
This is really nice in order to understand the geographical spread.
27:55:55
이제 비즈니스에 대한 첫 번째 통찰력을 얻었습니다.
So we have customers for our business that comes from six different countries. Germany, United States, France, Canada and so on.
27:56:02
이제 비즈니스 내 모든 카테고리를 탐색해야 합니다.
So now with that we have like the first little insights about our business. Now let's jump to another table, the products.
27:56:08
제품 테이블에서 distinct 카테고리를 선택하겠습니다.
So what you have to do is to explore all the categories inside our business, the major divisions.
27:56:14
이제 실행해 보겠습니다. 출력에서 네 개의 카테고리가 있습니다.
So we're going to say select distinct category from our table products.
27:56:19
액세서리, 자전거, 의류, 부품이 있습니다.
So let's go and execute it. Now in the output you can see we have four categories.
27:56:24
비즈니스 내 주요 부문은 무엇인가요?
We have the accessories, bikes, clothing, and components. This is like giving us an overview of the product range.
27:56:30
카테고리뿐만 아니라 하위 카테고리도 보고 싶습니다.
What are the major divisions inside our business? Now the next one I'm digging deeper in this information.
27:56:36
카테고리뿐만 아니라 하위 카테고리도 보고 싶습니다.
So not only I want to see the categories, I would like as well to see the subcategories.
27:56:42
카테고리와 하위 카테고리 간의 관계가 있으므로 새로운 쿼리를 시작하지 않습니다.
I'm not starting a new query because there is of course relationship between the category and the subcategory. Let's go now and execute it.
27:56:48
이제 출력 결과를 보시면, 카테고리가 더 구체적인 그룹으로 나뉘었습니다.
Now you can see the output, our categories are now split into more specific groups.
27:56:53
예를 들어, 여기 자전거 카테고리에는 산악 자전거, 도로 자전거 등이 있습니다.
So for example, the bikes over here, we have mountain bikes, road bikes and so on.
27:56:58
하위 카테고리는 카테고리보다 제품에 대한 더 많은 세부정보를 제공합니다.
So as you can see, the subcategories has more details about the products than the category.
27:57:03
이제 전체 그림을 보기 위해 제품 이름을 가져오겠습니다.
And now in order to get the full picture, we're going to bring now the product name.
27:57:10
이렇게 하면 한 번에 큰 그림을 얻을 수 있습니다.
So with that, we're going to get a big picture in one shot. So now you can see the whole hierarchy of our products.
27:57:17
데이터를 판매하는 방식이 더 흥미롭습니다.
and of course it is more interesting if you go and sell the data by
27:57:20
이 세 가지 정보를 가지고 실행하겠습니다.
those three informations so let me just execute it
27:57:23
이제 데이터를 탐색하면 카테고리가 있습니다.
again so now if you go and explore our data for example we have here the category
27:57:26
액세서리 카테고리 안에는 하위 카테고리가 있습니다.
accessories and we have a subcategory inside it called
27:57:29
이 하위 카테고리에는 세 가지 다른 제품이 있습니다.
lights and in this subcategory we have three different products
27:57:33
테이블의 끝으로 스크롤하면 확인할 수 있습니다.
and if you scroll to the end of our table you can see that
27:57:36
약 295개의 제품이 있으며, 제품 이름의 세분화가 카테고리와 다릅니다.
we have around 295 products so you can see the granularity of the product name is different than the category
27:57:43
하위 카테고리와 이 세 가지 정보는 서로 관련이 있습니다.
and subcategory and all those three informations are related
27:57:47
이제 이러한 차원을 탐색한 후 더 나은 이해를 갖게 되었습니다.
to each other's so now as you can see after exploring those
27:57:50
데이터가 어떻게 구성되어 있는지 이해할 수 있습니다.
dimensions we have now better understanding on
27:57:53
카테고리별로 집계하면 4개의 행만 얻을 수 있습니다.
how the data is organized and this can help us by the
27:57:56
제품별로 집계하면 수백 개의 행을 얻을 수 있습니다.
analyzes if you are aggregating by the category you
27:57:59
이렇게 데이터베이스의 차원을 탐색합니다.
will get only four rows if you are aggregating by the products
27:58:02
데이터 세트 내에서 날짜라는 특별한 유형의 차원으로 깊이 들어가겠습니다.
you will get hundreds of rows so this is how we explore the dimensions of our database okay so now with that we have a clear picture about the dimensions
27:58:11
이제 날짜 열을 탐색할 것입니다.
inside our data sets and now in the next step we're gonna deep dive into one special type of dimensions we have the dates so we're gonna explore the date columns
27:58:23
우리가 가진 날짜의 경계를 탐색하겠습니다.
okay so now what we're gonna do with the date exploration we're gonna go and
27:58:26
데이터 세트에서 가장 이른 날짜와 가장 늦은 날짜를 이해하겠습니다.
explore the boundaries of the dates that we have in
27:58:29
우리 비즈니스에 2년 또는 10년의 시간 범위가 있는지 확인하겠습니다.
the data sets what is the earliest and the latest dates in my data we're gonna understand the time span do we have in our business two years or like
27:58:38
10년이며, 이는 물론 이해하는 데 매우 중요합니다.
10 years and this is of course very important to understand in
27:58:41
다양한 유형의 시간 분석을 하기 위해서입니다.
order later to make different types of time analyzes
27:58:44
우리가 필요한 것은 최소 및 최대 함수입니다.
now the formula for that is very simple all what we need is
27:58:47
가장 이른 날짜와 가장 늦은 날짜를 얻기 위해서입니다.
the min and max functions in order to get the earliest
27:58:50
날짜 열에 적용할 것입니다.
and the latest dates and of course we're going to apply that on date columns
27:58:54
주문 날짜, 생성 날짜, 생년월일의 최소값을 가져올 것입니다.
date dimensions so for example we're going to have like min
27:58:57
데이터 세트에 있는 모든 날짜에 대해, 어떤 날짜를 보더라도
order date max create date min birth dates
27:59:00
데이터 내의 열에서 여러 값을 찾을 수 있습니다.
so any dates that you have in your data sets and here if you look to any date
27:59:03
흥미로운 것은 가장 이른 날짜가 무엇인지 이해하는 것입니다.
column inside your data you will find multiple values but
27:59:06
예를 들어 2018년과 가장 늦은 날짜는 무엇인지입니다.
what is interesting is to understand what is the earliest date
27:59:10
예를 들어 2028년과 함께 우리는
like here for example 2018 and what is the latest
27:59:13
10년의 시간 범위를 이해할 수 있습니다.
date for example 2028 and with that we
27:59:16
날짜 차이 함수를 사용하여, 이제 가서
can understand how we have like time span of 10
27:59:19
우리의 날짜 열에 새로운 공식을 적용합시다.
years using the date diff function so now let's go and
27:59:23
그렇다면 이제 데이터베이스 내의 날짜 정보를 검색해 보겠습니다.
apply our new formula on our date columns all
27:59:26
여기에는 여러 날짜가 있습니다: 주문 날짜, 배송 날짜 및 마감 날짜입니다.
right so now let's search for date informations inside our database and usually you're gonna find a lot in the facts so let's go to the fact sales And here we have like multiple dates, the order date, shipping date and due dates.
27:59:36
이제 주문 날짜의 경계를 탐색해 보겠습니다.
Now let's go and explore the boundaries of the order date.
27:59:39
우리는 첫 번째 및 마지막 주문 날짜를 찾아야 합니다.
So we have the following task, find the date of the first and last order. So how are we going to do that?
27:59:44
우리는 선택하겠다고 말할 것이며, 판매 테이블의 주문 날짜를 대상으로 합니다.
We're going to say select and we are targeting the order date from our table sales.
27:59:51
이제 실행해 보겠습니다. 데이터베이스 내에 많은 값이 있습니다.
So let's go and execute it. And now we can see we have a lot of values inside our database.
27:59:56
이제 첫 번째 날짜를 찾기 위해서, 우리는
So now in order to find the first date, what you're going to do, we're going to
28:00:00
최소 주문 날짜를 얻기 위해 평균 함수를 사용할 것입니다.
go and use the function mean in order to get
28:00:03
이제 마지막 주문 날짜를 찾아보겠습니다.
the minimum order date so we're gonna go and call it first order date so let's go and execute it so now we can see the date of the first order it is in december 2010.
28:00:14
이번에는 최대 주문 날짜를 가질 것입니다.
now let's go and find the date of the last order so
28:00:18
그리고 마지막이라고 부르겠습니다.
we're gonna have this time the max order date
28:00:21
마지막으로 부르자
and let's go and call it last
28:00:24
주문 날짜를 탐색해 보자
order dates so let's go and explore now
28:00:27
2014년이 마지막 주문 날짜이다
the other boundary and with that we can see in january
28:00:31
시스템에서 경계를 탐색했다
2014 it is the date of the last order
28:00:34
주문 날짜의 첫 번째와 마지막
in our system so with that we have explored the boundaries
28:00:37
우리는 이제 네 가지를 이해할 수 있다
of the order dates the first and the last and
28:00:40
우리 사업의 판매 연도
of course we can now understand very quickly that we have four
28:00:43
계산해 보자
years of sales inside our business but we can
28:00:46
두 날짜 사이의 연도를 찾기 위해
go and calculate it so now the task says how many years of
28:00:50
두 날짜를 빼야 한다
sales are available now in order to find the years between those two dates we have another scale function it's called a date diff
28:00:57
세 개의 인수가 필요하다
and now we have to go and subtract two dates now this function
28:01:00
연, 월, 일을 지정해야 한다
needs three arguments the first one you have to specify whether it
28:01:03
가장 작은 날짜로 시작한다
is a year month and day and we start with the smallest
28:01:06
최소 주문 날짜가 될 것이다
date so it's going to be the min order date
28:01:10
최신 날짜가 될 것이다
and then the last argument is going to be the latest
28:01:13
주문 범위라고 부를 수 있다
or the highest date and it's going to be the max order date
28:01:16
연도로서 실행해 보자
and we can go and call it order range in
28:01:19
출력에서 네 해를 볼 수 있다
years okay so let's go and execute it and
28:01:23
월을 확인하고 싶다면
with that you can see in the output we have four years of course
28:01:26
월을 실행해 보자
if you want to go and check the month you can go over here and say
28:01:29
37개월이 있다
month and execute so between those two dates we have
28:01:32
이름을 바꿔야 한다
37 months and of course now we have
28:01:35
주문 날짜의 차원을 탐색했다
to go and rename it so with that we have explored the
28:01:38
고객을 확인해 보자
dimension order dates but what is more interesting
28:01:41
최연소와 최고령을 찾아보자
is to check the customers and here we have the birth date so now what we can do we can go and find the youngest and the oldest
28:01:50
고객의 생년월일을 확인해 보겠습니다.
customer so let's go and do that we're gonna say select min
28:01:53
가장 오래된 생년월일을 찾고 있습니다.
birth dates and with that we are getting the
28:01:56
가장 오래된 생년월일을 찾고 있습니다.
oldest birth date and we will get now
28:01:59
가장 어린 생년월일을 찾고 있습니다.
the max birth date and with that we will get
28:02:03
우리 테이블의 가장 어린 생년월일을 찾고 있습니다.
the youngest birth date from our
28:02:06
테이블 고객들이니까 가봅시다.
table customers so let's go
28:02:09
그리고 이제 가장 오래된 고객의 생년월일을 볼 수 있습니다. 그가 아직 살아있기를 바랍니다. 100세가 넘고 가장 어린 고객은
and explore that now we can see the birth date of the oldest customer i hope he or she is still alive so it is more than 100 years and the youngest
28:02:18
약 40세 정도입니다.
customer is around like 40 years so
28:02:21
우리 사업에는 정말 어린 고객이 없습니다.
we don't have really young customers inside our business and
28:02:24
물론 생년월일을 보고 싶지 않다면
of course if you don't want to see the birth dates you want to see the
28:02:27
나이를 보고 싶다면 실제로 해야 할 일이 매우 간단합니다.
age what you have to do is actually very simple you're
28:02:31
당신은 또한 일수 차이를 사용할 것이고 우리는 연도를 원합니다.
going to use as well day diff and we want a year and
28:02:34
그런 다음 현재 날짜와 시간으로 최소 생년월일을 말할 것입니다. 이를 위해 get이라는 함수가 있습니다.
then we're going to say min birth date with the current date and time and for that we have a function called get
28:02:42
날짜를 호출할 것입니다. 가장 오래된 나이라고 부를 것입니다.
date i'm gonna call it oldest age
28:02:45
그래서 여기에서 이것을 실행하면
so if you go and execute this one over here
28:02:48
가장 오래된 고객의 나이를 볼 수 있습니다. 109세입니다.
you can see the age of the oldest customer it is 109
28:02:52
물론 가장 어린 고객에 대해서도 같은 작업을 할 수 있습니다.
and of course you can do the same thing for the youngest
28:02:55
단지 이것을 최대값으로 바꾸면 됩니다.
if you just replace this with max and
28:02:58
여기에서 우리는 가장 어린 나이를 가지고 있습니다. 그러니
here we have the youngest age so let's
28:03:01
가서 실행해 봅시다. 39세입니다. 친구들, 이것이 날짜의 경계를 탐색하는 방법입니다. 첫 번째 날짜와 마지막 날짜를 찾고
go and execute it it is 39 so my friends this is how we explore the boundaries of a date and by finding the first date and the last
28:03:10
그 사이의 연도를 통해 우리는 우리 사업의 시간 범위에 대해 더 잘 이해하고 있습니다.
date and the years between them, we are having now more understanding of the time span of our business.
28:03:16
그리고 이것은 나중에 다양한 복잡한 분석기를 만드는 데 도움이 될 것입니다. 이것이 날짜를 탐색하는 방법입니다. 알겠습니다.
And that's going to help us later by making different type of complex analyzers. So this is how we explore the dates. All right.
28:03:22
그래서 이제 우리는 프로젝트의 범위와 데이터 세트 내의 날짜 범위에 대한 명확한 그림을 가지고 있습니다.
So with that, we have now a clear picture about the scope of our projects and the date range inside our data sets.
28:03:28
이제 다음 단계에서는 두 번째 유형의 데이터인 측정을 탐색할 것입니다.
Now in the next step, we're going to go and explore the second type of data, the measures.
28:03:37
알겠습니다. 그렇다면 측정을 탐색하는 것이 정확히 무엇인가요? 우리가 할 일은 우리 사업의 주요 지표, 큰 숫자, 데이터의 가장 높은 집계 수준을 계산하고 찾는 것입니다.
All right. So now what is exactly exploring the measures? What we're going to do is to calculate and find out the key metrics of our business, the big numbers, the highest level of aggregations of our data.
28:03:49
그 공식은 매우 간단합니다. 우리는 SQL에서 집계 함수인 합계, 평균, 개수를 사용하여 데이터 세트 내의 모든 측정값을 계산할 것입니다.
And the formula for that is very simple. We're going to go and use the aggregate functions in SQL, like the sum average count for any measure inside our data sets.
28:03:58
예를 들어, 우리는 판매 가치를 요약하여 총 판매를 찾고, 평균 가격을 찾고, 판매된 모든 항목에 대한 큰 숫자를 얻기 위해 수량의 합계를 찾을 것입니다.
So for example, we're going to find the total sales by summarizing the sales value, finding the average price, finding the sum of quantity in order to have a big number about all sold items.
28:04:09
항상 집계 함수와 함께 측정값이 필요합니다. 예를 들어, 많은 값이 있는 열이 있다면 그 값을 요약하면 240과 같은 결과를 얻을 수 있습니다.
So always an aggregate function together with a measure. So for example, if you have a column where you have a lot of values and you go and summarize all those values, you will get, for example, 240.
28:04:19
이것은 핵심 지표입니다. 이것은 가장 높은 수준의 집계이며 값이 전혀 나뉘지 않습니다.
So this is a key metric. This is the highest level of aggregations and the value is not splitted at all.
28:04:25
예를 들어, 우리는 이것이 우리 비즈니스의 총 수익이라고 말합니다. 이것이 우리가 측정값을 탐색한다고 말하는 것입니다.
So for example, we say this is the total revenue of our business. And this is exactly what we mean by exploring the measures.
28:04:31
우리는 이러한 큰 숫자를 얻을 것입니다. 이제 데이터 세트 내의 측정값에 집계 함수를 적용해 보겠습니다.
We will get those big numbers. So now let's go and apply those aggregate functions to the measures that we have inside our data sets.
28:04:38
좋습니다. 이제 우리는 우리 비즈니스에서 가장 중요한 큰 숫자에 집중할 것입니다.
Okay, so now we're going to go and spotlight on the big numbers that matters the most of our business.
28:04:44
이제 제가 수집한 세 개의 테이블을 기반으로 다음 질문이 있습니다. 하나씩 해결해 보겠습니다.
So now based on those three tables I have collected here, the following questions. So let's go and solve them one by one.
28:04:50
첫 번째 질문은 총 판매를 찾는 것입니다. 그래서 우리는
The first one is find the total sales. So we're
28:04:53
판매 금액에 대한 합계 함수를 사용하여 총 판매를 요약할 것입니다.
going to go and summarize by using the sum function for the sales amount as total sales from our table fact sales.
28:05:03
그럼 실행해 보겠습니다. 이것은 우리 비즈니스의 총 판매 금액입니다. 약 2900만입니다.
So let's go and execute it. So this is the total amount of sales in our business. It is around 29 millions.
28:05:11
이것은 우리 비즈니스의 총 수익입니다. 이제 두 번째 질문으로 넘어갈 수 있습니다. 얼마나 많은 항목이 판매되었는지 보여주세요.
So this is the business total revenue. Now we can go to the second one. It says show how many items are sold.
28:05:18
이번에는 같은 테이블에서 다른 열이 필요합니다. 질문은 얼마나 많은 항목인가요?
So this time we need another column, but from the same table from the fact sales. So the question is how many items?
28:05:25
즉, 우리는 수량을 원하며 같은 함수를 사용할 것입니다.
That means we want the quantity and we're going to stay with the same function.
28:05:30
우리는 수량의 모든 값을 요약하고 이를 총 수량이라고 부를 수 있습니다.
So we are summarizing all the values of the quantity and we can call it total quantity.
28:05:35
그것을 탐색해 보겠습니다. 우리 비즈니스는 약 60,000개의 항목을 판매했으며 이 60,000개의 항목은 약 3000만을 생성했습니다.
Let's go and explore that. So we can see our business did sold around 60,000 items and these 60,000 items did generate around 30 million.
28:05:45
계속 진행해 보겠습니다. 다음 질문은 평균 판매 가격을 찾는 것입니다. 즉, 우리는 같은 테이블을 대상으로 합니다.
So let's keep going. The next question, find the average selling price. So that means we are targeting the same table.
28:05:51
여기 가격 정보가 있습니다. 우리는 가격이라고 말할 것입니다. 이번에는 집계 함수가 평균이 될 것입니다.
And here we have the price information. So we're going to say the price. This time the aggregate function is going to be the average.
28:05:58
우리는 이를 평균 가격이라고 부를 것입니다. 실행해 보겠습니다. 우리 비즈니스의 평균 가격은 486입니다.
And we're going to call it average price. So let's go and execute it. So the average price in our business is 486.
28:06:05
즉, 우리 비즈니스는 비싼 상품을 판매하고 있습니다. 이제 다음 질문으로 넘어갑니다.
So that means our business is selling like expensive items. Now let's go to the next question.
28:06:11
총 주문 수를 찾으라고 합니다. 이를 위해 우리는 count 함수를 사용할 것입니다.
It says find the total number of orders. And for that we're going to go and use the function count.
28:06:17
주문 번호를 세어볼 수 있습니다. 주문 번호, 총 주문입니다.
And we can count the order numbers. So order number, total orders.
28:06:23
실행해 보겠습니다. 60,000개의 주문이 있다고 합니다.
Let's go and execute it. So it says we have 60,000 orders.
28:06:28
이제 count 함수를 사용하고 있으므로, 제가 보통 하는 것은 동일한 것을 세지만 distinct를 사용합니다.
And now as you are working with the count function, what I usually do, I try to count the same thing, but using distinct.
28:06:36
distinct 주문 번호입니다. 여기서 제가 하려는 것은 먼저 주문 번호의 중복을 제거한 다음 세는 것입니다.
So distinct order number. So what I'm trying to do here is first eliminate any duplicates in the order number and then count it.
28:06:44
같은 주문을 두 번 세고 싶지 않습니다. 그러니 실행해 보겠습니다.
I don't want to count the same order twice inside our sales. So let's go and execute that.
28:06:51
이제 보시다시피, 우리는 60,000개의 주문 중 27,000개만 있습니다.
Now, as you can see, we have only 27,000 orders out of 60,000.
28:06:56
이것은 같은 주문이 데이터베이스에 반복되고 있다는 것을 의미합니다. 실제로 살펴보겠습니다.
So that means the same order is repeating in our database. Let's have actually a look.
28:07:02
우리 테이블에서 모든 항목을 선택해 보겠습니다. 그리고 살펴보겠습니다.
So select star from our table. And let's go and have a look.
28:07:07
여기 첫 번째 주문에서 보시다시피, 같은 주문이 세 번 반복됩니다.
Now, as you can see, from the first order over here, you can see the same order is repeated three times.
28:07:12
그것은 이 고객이 같은 주문으로 세 가지를 주문했기 때문입니다.
And that's because this customer did order three things in the same order.
28:07:17
그렇다면 이제 주문의 정의는 무엇인가요? 보통 전체가 하나의 주문입니다.
So now of course, what is the definition of order? Usually the whole thing is one order.
28:07:22
정확한 주문 수를 얻기 위해서는 먼저 모든 중복을 제거하고, 그 다음에 우리가 가진 주문 수를 세기 위해 distinct를 사용해야 합니다.
That's why in order to get an accurate number of orders, you have to go and use a distinct in order to eliminate first all duplicates and then count how many orders we have.
28:07:32
이 시나리오에서, 우리 비즈니스에는 약 27,000개의 주문이 있다고 말할 것입니다.
So in this scenario, I'm going to say in our business, we have around 27,000 orders.
28:07:37
그래서 카운트 함수를 사용하는 것이 조금 까다로운 이유입니다. 항상 distinct 사용 전후의 숫자를 비교해 보세요.
So that's why it is a little bit tricky using the count function. Always try to compare the numbers before and after using distinct.
28:07:44
다음 항목으로 넘어가겠습니다. 총 제품 수를 찾으라고 합니다.
So let's keep going to the next one. it says find the
28:07:47
총 제품 수는 매우 간단하므로 선택하겠습니다.
total number of products so it is very simple we're gonna say select
28:07:50
제품 키를 세고
count and we're gonna say product key as
28:07:54
테이블에서 총 제품 수를
total products from the table
28:07:57
실행해 보겠습니다.
goes products so let's go and execute
28:08:01
보시다시피 우리는 295가 있습니다.
it so as you can see we have 295 and
28:08:04
distinct를 만들어 확인하면 같은 숫자를 얻을 수 있습니다. 즉, 중복이 없다는 의미입니다.
if you go and make a distinct just to check you will get the same number so that means there is no duplicates and of course you can go and
28:08:12
제품 이름을 세면 제품의 이름이
count the product name instead the names of the product is
28:08:15
고유하므로 같은 숫자를 얻고 있습니다.
unique so that's why we are as well getting the same numbers
28:08:19
그럼 계속해서 총 고객 수를 찾아보겠습니다.
so that's it let's continue find the total
28:08:22
고객 수를 세는 것도 같은 방식입니다.
number of customers so the same thing select count
28:08:25
고객 키를 사용하여 실행해 보겠습니다.
and you can go with the customer key for example from
28:08:29
우리 시스템에는 18,000명의 등록된 고객이 있습니다.
gold dimension customers and i'm gonna call it as total customers so let's go and execute it so we can see
28:08:37
다음 항목은 총 고객 수를 찾으라고 합니다.
our system we have 18 000 registered customers
28:08:40
주문을 한 고객 수를 찾으라고 합니다.
now the next one it says find the total number of
28:08:43
주문을 한 고객의 총 수를 찾아야 합니다.
customers that has placed an order so that means
28:08:47
우리 데이터베이스에 고객이 있다고 해서
having a customer inside our database doesn't mean that
28:08:50
이 고객이 이미 주문을 했다는 의미는 아닙니다.
this customer did already placed an order maybe we have customer
28:08:53
등록만 하고 아무것도 주문하지 않은 고객도 있을 수 있습니다.
that's just registered and didn't order anything so
28:08:56
우리가 할 일은 동일한 쿼리를 가져오되
what we're gonna do we're gonna take the same query but instead of
28:08:59
고객 테이블을 대상으로 하는 대신
targeting the customers table we're gonna target our fact
28:09:02
판매를 대상으로 할 것입니다. 이제 실행해 보겠습니다.
the sales so let's go and execute it so
28:09:06
지금 보시다시피 16,000이 나옵니다. 말이 안 됩니다.
now as you can see we are getting 16 000 which makes no sense
28:09:09
하나의 고객이 여러 개의 주문을 할 수 있기 때문입니다.
because one customers might order multiple
28:09:12
그래서 우리가 할 일은 distinct를 사용할 것입니다.
stuff so what we're gonna do we're gonna say distinct and
28:09:15
다시 생성해 보겠습니다. 이제 더 정확해졌습니다. 약
let's create again so now it is more correct we are getting around
28:09:19
18,000명의 고객이 나옵니다. 이제 하나씩 비교해 보겠습니다.
18 000 customers now we can go and compare them one
28:09:22
하나씩 비교해 보겠습니다. 보시다시피 같은 숫자가 나옵니다.
by one so as you can see we are getting the same numbers so
28:09:25
즉, 모든 등록된 고객이 이미
that means all our registered customers did already
28:09:29
주문을 했다는 의미입니다. 숫자가 일치하므로
placed an order because the numbers are matching so it
28:09:32
매우 간단합니다. 집계 함수를 사용하고
is very simple we are just using an aggregate functions and with
28:09:35
그 덕분에 이러한 키 값을 얻고 있습니다. 제가 보통 하는 것은
that we are getting those key values but what i usually do
28:09:38
모든 측정을 하나의 쿼리로 수집하는 것입니다.
is that i collect all those measures in one query in
28:09:41
모든 주요 숫자의 개요를 얻기 위해서입니다.
order to have an overview of all key numbers
28:09:44
각각을 개별적으로 쿼리하는 대신
in our business so instead of me querying each one of them
28:09:47
한 번에 결합합니다. 이제
individually i combine them in one go so now
28:09:50
우리가 할 일은 모든 주요 지표를 보여주는 보고서를 생성하는 것입니다.
what we're gonna do we're gonna generate a report that shows all key metrics of our business so how i usually do it i'm gonna go and get the first query for the total sales and and put it over here.
28:10:00
이제 두 개의 열만 만들 것입니다. 첫 번째는 측정의 이름이고 두 번째는 측정의 값입니다.
And now I'm going to build only two columns. The first one is the name of the measure and the second one is the value of the measure.
28:10:07
제가 무슨 뜻인지 보여드리겠습니다. 여기 있는 것은 총 판매라고 부르지 않을 것입니다.
So let me show you what I mean. Now, this one over here, I will not call it total sales. I'm going to make it like generic.
28:10:12
측정 값이라고 하겠습니다. 그 전에 정적 문자열 값으로 다른 열을 만들 것입니다.
So I'm going to say measure value. And before it, we're going to make another column from a static string value is the total sales.
28:10:22
우리는 이를 측정 이름이라고 부를 것입니다. 그래서
And we're going to call it measure name like this. so
28:10:25
여기서 이 작업을 실행해 보겠습니다. 그래서 측정
let's go and just execute this one over here so the measure
28:10:28
총 판매량이므로 더 이상
is total sales so it is not anymore like
28:10:31
열 이름이 아니라 출력의 값이 됩니다. 그리고
the column name it is now a value in the output and the
28:10:34
측정 값은 현재 약 3000만입니다. 제가 할
measure value is like around 30 millions now what i'm
28:10:37
일은 두 번째 행으로 또 다른 측정을 추가하는 것입니다.
gonna do i'm gonna go and add another measure as a second row
28:10:41
그렇게 하기 위해 우리는 유니온 올을 사용할 것입니다.
and in order to do that we're gonna use the union all and
28:10:44
그런 다음 여기에서 전체를 복사하고 총 수량이라고 말합니다.
then copy the whole thing over here and say total quantity
28:10:48
그리고 우리는 측정을 수량으로 변경할 수 있습니다.
and we can change the measure to quantity
28:10:51
이제 두 개를 선택하고 쿼리해 보겠습니다.
so now let's select both of them and query
28:10:54
보시다시피 이제 두 개의 큰 숫자가 있습니다.
and as you can see we have now the two big numbers in
28:10:57
하나의 쿼리에서 총 판매량과 총 수량입니다.
one query so the total sales and the total quantity so
28:11:01
이제 우리가 할 수 있는 것은 이 모든 큰 숫자와
now what we can do we can go and collect all those big numbers and
28:11:04
측정을 수집하여 하나의 쿼리에 넣는 것입니다.
measures and put it in one query so that we have the
28:11:07
그래서 평균 가격, 총 주문 수, 제품 고객 수를 얻을 수 있습니다.
average price the total number of orders product customers and
28:11:10
또한 SQL은 여기서 열의 수와
as well you can go and target different tables because sql
28:11:13
열의 데이터 유형이 일치해야 한다는 것에만 신경 씁니다.
cares here only about the number of columns and the
28:11:17
이제 쿼리를 실행해 보겠습니다. 이제
data type of columns must be matching so now let's go
28:11:20
단일 쿼리에서 큰 숫자와 주요 지표를 볼 수 있습니다.
and query this and now in single
28:11:23
우리 비즈니스의 총 판매량, 총 수량, 평균을 볼 수 있습니다.
query we can see the big numbers the key metrics
28:11:26
가격 등이 있습니다. 이것은 모든 비즈니스에 대해 생성할 수 있는 슈퍼 리포트입니다.
of our business we can see the total sales total quantity average
28:11:30
한 번에 전체를 볼 수 있습니다.
price and so on this is a super report where you can generate
28:11:33
비즈니스에 대한 큰 그림을 얻는 방법입니다. 일반적으로 이렇게 합니다.
it for any business where you have in one go the full
28:11:36
새 데이터베이스를 탐색할 때 모든 것을 넣습니다.
big picture about the business so this is how i generally do
28:11:40
큰 숫자와 측정을 하나의 쿼리에 넣어 비즈니스에 대한 더 나은 이해를 돕습니다.
if i'm exploring a new database i put all those
28:11:43
큰 숫자와 측정값을 하나의 쿼리에 넣어 비즈니스를 더 잘 이해할 수 있습니다. 자, 친구들, 이제 우리는 데이터 세트의 차원과 측정값에 대한 명확한 이해를 갖게 되었습니다.
big numbers and measures in one query to have better understanding about the business all right my friends so with that we have now a clear understanding about the dimensions and as well the measures of our data sets.
28:11:55
이제 다음 단계에서는 통찰력을 생성하기 위해 데이터를 결합하기 시작할 것입니다. 그리고 우리는 아주 기본적인 분석인 크기 분석에 집중할 것입니다.
Now in the next step we're going to go and start combining stuff together in order to generate insights and we're going to focus now in a very basic analysis it is the magnitude analysis.
28:12:08
좋습니다. 그럼 크기 분석이 정확히 무엇인가요? 이는 서로 다른 카테고리와 차원 간의 측정값을 비교하는 것입니다. 이를 통해 서로 다른 카테고리의 중요성을 이해할 수 있습니다.
Okay so now what is exactly a magnitude analysis? It's all about comparing the measure values across different categories and dimensions and this can help us of course to understand the importance of different categories.
28:12:20
이제 그에 대한 공식은 흥미로울 수 있습니다. 이번에는 데이터를 혼합할 것입니다.
Now the formula for that can be interesting. So now this time we will be mixing stuff together.
28:12:25
먼저 특정 측정값을 집계해야 합니다. 그리고 차원별로 말합니다.
So first we have to go and aggregate a specific measure. And then we say by dimension.
28:12:30
여기서 측정을 분할하기 위해 차원이 필요합니다. 복잡하게 들리지만 매우 간단하고 기본적입니다.
We need here the dimension in order to split the measure. It sounds complicated but it is very simple and basics.
28:12:36
예를 들어, 국가별 총 판매량, 카테고리별 총 수량, 제품별 평균 가격을 말할 수 있습니다.
So for example we can say the total sales by country. The total quantity by category. The average price by products.
28:12:43
고객별 총 주문 수를 말할 수 있습니다. 이 공식을 따르면 끝없는 통찰력을 생성할 수 있습니다.
The total orders by customer. And if you follow this formula you will be generating endless amount of insights.
28:12:50
단순히 어떤 측정값과 어떤 차원을 결합하기만 하면 새로운 통찰력이 생깁니다. 이렇게 보일 것입니다.
By just combining any measure with any dimension, you can call it, it is a new insight. So it's going to look like this.
28:12:56
예를 들어, 하나의 측정값이 600이라고 가정해 보겠습니다. 이제 이 측정값을 차원과 함께 넣으면 어떤 일이 발생할까요?
If you have one measure that is like, for example, 600. And if you put now this measure together with the dimension, what can happen?
28:13:02
이 600은 차원 값에 따라 나뉘게 됩니다. 그래서 A는 200, B는 300, C는 100이 될 수 있습니다.
This 600 is going to be split by the dimension values. So A can have like 200, B can have 300, and C, 100.
28:13:10
이제 이를 통해 카테고리를 비교할 수 있습니다, 맞나요?
And now with that, we can go and compare those categories, right?
28:13:13
이제 카테고리 B가 가장 높은 측정값을 가지고 있고 C가 가장 낮은 것을 볼 수 있습니다.
So we can see now that category B has the highest measure and the C has the lowest.
28:13:18
이것은 측정값의 값을 비교하는 데 도움이 됩니다. 가장 좋은 카테고리와 가장 나쁜 카테고리가 무엇인지.
and this helps us to compare the values of the measure what is the
28:13:21
가장 좋은 카테고리와 가장 나쁜 카테고리가 무엇인지. 이것은 매우 기본적인 분석입니다.
best category and what is the worst category so this is
28:13:24
이제 이 공식을 우리의 데이터 세트에 적용해 보겠습니다. 자, 이제 모든 것을 분해해 보겠습니다.
very basics analysis so let's go and apply this formula on
28:13:28
우리의 데이터 세트를 이제 모든 측정을 차원별로 나누어 보겠습니다. 여기 몇 가지 흥미로운 예를 준비했습니다.
our data sets okay so now let's go and break all our
28:13:31
먼저 고객의 총 수를 나누어 보겠습니다.
measures by dimensions so here i've prepared a few interesting examples
28:13:34
우리가 배운 대로, 국가별로 18,000명이 있습니다.
where first we're gonna break the total number of customers
28:13:37
따라서 측정값은 총 고객 수이고,
as we learned we have 18 000 by the countries
28:13:41
차원은 국가가 될 것입니다. 그러니 그에 대한 쿼리를 작성해 보겠습니다.
so the measure is total customers and the
28:13:44
우리는 선택할 것입니다. 그래서 우리가 추가할 첫 번째 것은
dimension gonna be the countries so let's go and write the query for that
28:13:47
차원입니다. 그래서 그것은 국가가 될 것이고, 그 다음에 필요한 것은
we're going to select so the first thing that we're going to go and add is
28:13:50
측정값입니다. 고객 수를 세는 것이 될 것입니다.
the dimension so it's going to be the country and then we need the
28:13:53
고객 키의 수가 될 것입니다. 그래서 이것은 우리에게 제공할 것입니다.
measure it's going to be the count of the
28:13:56
고객 키이므로 이것은
customer key so this will give us
28:13:59
총 고객 수를 제공하고 테이블을 선택해야 합니다
the total customers and we need to select our table
28:14:03
차원 고객이 될 것이고 물론
so it's going to be the dimension customers and of course
28:14:06
데이터를 국가별로 그룹화해야 합니다
we have to go and group up the data by the countries so
28:14:09
국가별로 그룹화하므로 실행해 봅시다
group up country so let's go and
28:14:12
국가 목록을 다시 볼 수 있습니다
execute it and with that you see again the list of
28:14:16
국가별 총 고객 수가 있습니다
countries so we have our six countries and then the
28:14:19
국가별 고객 분포를 볼 수 있습니다
total customers for each country so with that we
28:14:22
우리가 일반적으로 하는 것은 데이터를 정렬하는 것입니다
can see the distribution of customers by the country
28:14:25
총 고객 수를 이렇게 측정하고
but what we usually do is that we go and sort the data by the
28:14:28
내림차순으로 정렬할 것입니다
measure the total customers like this and
28:14:31
고객 수가 가장 많은 국가를 얻을 수 있습니다
we're gonna sort it by descending so with that we will get first
28:14:35
미국, 호주, 영국 337
the countries with the highest customers so let's go and execute it so now we can see in the results the highest number of customers come from united
28:14:43
국가 정보가 없는 고객
states then australia united kingdom 337
28:14:47
사용할 수 없습니다. 정말 간단합니다
customers without the country informations
28:14:51
따라서 총 고객 수를 나누었습니다
it is not available so that's it right it is very simple
28:14:54
차원인 국가별로 나누었습니다
so with that we have splitted the total number of customers
28:14:57
다양한 유형의 차원으로 데이터를 나눌 수 있습니다
by a dimension the country now of course we can go and split
28:15:00
다음은 총 고객 수를 찾는 것입니다
the data by different type of dimension so for
28:15:04
성별로, 같은 측정값이 있습니다
the next one we are saying find the total customers by
28:15:07
하지만 다양한 유형의 차원으로 데이터를 나누고 있습니다
gender so here's the same thing we have the same measure the total customers
28:15:10
그냥 복사하고 붙여넣기 하여 성별로 전환합니다
but we are splitting the data by different type of dimension
28:15:14
이제 성별의 세분화가 보입니다
so just copy and paste and now instead of countries we just gonna switch it to gender and over here and that's it so let's go and execute
28:15:23
국가와는 다릅니다. 여기에는 세 가지 값만 있습니다
so now as you can see the granularity of the gender over here
28:15:26
남성과 거의 고르게 나뉘어 있습니다
is different than the countries we have here only three values
28:15:29
남성과 여성 고객이 거의 균등하게 나뉘어 있는 것을 볼 수 있습니다.
and we can see it is almost split evenly between male
28:15:33
고객의 인구 통계를 이해하는 데 도움이 될 수 있습니다.
customers and female customers and of course this can help us
28:15:36
매우 간단하게, 우리는 단순히 차원을 바꿨습니다.
to understand the demography of our customers
28:15:39
차원을 바꿨으므로 재료별로 나눌 수 있습니다.
and as you can see it was very simple we just switched the
28:15:42
상태와 같은 다른 요소로 나눌 수 있습니다. 이제 총합을 나눠봅시다.
dimension so you can go and split as well by the material
28:15:45
카테고리별로 제품을 나누겠습니다. 사실 쿼리는
status and so on now let's go and split that total
28:15:49
매우 간단할 것입니다. 선택하고 여기서 동일한
products by the category well actually the query is
28:15:52
집계 함수를 사용할 것입니다. 제품 수를 계산합니다.
going to be very simple as well so select and here we're going to have the same
28:15:55
우리 테이블의 총 제품 수입니다.
aggregate function the count products key as
28:15:59
금 차원 제품이고, 그 다음에는 그룹화할 것입니다.
total products from our table
28:16:03
차원 카테고리별로 그룹화하고 정렬할 것입니다.
gold dimension products and then we're going to group up
28:16:06
차원 카테고리별로 그룹화하고 정렬할 것입니다.
by the dimension the category and we're going to order
28:16:09
가장 높은 것부터 가장 낮은 것까지 정렬하겠습니다. 실행해 봅시다.
by as well the same thing total products distinct
28:16:12
우리가 가진 제품 수를 확인할 수 있습니다.
from the highest to the lowest so let's go and execute
28:16:16
각 카테고리에서 가장 큰 것을 볼 수 있습니다.
it and with that we can see how many products do we have
28:16:19
구성 요소가 가장 큰 카테고리이고, 그 다음은 피크입니다.
in each of those categories and we can see the biggest
28:16:22
우리가 가진 7개의 제품이 흥미롭습니다.
category the components and after that the pikes
28:16:25
어떤 카테고리에도 속하지 않는 널이 있습니다. 정말 흥미롭습니다.
and this is interesting that we have seven products where we have
28:16:28
다음으로 넘어가 보겠습니다. 여기서 무엇을 가지고 있나요?
nulls where they don't belong to any category this is really
28:16:32
각 카테고리의 평균 비용이 무엇인지 보겠습니다.
nice let's go to the next one what do we have over here what
28:16:35
이것은 다른 스타일의 질문과 같습니다. 하지만 결국
is the average costs in each category so this
28:16:38
여기서 평균 비용을 확인할 수 있습니다.
is like different style of question but at the end we can have the
28:16:41
측정값이며 카테고리는 우리의 차원입니다.
same thing we have over here the average costs this
28:16:44
카테고리별 평균 비용을 찾으라고 말하고 있습니다.
is the measure and the category is our dimension it's
28:16:47
카테고리별 평균 비용을 찾으라고 말하고 있습니다.
like we are saying find average costs by category
28:16:51
우리가 할 일은 같은 쿼리를 복사하는 것입니다.
so what we're gonna do we're gonna go and copy the same query and
28:16:54
차원은 동일하므로 카테고리는 같지만
the dimension is the same so the categories but the
28:16:57
측정값이 다릅니다. 우리는 총 제품에 대해 이야기하고 있지 않습니다.
measure is different we are not talking about the total products
28:17:00
우리는 평균이라고 말할 것이고, 여기서 비용 열을 가질 수 있습니다.
we are gonna say average and here we can have the column costs and let's go rename it average costs so that's it as well for the order by
28:17:09
새 측정값을 사용해야 하므로 실행해 보겠습니다.
you have to use the new measure so let's go and
28:17:12
이제 가장 비싼 카테고리는 자전거입니다. 자전거는 액세서리에 비해 비용이 많이 듭니다.
execute it so now we can see the most expensive category is the bikes costs a lot compared to the accessories of course so you can see the accessories is only 13 and the bikes is 900.
28:17:24
이것은 각 카테고리가 얼마나 비싼지에 대한 통찰력을 제공합니다.
so this is as well gives us insights about how expensive each
28:17:28
카테고리이며, 항상 같은 템플릿을 사용하고 있습니다.
category is and as you can see it is always the same templates we are splitting specific measure by a dimension so let's keep going to the next one it says what is the total revenue
28:17:39
각 카테고리에 대해 생성된 총 수익은 무엇인가요?
generated for each category so again here the question
28:17:42
카테고리별 총 수익을 찾아야 합니다.
is find the total revenue by category so
28:17:46
여기서 총 수익은 측정값입니다.
the total revenue here is the measure and the category again
28:17:49
차원입니다. 이제 총 수익은
is the dimension so now the total revenue comes from
28:17:52
사실이며, 카테고리는 이번에 차원에서 가져옵니다.
the fact and the category comes this time from the dimension
28:17:55
즉, 테이블을 조인해야 합니다.
so that means we have to go and join tables right so how we're gonna do
28:17:58
먼저 선택 스타에서 시작하겠습니다.
it let's go and start with the select star from
28:18:01
사실 테이블에서 항상 시작하고 싶습니다.
and i would like always to start from the fact table so
28:18:05
사실 판매 f와 조인할 것입니다.
fact sales f and then we're gonna gonna go and join it with
28:18:08
차원과 조인할 때 왼쪽 조인을 사용합니다.
the dimension and usually i go with the left join in order to
28:18:11
무언가를 잃지 않기 위해서입니다.
not lose anything because if you use an inner join you
28:18:14
내가 원하지 않기 때문에 차원과 왼쪽 조인합니다.
might lose in the facts few orders and few sales
28:18:17
제품이 될 것이며, 그 키는
i don't want that so left join with the dimension this
28:18:20
매우 간단할 것이며, 제품 키가 될 것입니다.
one's gonna be the products and the key for that's gonna be
28:18:23
우리는 사실에서 판매 권리를 가져와야 합니다.
very simple gonna be the product key and the same thing for the facts so with that we joined the fact table with the dimension so now we have to go and pick what do
28:18:32
판매 금액과 제품에서 카테고리를 가져와야 합니다.
need we need from the fact the sales rights so sales
28:18:35
그리고 우리는 데이터를 카테고리별로 그룹화하고 싶습니다.
amount and we need from the products the category
28:18:39
우리는 데이터를 카테고리별로 그룹화하고 싶습니다.
and we want to group up the data by the category
28:18:42
이 부분은 완료되었습니다. 이제
so so this part is done what is
28:18:45
물론 누락된 것은 집계입니다. 그래서 우리는 집계하고 있습니다.
missing is of course the aggregations so we are aggregating
28:18:49
실제로 판매량입니다. 일부 판매와
actually the sales so some sales and
28:18:52
우리는 이를 총 수익이라고 부를 수 있습니다.
we can call it total revenue so like
28:18:55
이제 우리는 데이터를 정렬할 수 있습니다.
this and of course we can go and order the data by
28:18:59
우리의 측정 기준에 따라 총 수익을
the total revenue by our measure and distinct
28:19:02
가장 높은 것부터 가장 낮은 것까지 정렬할 수 있습니다.
from highest to lowest so you can see it is exactly like the
28:19:05
이전과 정확히 같지만, 여기 데이터는 하나의 테이블에서만 나오지 않습니다.
previous one but here the data doesn't come from only one table
28:19:08
여기서는 두 개의 테이블에서 나오며, 측정값은 사실에서 나옵니다.
here it comes from two tables so the measure come from the facts
28:19:11
차원은 차원 제품에서 나오며,
and the dimension come from the dimension products and
28:19:14
차원은 모든 설명을 포함하고 있습니다.
this is classic right the dimension has all those descriptions
28:19:18
제품에 대한 세부정보와 카테고리와 같은
and details about the products like the categories
28:19:21
사실 테이블은 모든 측정값과 날짜를 포함하고 있습니다.
and the fact table has all those measures and dates
28:19:24
우리가 우리의 측정값을 계산하기 위해 사용하는 것들입니다.
that we use in order to calculate our measures so
28:19:27
이제 실행해 보겠습니다. 출력에서 볼 수 있듯이
that's it let's go and execute it now as you can see in the output
28:19:31
자전거 카테고리가 가장 많은 수익을 가져옵니다.
the category bikes is bringing the most of
28:19:34
여기서는 약 2800만 달러입니다.
revenue so here it's like in millions 28 millions
28:19:37
판매량과 액세서리 및 의류가
of sales and the accessories and the clothing is
28:19:40
자연스럽게 많은 수익을 가져오고 있습니다.
naturally bringing a lot of like revenue both of them are
28:19:43
둘 다 100만 달러 이하입니다. 이를 통해 우리는 자전거 판매로 많은 돈을 벌고 있다는 것을 이해할 수 있습니다.
below like 1 million so with that you can understand our business is making a lot of money selling bikes right so my friends as we are exploring the data we are understanding more and more about our business right?
28:19:55
다음으로 넘어가겠습니다. 여기 질문이 있습니다. 각 고객이 생성한 총 수익은 얼마입니까?
So let's keep going to the next one. We have here the question, what is the total revenue generated
28:20:00
이제 우리는 가장 많은 지출을 한 고객을 찾고 싶습니다.
by each customer so now we want to find out the top
28:20:03
사실 테이블에서 시작하여
spender right select star and as well we start from
28:20:07
고객과 조인할 것입니다.
the fact table and this time
28:20:10
고객과 조인할 것입니다.
we're gonna lift join it with the customers right so
28:20:13
차원 고객과 조인할 것입니다.
the dimension customers and we're gonna go join
28:20:16
고객 키와 함께 고객의 이름과 몇 가지 세부 정보를 가져올 것입니다.
the data so we're gonna use the customer key for the join and what we're gonna do we're gonna go and get maybe the customer key and let's go and get
28:20:24
그리고 성도 가져올 것입니다.
as well the first name maybe a few details about the customer
28:20:27
고객에게서 원하는 열입니다.
and as well the last name so those are the columns
28:20:31
집계를 필요로 합니다.
that we want from the customers and now what do we need we
28:20:34
총 수익과 같은 동일한 것입니다.
need the aggregation so it's going to be the same thing sales amount
28:20:37
총 수익으로서 우리는
as total revenue and we
28:20:40
세 가지 정보를 기준으로 데이터를 그룹화해야 하며, 클릭하여 붙여넣기 할 수 있습니다. 마지막으로는 항상 총 수익을 내림차순으로 정렬할 수 있습니다.
have to go and group up the data by all those three informations so we can go and click paste and at the end as usual we can order by the measure total revenue descending.
28:20:51
그래서 그게 전부입니다. 이전과 정확히 같지만 차원이 다릅니다. 이제 쿼리를 실행해 보겠습니다.
So that's it. It is exactly like previous one, but with different dimensions. So let's go and query it.
28:20:57
이제 18,000명의 모든 고객 목록을 얻었습니다.
And now we get a full list of all our customers, the 18,000.
28:21:02
각 고객의 총 수익을 볼 수 있습니다. 니콜과 케이트린을 볼 수 있습니다.
And we can see that total revenue for each customer. So we can see Nicole and Caitlin.
28:21:07
그들은 우리의 최고 소비자이자 우리 비즈니스에 판매와 수익을 창출한 가장 충성스러운 고객입니다.
They are our top spenders and the most royal customers that generated sales and revenue for our business.
28:21:14
정말 멋지죠? 이제 다음으로 가봅시다.
This is really cool, right? Now let's go to the next one.
28:21:17
판매된 품목의 분포가 무엇인지
says what is the distribution of sold items
28:21:21
국가별로 총량을 찾는 것과 같습니다.
across countries it is like finding the total
28:21:24
국가별 수량을 찾는 것이므로 매우 간단합니다.
quantity by countries so it is very simple i'm
28:21:27
같은 쿼리를 가져올 것입니다. 국가 정보는
gonna go and take the same query because countries comes from the
28:21:30
고객 차원에서 나오고 판매된 품목의 수량은
dimension customers and the sold items the quantity
28:21:33
판매에서 나오므로 같은 조인을 하지만
come from the sales so we are doing the same joints but
28:21:36
다른 차원과 측정값을 사용합니다. 고객에게서 필요한 것은 국가뿐이며, 측정값은 수량이 될 것입니다. 여기서 우리는
with different dimensions and measures so what do we need from the customers is only the country and the measure is going to be the quantity and here we're going to go and say
28:21:45
판매된 총 품목 수를 말할 것입니다.
total sold items and we have
28:21:48
국가별로 그룹화를 변경해야 하며,
to change the group by to the countries and
28:21:51
새로운 측정값으로 데이터를 정렬해야 합니다. 그게 전부입니다. 이렇게 해서 우리는
sorting the data by the new measure that's it and with that we
28:21:54
단지 변경함으로써 새로운 보고서를 생성하고 있습니다.
are generating new reports by just changing
28:21:57
치수와 측정을 변경하여 새로운 보고서를 생성하고 있습니다.
the dimensions and measures so again this is very interesting to
28:22:01
어떤 나라가 좋은 비즈니스를 창출하고 있는지 이해하는 것이 매우 흥미롭습니다.
understand which country is generating like good business
28:22:04
여기에서 우리는 고유한 값이 적은 차원을 가지고 있습니다.
for us so my friends as you might already notice if in the dimension we have like small number of unique values like in the countries we have here only seven values in
28:22:13
성별은 세 개뿐이며 우리는 이러한 차원을 낮은 기수라고 부릅니다.
the gender we have only three we call those dimensions low
28:22:16
값의 수가 적기 때문에 기수 차원입니다.
cardinality dimensions because we have low number of values
28:22:19
여기에서 예를 들어 7개의 행만 얻을 수 있습니다.
inside it and in the results we will get only here for example seven
28:22:23
고객에 의해 높은 기수인 경우입니다.
rows but if our dimension is high cardinality
28:22:26
고객 수는 18,000명입니다.
like by the customers we have 18 000
28:22:30
고유한 고객 수에 따라 측정값이 나뉘게 됩니다.
unique customers then our measure is
28:22:33
결과에서 고객 수는 정확히 동일하게 나타납니다.
going to be splitted by those 18 000 and in the results we
28:22:36
행 수와 결과는 기수에 따라 달라집니다.
will get exactly the same number of customers so the number of rows and results really depends on the cardinality
28:22:42
우리가 많은 다양한 보고서를 생성할 수 있습니다.
of the dimension so as you can see we can generate a lot
28:22:45
측정을 차원으로 나누어 8개를 생성했습니다.
of different reports by only following this formula dividing
28:22:49
몇 가지 측정값만으로도 다양한 통찰력과 보고서를 생성했습니다.
the measure by a dimension so we just generated eight
28:22:52
이제 비디오를 일시 정지하고 다양한 차원과 측정을 시도해 보세요.
different insights and reports by only few measures and
28:22:55
더 많은 통찰력을 얻기 위해 다양한 차원과 측정을 시도해 보세요.
dimensions so now what you can do you can pause the video and try different
28:22:59
우리 비즈니스에 대한 통찰력을 얻기 위해 다양한 차원과 측정을 시도해 보세요.
dimensions and measures in order to have more insights
28:23:02
이제 마지막 단계에서 우리는 순위 분석을 수행할 것입니다.
about our business okay so as you can see this is the basics analysis that we can do in any data set or any domain where we are aggregating
28:23:09
순위 분석이란 무엇인가요? 매우 기본적입니다.
a measure by dimension now in the next and last step in our
28:23:12
우리 차원의 값을 기준으로 정렬할 것입니다.
projects we will be doing ranking analysis okay
28:23:20
상위 성과자와 하위 성과자를 식별하기 위해서입니다.
so what is ranking analysis it is very basic so we're
28:23:23
그 공식을 다음과 같이 설정할 것입니다.
gonna go and order the value of our dimension based on
28:23:26
집계된 측정값에 따라 차원을 정렬할 것입니다.
a measure in order to identify the top performers and as well the bottom performers and the formula for that is going to be the following so this time we're going to be
28:23:34
예를 들어, 우리는 국가를 총 판매량에 따라 정렬할 것입니다.
ranking the dimensions by an aggregated measure so
28:23:38
판매된 상위 5개 제품을 찾을 것입니다.
for example we're gonna rank the countries by the total sale or
28:23:41
판매된 상위 다섯 개 제품을 찾을 것입니다.
we're gonna find the top five products by the sold
28:23:44
하위 세 고객 또는 총 주문 수로.
item the quantity or the bottom three customers by
28:23:47
우리는 차원 값의 정렬된 목록을 가질 것입니다.
total orders so it's like the magnitude analyzes we're
28:23:50
가장 높은 것부터 가장 낮은 것까지 빠르게 식별하기 위해.
gonna have like an ordered list of dimensions value for
28:23:53
상위 실적자를 식별할 수 있습니다.
example from the highest to the lowest in order to identify quickly the
28:23:56
상위 두 카테고리만 보고 싶습니다.
top performers and of course we can go and filter the data by saying
28:24:00
그렇게 하면 다른 모든 차원을 제거하게 됩니다.
i would like to have only the top two categories and
28:24:03
상위 두 개에 대해 SQL에서 사용할 수 있습니다.
with that you are removing all other dimensions that are not
28:24:06
상위 또는 순위 창 함수와 함께 사용할 수 있습니다.
on the top two and in sql we can use for that the keyword
28:24:09
순위, 밀집 순위, 행 번호 등입니다.
top or we can use the ranking window functions like
28:24:13
우리 데이터를 순위 매기기 위해 공식을 적용해 보겠습니다.
rank dense rank row number and so on so
28:24:16
데이터를 확인해 보겠습니다.
let's go and apply our formula in order to rank our data
28:24:19
첫 번째 질문은 어떤 다섯 개의 제품이 가장 높은 수익을 생성하는가입니다.
sets okay so now let's check our data we're gonna start with
28:24:22
우리 비즈니스에서 가장 잘 수행되는 제품을 찾고 있습니다.
the first question which five products generate the highest revenue so we are searching for the best performing products
28:24:29
이 질문에서 우리가 가진 차원과 측정값은 수익입니다.
in our business so of course the first question what is the dimension
28:24:32
즉, 사실과 제품의 판매가 필요합니다.
and measure that we have in this question well the revenue
28:24:35
즉, 이 쿼리를 작성하기 위해 제품 차원이 필요합니다.
that means we need the sales from the facts and the products
28:24:39
쿼리는 매우 간단할 수 있습니다.
that means we need the dimension products now in order to write this
28:24:42
그룹으로 사용할 수 있습니다.
query it can be very simple so we can use as well the group
28:24:45
카테고리별로 총 판매를 집계한 이 쿼리를 가져오겠습니다.
by i will not write it from the scratch so i'm just gonna take this query over here where we aggregated the total sales by the category now what i have to do is just to change the dimension.
28:24:55
따라서 카테고리 대신 제품이 필요합니다.
So instead of the category, we need the product
28:24:58
이제 제품 이름으로 데이터를 집계하고 있습니다.
name and we are aggregating now the data by the product
28:25:02
우리는 상위 다섯 개 제품이 필요합니다.
name because we need the top five products right so
28:25:05
수익은 판매 금액이며, 이제 거의 모든 것이 준비되었습니다.
the revenue is the sales amount and with that we have
28:25:08
이제 실행해 보겠습니다.
like almost everything is ready so let's go and execute it
28:25:11
이제 모든 제품 목록을 볼 수 있습니다.
and now we can see we have a list of all products in our
28:25:14
비즈니스와 총 수익을 볼 수 있습니다.
business and as well we can see the total revenue but
28:25:17
작업에서는 상위 다섯 개가 필요하다고 합니다.
the task says here we need the top five so
28:25:20
데이터베이스의 모든 제품이 필요하지 않습니다.
we don't need all the products from our database we have have
28:25:23
이 하위 집합만 선택해야 합니다.
to go and select only this subset now in order to do that in
28:25:26
SQL 서버에서는 매우 간단합니다.
sql server it's very simple we're going to go over here and say top
28:25:30
상위 다섯 개를 반환할 수 있습니다.
five and sql can go and return only the first
28:25:33
결과에서 다섯 개의 제품만 있습니다.
five rows from the results so let's go and execute
28:25:36
판매량이 가장 높은 다섯 개의 제품입니다.
it and as you can see now in the results we have only five products
28:25:39
작업을 완료했습니다.
with the highest sales and that's it with that we have solved
28:25:42
모두 피크입니다.
the task and we can see the top five products and
28:25:45
최악의 성과를 내는 다섯 개를 찾고 싶습니다.
all of them are pikes now let's go and check the other sides
28:25:49
판매량 기준으로 최악의 제품입니다.
we want to find the five worst performing
28:25:52
매우 간단합니다.
products by the same measure the sales and this is
28:25:55
같은 쿼리를 사용합니다.
very simple so what you're gonna do we're gonna go and take the same
28:25:58
데이터를 낮은 것부터 높은 것까지 정렬합니다.
query over here and now what you're gonna do we're gonna go and sort
28:26:02
내림차순 대신 제거할 수 있습니다.
the data from the lowest to the highest so
28:26:05
오름차순으로 정렬합니다.
instead of descending we can remove it and
28:26:08
이제 다섯 개의 베스트셀러와 최악의 판매자를 볼 수 있습니다.
with that sql gonna use the ascending so let's go and execute it and with that as you can see we are getting the worst five performing products by just sorting the data differently so So it is very simple, right?
28:26:20
차원을 변경하고 다른 보고서를 생성할 수 있습니다.
And with that, we can see our five best sellers and the five worst sellers.
28:26:24
제품 이름 대신 하위 카테고리를 확인해 보겠습니다.
And now what we can do, we can go and just change the dimension and generate different reports.
28:26:28
하위 카테고리에서 최고의 것을 볼 수 있습니다.
Like instead of the product name, let's go and check the subcategories. What are the best subcategories of our data?
28:26:35
최악의 성과를 내는 하위 카테고리도 확인할 수 있습니다.
So I just changed the dimension. Let's go and query. So with that, we can see the best subcategories we have in our business.
28:26:41
SQL에서 순위를 만드는 두 가지 방법이 있습니다.
And the same thing if you want to go and check the worst performing subcategories. So generating reports is very simple.
28:26:47
그룹 바이와 함께 상위 키워드를 사용하는 간단한 방법이 있습니다.
And now, my friends, in SQL, there is like two ways on how to create ranking.
28:26:52
우리는 그룹 바이를 사용하여 간단한 방법을 가지고 있습니다.
We have a simple one where we are using the group by clouds together with the keyword top.
28:26:57
하지만 보고서를 생성할 때 더 복잡한 경우에는 윈도우 함수를 사용해야 합니다.
But if you are generating reports where it's things are more complex and you need more flexibility, you should use the window functions.
28:27:04
이제 윈도우 함수를 사용하여 이 작업을 해결하는 방법을 보여드리겠습니다.
So let me show you how I can solve this task using the window function. So now I'm going to go and take almost the same query.
28:27:11
여기에 놓고 상위 다섯 개를 제거하겠습니다.
Let's put it over here. I'm going to get rid of the top five.
28:27:14
아직 제품 이름에 대해 이야기하고 있습니다.
and let's see we are still speaking about the product name
28:27:18
그룹 i와 함께 이제 우리가 할 일은
as well with the group i but now what we're gonna do we're gonna go and
28:27:21
순위를 생성하여 예를 들어 행 번호를 사용할 수 있습니다.
generate a rank so we can go and use for example the row number
28:27:24
순위를 매기기 위해 여러 유형의 윈도우 함수가 있습니다.
and in scale there's like different types of window functions for
28:27:27
그 중 하나는 행 번호 또는 순위입니다.
ranking one of them is the row number or the rank
28:27:31
이제 정렬하겠습니다.
and then we're gonna say over now we're gonna go and sort the
28:27:34
데이터를 총 수익에 따라 정렬해야 합니다.
data it's like we have done in the previous one we have to sort
28:27:37
총 수익은 판매의 합계입니다.
the data by the total revenue and total revenue is the
28:27:40
내림차순으로 정렬하겠습니다.
sum of sales and descending and we're
28:27:43
이제 새로운 열을 생성했습니다.
gonna call this rank products so let's go
28:27:47
각 제품에 대해 순위를 매겼습니다.
and execute it now as you can see we have created a new column where we have like a rank so we have for each product like one rank until the last product 130.
28:27:59
지금 우리가 관심 있는 것은 상위 다섯 개를 선택하는 것입니다.
so now what we are interested is to go and select the top
28:28:02
그래서 서브 쿼리를 사용할 것입니다.
five right now in order to do that we need a second step
28:28:05
별을 선택하겠습니다.
that's why we're gonna go and use the sub query so we're gonna
28:28:08
전체를 서브 쿼리에 넣겠습니다.
say select star from and then we're gonna put the whole
28:28:11
새 플래그를 사용해야 합니다.
thing in the sub query something like that
28:28:14
데이터를 필터링하기 위해서입니다.
and all what you have to do is to use the new flag that
28:28:17
순위 제품이 더 작거나
we have created in order to filter the data so we're
28:28:20
다섯과 같도록 하겠습니다.
gonna say where the rank products is smaller or
28:28:23
상위 다섯 개의 제품을 얻어야 합니다.
equal to five and with that we should get only
28:28:27
결과를 얻고 있습니다.
the top five products so let's go and execute it
28:28:30
그리고 보시다시피 우리는 지금 같은 결과를 얻고 있습니다.
and as you can see we are getting the same results now of course with the window
28:28:33
함수는 첫 번째 것보다 더 복잡하지만
function it is more complicated than the first one but with
28:28:36
창 함수로 더 많은 선택의 유연성을 얻습니다.
the window function we get more flexibility on selecting more
28:28:39
열 또는 다양한 집계 유형을 추가하는 것에 대한 세부정보
columns or adding more different types of aggregations
28:28:43
쿼리에 대한 세부정보와 함께 다양한 유형의
and details on the query and as well we can go and use different types
28:28:46
동점을 처리하는 순위 함수
of ranking functions that handles the ties
28:28:49
다르게 처리하므로 작업이 매우 간단하다면
differently so if the task is very simple like this i'm
28:28:52
간단한 그룹 I로 진행하겠지만 복잡한 보고서를 생성한다면
gonna go with the simple group i but if you are generating like complex reports i'm gonna go with the window function so So now what you can do, you can go and rank the data by different dimensions and measures.
28:29:03
예를 들어, 가장 높은 수익을 올린 상위 10명의 고객을 찾습니다.
For example, find the top 10 customers who have generated the highest revenue.
28:29:08
또한 주문이 가장 적은 세 명의 고객을 찾을 수 있습니다.
And as well, you can go and find the three customers with the fewest orders placed.
28:29:13
그래서 다시 이전에 생성한 쿼리를 재사용할 수 있습니다.
So again, we can go and reuse the previous queries that we have generated.
28:29:17
이 쿼리는 고객과 그들의 총 판매를 생성합니다.
So this query generates the customers and their total sales.
28:29:21
당신이 해야 할 일은 상위 10이라고 말한 다음 쿼리를 다시 실행하는 것입니다.
And all what you have to do is to say top 10 and then rerun the query. And with that, we are getting the top 10 customers.
28:29:28
그리고 최저 세 명의 고객에 대해서는
and about the lowest three customers all
28:29:31
측정을 교체해야 합니다.
what we have to do is to go and replace the measure so
28:29:34
고유한 주문 수를 세고 있습니다.
we are counting the unique number of
28:29:37
총 주문 수를 말할 수 있습니다.
orders so we can say total
28:29:40
주문을 변경하고
orders and as well go change the order by
28:29:43
내림차순이 아닌 오름차순으로 상위
not descending ascending and we need the top
28:29:46
세 명을 보겠습니다.
three so let's go and execute it so we
28:29:50
한 번만 주문한 세 명의 고객을 볼 수 있습니다.
can see the three customers that did order only once and they are the three customers with the fewest orders So as you can see, by just switching the dimensions and measures, we are generating completely new important insights.
28:30:02
그리고 데이터를 탐색하면서 최고의 제품과
And as you can see, as we are exploring the data, we are understanding what are the best products, what are the top customers that are usually very important for reporting.
28:30:11
상위 고객이 무엇인지 이해하고 있습니다.
All right, my friends. So with that, we have covered the last step in our projects, how to rank our data.
28:30:17
프로젝트의 마지막 단계를 다루었습니다.
And with that, we have covered all the steps of the project roadmap.
28:30:20
우리는 데이터베이스 차원 측정을 탐색했습니다.
We have done a lot of explorations for the database dimensions measures We have combined the dimensions and measures in order to do magnitude and ranking analyzes.
28:30:30
좋아요, 친구들 그래서 EDA 프로젝트에 대한 모든 내용은 여기까지입니다. 이제 다음 프로젝트에서는 고급 데이터 분석을 다룰 것입니다.
Okay, my friends So that's all about that EDA projects and now in the next one We will do the last type of projects the advanced data analytics.
28:30:38
자, 시작해봅시다
So let's go And
28:30:44
이제 우리가 다룰 시간은 SQL을 사용한 고급 분석 프로젝트입니다. 여기서 우리는 실제 비즈니스 질문에 답하기 위해 복잡한 SQL 쿼리를 작성할 것입니다.
now the time that we're gonna cover is advanced analytics projects using SQL where we're gonna write complex SQL queries to answer real business questions.
28:30:51
우리는 고급 윈도우 함수와 CTE 서브 쿼리를 사용할 것이며, 두 개의 큰 쿼리를 작성하여 두 개의 보고서를 생성할 것입니다.
So we're going to use the advanced window functions, the CTE sub queries, and we're going to go and script two big queries in order to generate two reports.
28:31:00
이러한 유형의 프로젝트를 통해 실제 비즈니스 질문을 해결하는 방법을 배울 것입니다. 알겠죠?
So with this type of project, you will learn how to solve real business questions using advanced techniques. All right.
28:31:06
이 프로젝트에도 로드맵이 있으며, 다양한 단계와 분석을 통해 진행할 것입니다.
So for this project as well, we have a roadmap where we're going to progress through different type of steps and analyzes.
28:31:12
우리는 시간 변화, 누적 분석, 성과, 데이터 세분화, 기타 항목 보고 등을 SQL을 사용하여 수행할 것입니다.
So we're going to do many stuff like change of our time, cumulative analyzes, performance, data segmentations, and other entry reporting, and all using SQL.
28:31:20
로드맵의 첫 번째 단계부터 시작해봅시다. 우리는 시간에 따른 변화를 분석할 것입니다. 자, 시작합시다.
So let's start with the first step in the roadmap. We're going to analyze the change over time. So let's go.
28:31:26
좋아요, 이제 시간에 따른 변화란 무엇인가요?
Okay, so now what is change over time?
28:31:32
이는 측정값이 시간에 따라 어떻게 변하는지를 분석하는 기술입니다.
It is a technique in order to analyze how a measure evolves over the time.
28:31:36
그리고 이는 트렌드를 추적하고 데이터의 계절성을 식별하는 데 매우 중요합니다.
And this is very important in order to track the trends and as well to identify seasonality of your data.
28:31:42
그에 대한 공식은 매우 간단합니다. 우리는
And the formula for that is very simple. we're gonna go and aggregate a
28:31:45
측정값을 집계할 것이지만 이번에는 날짜 차원을 기반으로 합니다.
measure but this time based on a date dimension
28:31:48
예를 들어, 연도별 총 매출
for example the total sales by a year
28:31:51
월별 평균 비용을 예로 들 수 있습니다. 따라서
the average cost by the month so if you combine any
28:31:55
날짜 열이나 차원과 함께 집계된 측정값을 결합하면
aggregated measure together with a date column or dimension
28:31:58
당신이 하는 모든 것은 시간에 따른 변화를 분석하는 것입니다. 예를 들어, 우리는 측정값을 나눌 것입니다.
then all what you are doing is you are analyzing the
28:32:01
우리 시대의 변화, 예를 들어 우리는 우리의 측정을 깨뜨릴 것입니다.
change of our time so for example we're gonna go and break our measure
28:32:04
이번에는 예를 들어 연도로, 이를 통해 우리는 시간이 지남에 따라 우리의 비즈니스가 어떻게 진행되고 있는지를 즉시 추적할 수 있습니다. 예를 들어, 여기서 가장 좋은 해는 2024년이었습니다.
this time for example by the years and with that we can track immediately how our business is doing over the time over the years So for example, we can see here the best year was 2024.
28:32:15
그리고 2025년에는 우리 비즈니스에서 정말 심각한 감소가 있었습니다. 그리고 2026년에는 약간 상승하고 있습니다.
And then we have really hard decline in our business in 2025. And then slightly it's going up in 2026.
28:32:21
그래서 이를 통해 우리는 우리의 비즈니스 트렌드를 빠르게 분석할 수 있습니다. 이제 가서 우리의 비즈니스에서 시간의 트렌드와 변화를 확인해 봅시다.
So with that, we can quickly analyze the trends of our business. So now let's go and check the trends and the changes of our time in our business.
28:32:29
좋습니다, 이제 우리의 데이터에서 시간의 트렌드와 변화를 분석해 봅시다.
Okay, so now let's analyze the trends and changes of our time in our data.
28:32:33
이러한 분석을 수행하기 위해 일반적으로 우리는 사실 테이블을 목표로 합니다.
And in order to do this kind of analysis, usually we target the fact table.
28:32:37
왜냐하면 그곳에는 일반적으로 우리의 측정값과 날짜가 있기 때문입니다. 그래서 우리는 주문 날짜, 배송 날짜 및 마감 날짜가 있습니다.
Because there usually we have our measures and as well dates. So we have the order date, shipping date and due date.
28:32:44
이제 우리가 할 수 있는 것은 시간에 따른 판매 성과를 분석하는 것입니다.
Now what we can do, we can go and analyze there the sales performance over time.
28:32:48
우리가 배운 대로, 필요한 것은 메트릭과 날짜입니다. 예를 들어 주문 날짜를 선택해 보겠습니다.
So as we learned, all what we need is a metric and a date. Let's go for example and select the order date.
28:32:56
그리고 우리 사실 테이블에서 판매 금액을 측정하는 것 중 하나입니다.
And as well, one of those measures sales amount from our fact table.
28:33:02
그래서 쿼리를 실행해 보겠습니다. 그리고 데이터를 주문 날짜 기준으로 오름차순 정렬할 수 있습니다.
So let's go and query it. And we can go and order the data by the order date ascending.
28:33:09
그래서 실행해 보겠습니다. 보시다시피 null 값이 있습니다.
So let's go and execute. and as you can see we have nulls in
28:33:12
우리 데이터에서 우리는 그 데이터를 필터링할 수 있습니다.
our data what we can do we can go and filter those data out
28:33:15
우리는 그것이 필요하지 않으므로 주문 날짜가
we don't need it so we're gonna say where order date is
28:33:18
null이 아닌 것으로 설정하겠습니다. 다시 실행해 보겠습니다.
not null so let's go and execute it again all
28:33:21
그렇습니다. 이제 보시다시피 그런 주문이 없습니다.
right so that we don't have those orders now as you can see
28:33:25
우리는 시간에 따른 판매를 가지고 있습니다. 날짜가 있습니다.
we have sales over time right we have a date
28:33:28
그리고 우리는 측정값이 있으므로 이것은 정말 좋습니다.
and we have a measure so this looks really good
28:33:31
하지만 이제 우리가 할 것은 판매 금액으로 데이터를 집계하는 것입니다. 합계를 말해 보겠습니다.
but now what we're gonna do we're gonna go and aggregate the data by the sales amount so let's go and say sum and we're gonna
28:33:38
총 판매라고 부르고 데이터를 그룹화합니다.
call it total sales and then we group up
28:33:41
주문 날짜별로 데이터를 그룹화합니다.
the data by the order dates so
28:33:44
실행해 보겠습니다. 보시다시피 각
let's go and execute it and with that as you can see for each
28:33:47
날짜에 대해 총 판매가 있습니다. 이제 세분화 수준이
day we have the total sales so now the granularity
28:33:51
우리 데이터는 날짜 단위입니다. 물론 이제
of our data is the day and we can say of course now
28:33:54
우리는 시간에 따른 판매를 분석하고 있지만 보통 우리는
we are analyzing the sales of our time but usually we don't
28:33:57
일 단위로 데이터를 집계하지 않습니다. 더 높은
aggregate the data on the day level we want to have higher
28:34:00
집계를 원합니다. 예를 들어 연도로 가보겠습니다.
aggregations for example let's go to the years
28:34:03
이제 날짜 차원을 변경하려면
and now in order to change the dimension date here
28:34:06
일에서 연도로 변경해야 합니다. 날짜 함수를 사용해야 합니다.
from a day to a year we have to use date functions
28:34:09
날짜 부분을 추출하기 위한 많은 날짜 함수가 있습니다.
and there are a lot of date functions in order to extract
28:34:13
연도를 얻기 위한 간단한 함수가 있습니다. 그것은 변환할 것입니다.
that date part and now in order just to get the year
28:34:16
우리 날짜를 연도로 변환합니다. 그래서 그것을 주문이라고 부릅시다.
we have a quick function called year and it's going to convert
28:34:19
연도라고 부르고 물론 우리는 그룹화해야 합니다.
our date to year so let's call it order
28:34:23
연도와 물론 우리는 그룹화해야 합니다
year and of course we have to go and group up the
28:34:26
데이터를 연도별로 정렬하고
data by the year and as well sort it by the year so
28:34:29
이제 실행해 보겠습니다. 우리는 연도 수준에 있습니다
let's go and execute now we are at the year level
28:34:32
그리고 우리는 단지 5년만 가지고 있습니다. 즉, 변경했습니다
and we have only five years so that means we have changed
28:34:35
집계를 일에서 연도로 변경했습니다. 이제
the aggregation from the day to a year and now it is
28:34:39
우리 비즈니스의 성과를 쉽게 분석할 수 있습니다
very easily to analyze the performance of our business
28:34:42
세월이 흐르면서 첫 해가 가장 낮았습니다
over the years so the first year was the lowest
28:34:45
그리고 2013년이 우리 사업에서 가장 좋았다는 것을 알 수 있습니다.
and you can see 2013 is the best
28:34:48
그 후 2014년에 급격히 감소했습니다.
year in our business and then it is declined massively
28:34:52
물론 우리는 더 많은 것을 추가할 수 있습니다.
in 2014 and of course we can go and add more
28:34:55
데이터에 대한 조치를 추가하는 것뿐만 아니라 총 판매량도 포함됩니다.
measures to our data not only the total sales for
28:34:58
예를 들어, 고객의 총 수를 계산해 보겠습니다.
example let's go and calculate the total number of customers
28:35:01
그래서 우리는 고유 고객 수를 세울 수 있습니다.
so we can say counts distinct customer
28:35:05
총 고객 수를 키로 하여.
key as total customers so
28:35:08
이제 실행해 보겠습니다. 그와 함께 우리는 고객이 증가하고 있는지 확인할 수 있습니다.
let's go and execute it and with that we can check are we gaining
28:35:11
시간이 지남에 따라 고객이 증가하고 있는지, 우리가 볼 수 있는 경향이 있는지 확인할 수 있으며, 우리는 계속해서 확장할 수 있습니다.
like customers over the time if there are any trends that we can see and we can go and keep extending stuff like we can go and add
28:35:19
총 수량을 추가하여 수량을 요약할 수 있습니다.
the total number of quantities so summarize quantity
28:35:22
총 수량으로.
as total quantity so
28:35:25
이제 실행해 보겠습니다. 그와 함께 우리는 정말 멋진 그림을 갖게 됩니다.
let's go and execute and with that we have really nice picture in
28:35:28
수익이 증가하고 있는지 감소하고 있는지 이해하기 위해.
order to understand is the revenue increasing
28:35:31
최고의 해는 무엇인지, 최악의 해는 무엇인지, 시간이 지남에 따라 고객이 증가하고 있는지, 우리가 지금 결과를 보고 발견할 수 있는 경향이 있는지.
or decreasing over the time what is the best year
28:35:35
결과를 보면 이것이 우리에게 높은 수준의 장기적인 데이터 관점을 제공합니다.
the worst year are we gaining customers over time is there any like trends that we can spot now by looking to the result you can see this gives us
28:35:43
물론 이것은 전략적 결정에 도움이 됩니다.
high level long-term view of your data and of
28:35:46
이제 우리가 할 수 있는 것은 월별로 세분화하는 것입니다.
course it helps for strategic decisions and now what we
28:35:49
그래서 우리는
can do we can go and drill down to the months so we
28:35:52
연도에 관계없이 월별로 데이터를 집계할 수 있습니다.
can go and aggregate the data by the month regardless the years
28:35:55
각 월이 어떻게 되는지에 대한 아이디어를 제공하기 위해서입니다.
in order to give us an idea how each month is
28:35:59
연도에서 월로 기능을 전환하면 됩니다.
performing on average so all what you have to do is to switch the
28:36:02
그룹화 및 정렬을 위해 실행해 보겠습니다.
function from year to a month like this and of
28:36:05
출력에서는 모든 월을 얻을 수 있습니다.
course for the group by and the order by let's go and execute
28:36:08
어떤 월이 판매에 가장 좋은지 알아보겠습니다.
and of course in the output we will get all the the months and
28:36:11
물론 12월입니다. 크리스마스가 있으니까요.
guess what which month is the best for sales is
28:36:15
그리고 최악의 월은 2월입니다.
of course december because you have all those christmas and
28:36:18
이로써 계절성을 이해하고 있습니다.
stuff and the worst month as you can see is february
28:36:21
우리 비즈니스의 트렌드 패턴을 이해하고 있습니다.
so with that we are understanding the seasonality of
28:36:24
우리 분석에 연도를 포함하지 않으므로,
our business and the trends patterns of our business
28:36:27
모든 연도의 데이터를 집계하고 있습니다. 이제 각 연도에 대해 더 구체적으로 만들 수 있습니다.
and as you are not including the year in our analysis
28:36:30
우리 쿼리에 연도와 월을 추가할 것입니다.
you are aggregating all the data from all years now what you can do we can make it more specific for each year where you go and add the year informations
28:36:39
쿼리에 연도와 월을 추가할 것입니다.
to our query so we're gonna have both a year and
28:36:42
그룹화에 추가해야 합니다.
month let me just change this to a month and of
28:36:45
정렬에 추가해야 합니다. 실행해 보겠습니다.
course we have to go and add it to the group by and
28:36:49
특정 연도의 월 데이터를 집계하고 있습니다.
the order by so let's go and execute and with that we
28:36:52
이제 모든 연도의 모든 월이 있습니다.
are aggregating the data of a month of specific year
28:36:55
이제 하나의 연도에 집중하고 싶다면 데이터를 필터링할 수 있습니다.
so now we have all the months of all years and
28:36:58
연도와 월을 별도의 열로 사용하는 대신, 날짜 트렁크 기능을 사용할 수 있습니다.
now if you want to focus on only one year what you can do you can go and filter the data by the order year and with that you can see how the data is evolving over time Now, of course, in SQL, we can go and format the date differently.
28:37:09
여기서 날짜 트렁크를 사용할 것입니다. 월 수준의 세분화가 필요하면 월을 입력합니다.
So instead of using the year and the month in separate columns, what we can do, we can use that date trunk function.
28:37:17
연도와 날짜를 모두 얻을 수 있습니다. 이렇게 주문 날짜라고 부릅시다.
So instead of here, we're going to say date trunk. And if you want the granularity of your date at the month level, you're going to say month and then the date.
28:37:25
실행해 보겠습니다. 출력에서 이전과 동일한 결과를 얻을 것입니다.
And with that, you will get both the year and the date. And let's call it order date like this.
28:37:32
연도와 월을 위한 두 개의 열 대신, 모든 것을 하나로 통합했습니다.
So let's go and execute. Now in the output, we will get exactly the same result as before.
28:37:38
월을 지정했기 때문에 모든 날짜가 제거됩니다.
But instead of having like two columns for the year and the month, we have everything in one.
28:37:41
그리고 우리가 월을 말했기 때문에 모든 날짜를 제거할 것입니다.
And because we said the month, that means it's going to go and remove all the days.
28:37:46
그래서 보시다시피 항상 1부터 시작합니다. 즉, 그 달의 첫 번째 날입니다.
So as you can see, it always starts with the one. So the first day of the month.
28:37:51
그리고 그렇게 하면 각 년도마다 각 월에 대한 한 행을 얻을 수 있습니다.
And with that, you will get one row for each month, for each year.
28:37:54
그리고 만약 그것을 빠르게 년도로 변경하고 싶다면, 날짜 부분을 년도로 변경하면 됩니다.
And if you want to change that quickly to a year, just go and change the date parts to a year.
28:38:00
그래서 포맷의 첫 번째 인자는 날짜가 될 것입니다. 그리고 원하는 포맷을 설정하면 됩니다.
And you will get the granularity of the year. Now, if you don't like this format and you would like to have your specific format, what you can do, you can go and use the format function.
28:38:10
예를 들어, 연도로 시작합니다. 그리고 월 이름의 약어를 원한다고 가정해 보겠습니다. 이런 식으로요.
So format, the first argument is going to be the date. And then you go and do your format that you want.
28:38:16
그리고 물론, 그룹화 및 정렬도 가능합니다. 그래서 실행해 보겠습니다.
So, for example, it starts with the years. And let's say I would like to have the abbreviation of the month name. So something like this.
28:38:23
예를 들어, 연도로 시작합니다. 그리고 월 이름의 약어를 원한다고 가정해 보겠습니다. 이런 식으로요.
And of course, group by and order by. So let's go and execute it.
28:38:28
그렇게 하면 연도에서 월 이름의 약어를 얻을 수 있습니다. 하지만 어떤 함수를 사용하는지 주의해야 합니다.
and with that we got our format the year minus then
28:38:31
월의 약어를 얻으려면 어떤 함수를 사용하는지 주의해야 합니다.
the abbreviation of the month but you have to be careful which function you
28:38:34
출력에서 얻는 포맷이 문자열이기 때문에
are using because the format you will get in the output
28:38:37
여기 데이터는 연도로 정렬되지만 월로는 정렬되지 않습니다.
a string and as you can see you cannot sort it correctly
28:38:40
여기 데이터는 연도로 정렬되지만 월로는 정렬되지 않습니다.
so the data here is sorted by the year but not by the month
28:38:44
하지만 날짜 트렁크를 사용하면 데이터를 올바르게 정렬할 수 있습니다.
but if you are using date trunk you can see the
28:38:47
데이터가 올바르게 정렬되므로 월로 전환하면 됩니다.
data is correctly sorted so if we switch it to a month
28:38:50
모두 올바르게 정렬되었습니다. 왜냐하면 여기 출력은 날짜이기 때문입니다.
it will be as well okay so everything is sorted correctly because the output here is a date
28:38:57
모두 올바르게 정렬되었습니다. 왜냐하면 여기 출력은 날짜이기 때문입니다.
and SQL gonna sort the date correctly it is not string and
28:39:00
연도와 월을 사용하면 여기 출력이
if you are using the year and the month the output here
28:39:03
정수가 될 것이고 정수를 정렬하는 것은 문제가 되지 않습니다.
gonna be an integer and sorting an integer is not
28:39:06
문제가 되지 않으므로 원하는 것을 선택할 수 있습니다.
a problem so of course you can go and pick the one that you like
28:39:10
그게 전부입니다. 실행해 보겠습니다.
so that's it let's go and execute it and now
28:39:13
다른 날짜를 찾아서 계속 분석할 수 있습니다.
you can go and keep analyzing by finding another date
28:39:16
데이터 세트와 다른 측정값에서 매우 간단합니다.
in our data sets and another measure so as you can see it is very simple okay so that's all about how to analyze the trends and the change over time now the next step
28:39:25
우리는 누적 분석을 통해 고급 집계를 수행할 것입니다.
We're going to do some kind of advanced aggregations by doing cumulative analysis.
28:39:33
그래서 누적 분석이란 무엇인가요? 시간에 따라 데이터를 점진적으로 집계하는 것입니다.
Okay, so what is cumulative analysis? It is aggregating the data progressively over the time.
28:39:38
그리고 이것은 시간이 지남에 따라 우리의 비즈니스가 어떻게 성장하고 있는지를 이해하기 위한 매우 중요한 기법입니다.
And this is a very important technique in order to understand how our business is growing over the time.
28:39:45
그래서 우리의 비즈니스가 시간이 지남에 따라 어떻게 진행되고 있는지, 성장하고 있는지 또는 감소하고 있는지에 대한 매우 흥미로운 분석입니다.
So how our business is progressing over the time, whether it is growing or declining. It is very interesting analysis.
28:39:52
그래서 공식은 시간이 지남에 따라 변화와 매우 유사할 것입니다.
So the formula is going to be very similar to the changes over time.
28:39:55
하지만 측정값에 대한 단순 집계 대신, 우리는 이번에는 측정값을 집계할 수 있습니다.
But instead of having a simple aggregation on the measure, we can aggregate our measure, but this time,
28:40:00
누적적으로 서로의 위에 추가하는 것과 같아서
cumulative so we are like adding stuff on top of each other's and
28:40:03
데이터는 다시 날짜 차원으로 나눌 수 있습니다.
the data again can split it by the date dimension because
28:40:06
우리는 예를 들어 시간이 지남에 따라 진행 상황을 추적하고 싶습니다.
we want to track the progress over the time for example we
28:40:10
우리는 판매의 누적 합계 또는 이동 평균을 찾을 수 있습니다.
can find the running total of sales or the moving
28:40:13
예를 들어, 우리의 판매가 연도로 나뉘어지는 간단한 예를 들어 보겠습니다.
average of sales by a month so now let's have again our simple
28:40:16
2024년에는 300이 있습니다.
example where our sales is splitted by the years now this is the classic change of our time but in order now to make it cumulative what can happen we're gonna take the measure and add to it For example, 2024, we have 300.
28:40:29
그리고 2025년에는 300과 100을 더하여 누적합을 만듭니다.
And now for 2025, we're going to add the 300 together with the 100 in order to make it cumulative.
28:40:35
2025년에는 400이 될 것입니다. 2026년에도 같은 방식으로 400과 200을 더할 것입니다.
So for 2025, we're going to have 400. And the same thing for 2026, we're going to go and add the 400 together with the 200.
28:40:43
그렇게 하면 600이 됩니다. 보시다시피, 우리는 누적 값을 생성하기 위해 계속해서 값을 추가하고 있습니다.
And with that, we will get 600. So as you can see, we are keep adding the values in order to generate something called cumulative value.
28:40:49
이러한 유형의 분석을 위해 SQL에서 집계 윈도우 함수를 사용하여 누적 값을 찾습니다.
Now for this type of analysis, we use in SQL, the aggregate window functions. in order to find out the cumulative values.
28:40:56
이제 우리의 비즈니스가 성장하고 있는지 감소하고 있는지를 찾기 위해 공식을 적용해 보겠습니다.
So now let's go and apply our formula in order to find whether our business is growing or declining. So let's go.
28:41:02
이제 우리는 다음을 분석해야 합니다. 각 월의 총 판매와 시간에 따른 누적 판매를 계산할 것입니다.
Okay, so now we have to analyze the following. We're going to calculate the total sales for each month and as well the running total of sales over time in order to analyze the trends.
28:41:11
그래서 우리는 시간이 지남에 따라 변화를 계산하고 이미 그렇게 했습니다.
So let's see how we're going to do that. Let's start with the easy stuff where we're going to calculate the total sales for each month.
28:41:17
우리가 필요한 것은 날짜와 측정값입니다.
So we are calculating the changes over time and we have already done that. So all what we need is a date and a measure.
28:41:22
우리의 날짜는 주문 날짜가 될 수 있고, 측정값은 사실 테이블의 판매 금액이 될 것입니다.
our date can be the order date and the measure gonna be the sales amount from our fact table
28:41:29
이제 우리는 각 월의 총 판매를 찾고자 합니다.
so let's query this and now we want to find the total sales for
28:41:32
즉, 주문의 세분성을 하루에서 한 달로 변경할 것입니다.
each month that means we're gonna change the granularity of the order
28:41:35
판매에 대해서는 집계 함수를 사용하여 총 판매를 계산할 것입니다.
date from a day to a month and i usually like using the date rank for this kind of tasks and the minority gonna be the month so this is the order dates
28:41:46
물론 우리는 날짜별로 데이터를 그룹화해야 합니다.
and now for the sales we're gonna use aggregate function some sales
28:41:49
그래서
as total sales and of course we have to go
28:41:52
데이터를 날짜별로 그룹화합시다.
and group up the data by the date so
28:41:56
가서 변명합시다
let's go and excuse it
28:41:59
이제 각 월의 총 판매량을 보실 수 있습니다
so as you can see we have now the total sales for each month
28:42:02
널 값을 제거하는 것을 잊지 마세요
and don't forget to get rid of the nulls so we're
28:42:05
주문 날짜가 널이 아닌 곳을 말할 것입니다
going to say where order date is not null
28:42:08
이제 널이 없어서 더 좋아 보입니다
now it looks better we don't have nulls and of course
28:42:11
하지만 우리는 그것을 원하지 않습니다
we can go and order the data by our date now our measure is just aggregated for each month individually
28:42:18
누적 메트릭을 원합니다
right but we don't want that we want to have like a running
28:42:21
이를 위해 윈도우 함수를 사용해야 합니다
total so we'd like to have like cumulative metric
28:42:24
가서 그렇게 하겠습니다
in order to do that we have to use window function so let's
28:42:27
그런 다음 나머지를 서브 쿼리에 넣을 것입니다
go and do that we will use a sub query for that in order just to make it simple so what we need we need the order date and let's say the total sales and here we have to have our window function
28:42:40
주문으로 정렬할 필요는 없습니다
then we're going to put the rest in a sub query
28:42:43
어쨌든 데이터는 윈도우 함수로 정렬할 수 있습니다
and of course we can go and get rid of the order by because
28:42:46
이제 윈도우 함수를 작성해 보겠습니다
anyway our data can be sorted using the window function so now
28:42:49
총 판매량의 합계를 구할 것입니다
let's start writing our window function we will have the sum
28:42:53
새로운 값을 요약하고
of total sales so
28:42:56
이렇게 윈도우 함수를 만들 것입니다
we want to summarize those new values and you're gonna build
28:42:59
즉시 주문할 수 있습니다
a window function like this over we don't have to go and partition
28:43:02
계산된 새로운 주문 날짜로 정렬합니다
anything so we can go immediately and say order by our
28:43:05
오름차순으로 정렬하고 싶습니다
new order date that we have calculated and
28:43:08
우리는 그것이 오름차순이 되기를 원하므로 사실 그게 전부입니다.
we want it to be ascending so actually that's it so
28:43:12
이제 결과를 확인해 보세요
as running total sales so
28:43:15
모든 값이 누적되고 있습니다
let's try that out now if you look to the result you can see that
28:43:18
첫 번째 총 판매량은
all those values are cumulative and it
28:43:21
총 판매량과 같습니다
is working like this the first total sales is equal to
28:43:24
다음 행에서는 더해질 것입니다
the total sales because previously we don't have anything now
28:43:27
다음 행에서는 무엇이 일어날 수 있는지 추가할 것입니다.
for the next row what can happen is going to go and add
28:43:31
이 값을 이전 값에 추가하면 누적 합계를 얻습니다.
this value to the previous one and with that we get the running total value now moving on to the third row is going to go and add
28:43:39
이 세 값을 모두 더하면
all those three values together and of course this can give us
28:43:42
이번 달의 누적 합계를 얻을 수 있습니다.
that running total for this month and so on so as
28:43:45
SQL은 항상 창을 통해 이동합니다.
sql is moving through the window it is always
28:43:48
현재 값을 이전의 모든 값에 추가합니다.
adding the current value to all previous values
28:43:51
이는 창의 기본 프레임 때문입니다.
and this is because of the default frame of the window the
28:43:55
프레임은 무한히 진행되는 것과 현재 행 사이에 있습니다.
frame gonna be between the unbounded proceeding
28:43:58
예를 들어, 현재 행에서 이번 달의 총 판매량은 이 값이며, 무한히 진행되는 것은 모든 값입니다.
and the current row so that means for example if we are at this row over here current total sales for this month is this one and the unbounded proceeding is all the values
28:44:08
이번 달 이전의 모든 값입니다.
before this month so that means we are getting all the previous
28:44:11
현재 값과 함께 이전 값을 더하면
values together with the current value and with that
28:44:14
누적 판매 효과를 얻을 수 있습니다.
we will get the effect of the running total sales and
28:44:18
지금 보시다시피 모든 연도를 통과하고 있습니다.
now of course as you can see it is going through all the
28:44:21
현재 우리는 누적 합계를 한 해로 제한할 수 있습니다.
years right now we can go and limit the running
28:44:24
각 새 해마다 초기화해야 합니다.
total for only one year so for each new year
28:44:27
즉, 각 해에 대해 데이터를 분할하고 싶습니다.
it has to reset and start from the scratch so
28:44:30
따라서 창을 분할하기 위해 매우 간단합니다.
that means we are partitioning the data for each year we would like to have partition for the first year it's going to It is one row and for that 2011, we're going to get the whole partition over here.
28:44:40
주문 날짜로 분할하겠습니다. 그게 전부입니다.
So in order to partition our window, it's very simple.
28:44:43
이제 실행해 보겠습니다. 2010년의 첫 번째 파티션을 확인해 보겠습니다.
We're going to go and say partition by the order date. That's it.
28:44:48
누적 합계는 첫 번째 달과 동일하지만, 한 달만 있으므로 올해는 그게 전부입니다.
Let's go and execute it. Now let's go and check for the first partition for 2010.
28:44:53
다음 해로 넘어가면 초기화되는 것을 볼 수 있습니다.
You can see the running total is the same as the first month, but since we have only one month, that's it for this year.
28:45:00
2011년의 누적 판매량을 볼 수 있습니다.
Now, as we go to the next year, as you can see it resets. So you can see the running total is the same as the first month. But since we have only one month, that's it for this year. Now, as we go to the next year, as you can see, it resets. So you can see the running total sales for 2011.
28:45:07
1월과 정확히 같습니다. 현재 값과 이전 값을 더하지 않습니다.
It is exactly as January. It is not adding up now the value of the current value with the previous one because the previous one is outside of the window.
28:45:16
따라서 전체 연도의 누적 합계를 얻고 있습니다.
So as you can see, we are getting a running total for the whole year. And once we hit a new year, it is going to reset.
28:45:23
작동하고 있습니다. 이렇게 누적 값을 생성할 수 있습니다.
So it is working. and this is how you can create cumulative
28:45:26
SQL에서 누적 값을 생성하는 방법입니다.
values in sql and of course if you would like to change the granularity
28:45:30
데이터의 세분화를 변경하고 싶다면 매우 간단합니다.
of our data it is very simple all what you have to do is to go
28:45:33
여기에서 월 대신 연도로 변경하겠습니다.
over here and say instead of month we're gonna make it as a
28:45:36
물론 그룹 기준도 변경하는 것을 잊지 마세요.
year and of course don't forget to change as well the group by
28:45:39
이제 실행해 보겠습니다.
so let's go and execute and with that we
28:45:42
각 연도에 대한 누적 값을 생성하고 있습니다.
are creating cumulative values for each year but
28:45:45
물론 연도로 파티션을 나누는 것은 의미가 없습니다.
of course it makes no sense to partition by the years
28:45:48
그것을 제거하고 다시 실행해 보겠습니다.
let's go and remove it and execute it again and with
28:45:52
연도별 누적 판매 총액을 생성하고 있습니다.
that you are creating the running total sales the cumulative
28:45:55
그래서 이제 또 다른 측정값을 추가할 수 있습니다.
metric over the years so as you can see it is very
28:45:58
예를 들어, 누적 총액 대신 이동 평균을 찾을 수 있습니다.
simple now we can go and add like another measure
28:46:01
이동 평균을 찾기 위해 예를 들어 다른 집계를 추가할 수 있습니다.
and another aggregation like for example instead of
28:46:04
이동 평균을 구해보겠습니다.
finding the running total we can find the moving average
28:46:07
가격의 평균을 계산해야 합니다.
so let's for example go and get the moving average of
28:46:10
평균 가격을 평균으로 하고 이동 평균이라고 부르겠습니다.
the price so first we have to calculate the average of the price as average price and now what we have to do is to go and make another window function over here
28:46:20
이제 실행해 보겠습니다.
where we are saying average the average price and we're gonna go and call it moving average
28:46:29
이제 판매의 이동 평균 가격을 얻고 있습니다.
that's it so let's go and execute it and with that
28:46:32
그렇다면 정말 다른 점은 무엇인가요?
you are getting the moving average price of our sales
28:46:35
정상 집계와 누적 집계의 차이점은 무엇인가요?
all right so now you might still asking what is really different
28:46:38
각 연도의 성과를 확인하기 위해 정상 집계를 사용합니다.
between using a normal aggregation and cumulative aggregation well we usually use normal aggregations in order to check the performance of each individual role.
28:46:48
각 연도의 성과를 보고 싶다면 정상 집계를 사용할 것입니다.
Like if I want to see how each year is performing, I'm going to go and do a normal aggregation.
28:46:52
비즈니스의 성장 과정을 이해하려면 누적 집계를 사용해야 합니다.
But if you want to see a progression and you want to understand how your business is growing,
28:46:58
누적 값과 정상 집계의 차이가 있습니다.
you have to go and use cumulative aggregations because you can see easily here the progress of your business over the years.
28:47:05
누적 집계를 사용해야 비즈니스의 진행 상황을 쉽게 볼 수 있습니다.
So there is like a difference between using cumulative value and a normal aggregation. All right.
28:47:10
누적 분석을 완료했습니다. 이제 성과 분석을 진행하겠습니다.
So with that, we have done with the cumulative analyzes and you have learned all different types of aggregations now the next step in our roadmap we're gonna do performance analysis
28:47:24
좋아요, 성과 분석이란 무엇인가요? 그것은 비교하는 과정입니다.
okay so what is performance analysis it is the process of comparing
28:47:27
현재 값과 목표 값을 비교하는 것입니다.
the current value with a target value
28:47:30
특정 카테고리의 성과를 비교하는 것이며, 이는 성공을 측정하는 데 도움이 됩니다.
to compare the performance of specific category and this can help us in order to measure the success to compare the performance so the formula for that is very simple we're gonna find
28:47:39
현재 측정값과 목표 값의 차이를 찾는 것입니다.
the difference between the current measure and the target
28:47:43
예를 들어, 현재 판매량과 평균 판매량을 비교할 수 있습니다.
measure by subtracting them like for example we can go and compare
28:47:46
현재 연도 판매량과 이전 연도 판매량을 비교하거나,
the current sale with the average sale or the
28:47:49
현재 판매량과 최저 판매량을 비교할 수 있습니다.
current year sales with the previous year sales or
28:47:52
최고 판매량과 비교할 수도 있습니다. 현재 측정값과 목표를 항상 비교하고 있습니다.
the current sales with the lowest sales or maybe the
28:47:55
여기서 세 가지 카테고리로 나뉜 측정값이 있습니다. 이 값들은 현재 값입니다.
highest sales so as you can see we are always comparing the current measure together with a target with something else so for example we have here again a measure that is splitted by three categories so So those values are the current values.
28:48:07
이제 목표가 평균과 같은 경우, 각 행에 대해 200이 있습니다.
Now if you have a target like for example the average. Now as you can see for each row we have like the 200.
28:48:12
이 두 가지를 한 행에 갖게 되면, 우리는 단순히 빼면 됩니다.
Now what we can do once we have those two things in one row. We can go and simply subtract them.
28:48:17
A의 경우 현재 값은 평균과 정확히 같습니다. 둘 다 200이며, 차이는 0입니다.
So for the A the current value is exactly equal to the average. Both of them is 200 and the difference between them is 0.
28:48:24
이 제품은 평균적으로 성과를 내고 있습니다. 다음은 300이고 목표는 200입니다.
So this product is performing as an average. Now for the next one we have 300 and the target is 200.
28:48:29
그들 사이의 차이는 100입니다. 이는 이 카테고리가 매우 잘 수행되고 있음을 의미합니다.
So the differences between them is 100. That means this category is performing very well. So this is a good performer.
28:48:36
마지막으로, 우리는 -100을 얻게 됩니다. 이는 평균 이하임을 의미합니다.
Now for the last one, we will get minus 100. So that means it is below the average. So it is not performing very well.
28:48:43
이러한 유형의 분석을 위해 우리는 일반적으로 집계 윈도우 함수, 합계, 평균, 최대, 최소 또는 리드와 레그와 같은 값 윈도우 함수를 사용합니다.
And for this type of analysis, we usually use window functions like the aggregate window functions, the sum, average, max, min, or the value window functions like lead and lag.
28:48:53
이제 SQL로 돌아가 이 공식을 적용하여 비즈니스 성과를 측정해 보겠습니다.
So now let's go back to SQL and apply this formula in order to measure the performance of our business. So let's go. All right, my friends.
28:49:00
이제 우리는 다음 작업이 있습니다. 제품의 연간 성과를 분석하여 판매량을 평균 판매 성과와 이전 연도 판매량과 비교합니다.
So now we have the following task. analyze the yearly performance of products by comparing their sales to both the average sales performance of the product and the previous year sales.
28:49:11
조금 복잡하고 진지하게 들리네요. 시작하기 전에 커피를 마시죠.
Okay, this sounds a little bit complicated and serious. Let's have some coffee before we start.
28:49:15
여기서 우리는 무엇을 가지고 있나요? 제품의 연간 성과에 대해 이야기하고 있습니다.
Okay, so what do we have over here? So it is talking about the yearly performance of products.
28:49:22
즉, 주문 날짜를 차원으로 필요하고, 제품과 사용되는 측정값은 판매입니다.
So that means we need the order date as a dimension and as well the product and the measure that is used over here is the sales.
28:49:30
단계별로 진행합시다. 사실 테이블에서 필요한 것들이 있습니다.
So let's do it step by step so we need things from
28:49:33
사실 테이블에서 판매 데이터를 가져오고, 제품을 가져와야 합니다.
our fact table so fact sales and we
28:49:37
제품을 가져와서 멋진 이름을 갖기 위해,
need the product so i'm gonna go and get it from the dimension
28:49:40
제품 키로 데이터를 조인해야 합니다.
products in order to have a nice name so
28:49:43
우리는 제품 키로 데이터를 결합해야 합니다.
we have to join the data by the product key and
28:49:47
별칭을 p로 변경할 것입니다. 그래서 두 개의 테이블이 생겼습니다.
i'm gonna go and change the alias to p so product key okay so that we have our two tables now let's go and select our columns so we need
28:49:56
주문 날짜, 제품 이름, 그리고 측정값이 필요합니다.
the order date, we need the product name, and we need our measure. So it can be the sales amount.
28:50:03
그것은 연도별 성과를 분석해야 한다는 의미입니다.
All right, so now let's go and query those informations. Now we have to analyze the yearly performance.
28:50:08
우리는 날짜를 필요로 하지 않습니다. 세분화는 연도입니다.
That means we don't need the day. The granularity is the years. So that's why let's go and convert it using year function.
28:50:16
주문 연도로 부를 것입니다. 그리고 매출을 집계해야 합니다.
And we're going to call it order year. And of course, we have to go and aggregate then the sales.
28:50:21
현재 매출이라고 부를 것입니다. 날짜와 연도, 제품 이름으로 데이터를 그룹화해야 합니다.
And I'm going to call it current sales. And of course, we have to group up the data by the date, the year, and as well by the product name.
28:50:33
모든 null 값을 제거할 것입니다.
So that's it. Let's go and execute it. And of course, I'm going to go and get rid of all those nulls.
28:50:38
주문 날짜가 null이 아닌 곳에서.
So where order date is not null. All right. So with that, we have solved the first part.
28:50:45
제품의 연간 성과가 있습니다.
So we have the yearly performance of the product. Now in the task, we have to compare this value, the current sales, to the average sales performance.
28:50:54
평균 매출 성과와 비교해야 합니다.
the products so that means we need the average and as
28:50:57
작년 매출과 비교해야 합니다.
well the previous year sales so that means we have
28:51:00
같은 제품에 대해 작년과 비교해야 합니다.
to compare each value to the previous year for the same product
28:51:03
창 함수의 도움이 필요합니다.
of course so that means things are getting a little bit more complicated
28:51:07
하나씩 진행하겠습니다. 평균 매출에 집중하겠습니다.
and with that we need the help of the window functions let's
28:51:10
이 값들을 기반으로 할 것입니다.
do it one by one let's focus on the average sales so now
28:51:13
새로운 계산과 집계를 할 것입니다.
what you're gonna do based on those values based on these results
28:51:16
그것을 하기 위해서는 서브 쿼리나 CTE를 사용해야 합니다.
we will do a new calculations and aggregations
28:51:19
CTE를 사용할 것입니다. 더 깔끔해 보입니다.
and now in order to do that either we use a
28:51:22
연간 제품 매출로.
sub query or a cte i'm gonna go with the cte because it
28:51:25
이것은 새로운 이름입니다.
looks nicer so with yearly product
28:51:29
쿼리를 작성할 것입니다.
sales this is the new name that you are giving for
28:51:32
이 결과 위에 쿼리를 작성할 것입니다.
this results and now what we're gonna do we're gonna build queries
28:51:35
이 테이블에서 모든 것을 선택하겠습니다.
on top of these results so first of all i will just
28:51:38
작동하는지 테스트하기 위해.
select everything from this table yearly product sales
28:51:41
지금 데이터가 작동하는지 테스트하기 위해 선택하고 있습니다.
just to test so it is working now i'm selecting data
28:51:45
우리 도시에서 데이터를 선택하고 있습니다. 다음 단계는
from our city so now the next step i'm gonna go and
28:51:48
원하는 모든 열을 나열하는 것입니다. 순서는
list all the columns that i want in my my results so the order
28:51:51
날짜, 제품 이름, 현재 판매량입니다.
date the product name the
28:51:55
어떤 열을 표시할지 제어하기 위해
current sales this is just nicer in
28:51:58
최종 결과를 위해 어떤 열을 표시할지 제어해야 합니다.
order to have control on which columns you want to present at
28:52:01
데이터를 먼저 제품 이름으로 정렬하는 것입니다.
the end results now the next step i'm gonna go and order the
28:52:04
첫 번째 제품 이름과 데이터를
data by first the product name and
28:52:08
그 다음에 주문을 여기서 확인하면 결과를 더 잘 이해할 수 있습니다. 그래서 이 제품은 3년간의 판매가 있으며
then the order here and with that we can have better understanding of the results so we can see this product has three years of sales and those
28:52:15
각 연도의 현재 판매량입니다. 이제 우리는 가서
are the current sales for each year so now we have to go and
28:52:19
그 세 가지 판매의 평균을 계산해야 합니다.
calculate the average of those three sales
28:52:22
그렇게 하기 위해서는 현재 평균을 사용할 수 있습니다.
so in order to do that we can use the average current
28:52:26
우리가 가지고 있는 판매량입니다.
sales over we have
28:52:29
이제 데이터를 어떻게 분할할지 결정해야 합니다. 우리는
to decide now how to partition the data since we are focusing on
28:52:33
제품에 집중하고 있으므로 결과를 제품별로 분할해야 합니다.
the products we have to partition the results by the product
28:52:36
제품 이름으로 분할하겠다고 말할 것입니다.
name so we're going to say partition by product
28:52:39
데이터를 정렬할 필요는 없습니다. 왜냐하면 우리는
name and we don't have to sort the data because we are using
28:52:42
평균을 사용하고 있기 때문에 데이터가 어떻게 정렬되어 있는지는 중요하지 않습니다.
the average so it doesn't matter how the data is sorted
28:52:45
그래서 평균 판매량이라고 부르겠습니다. 이제 실행해 보겠습니다. 이 제품의 결과를 보면, 세 가지 값의 평균 판매량은 13,000입니다.
so let's call it average sales so let's go and execute it and now if you are looking to the results for this product the average sales of all those three values is 13 000.
28:52:57
이제 각 행에 대해 현재
so now as you can see for each row we have the current
28:53:00
판매량과 평균 판매량이 나란히 있습니다.
sales and side by side with the average sales and
28:53:03
다음 제품에 대해서도 마찬가지입니다. 이제 우리는
the same thing for the next product as well so now since we
28:53:06
현재 판매량과 평균을 같은 행에 가지고 있으므로
have both of the informations on the same row current
28:53:09
현재 값과 평균 값의 차이를 변경합니다. 그래서 당신이 해야 할 모든 것은
sales and the average the change the difference between the
28:53:13
다음과 같습니다.
current value and the average value so all what you have to do is to
28:53:16
현재 값과 평균 값을 빼는 것이므로
go and subtract right so we're gonna say the current
28:53:19
현재 판매량에서 평균 판매량을 빼고
sales subtracted by the average sales and
28:53:23
우리는 그것을 차이로 부를 것입니다
we're gonna call it the difference in
28:53:27
평균을 기준으로 하여 실행해 보겠습니다. 이제 비교 결과를 볼 수 있습니다.
average so let's go and execute it and now as you can see we are getting now the comparison we have the differences between the current and the average
28:53:36
물론, 제가 하고 싶은 것은 평균 이상인지, 이하인지 또는 평균인지 표시하는 플래그를 만드는 것입니다.
And of course, what I like to do is to make a flag or like indicator whether we are above the average, below the average or at the average.
28:53:43
그렇게 하기 위해서, 우리는 case when 문을 사용할 것입니다.
So in order to do that, we're going to go and use the case when statement.
28:53:47
차이가 0보다 크면 평균 이상입니다, 맞죠?
So if the difference is higher than zero, then we are above the average, right?
28:53:54
평균 이상입니다. 그에 대한 약어를 만들어 봅시다.
Above average. Let's have an abbreviation for that.
28:53:57
그리고 0보다 낮으면 평균 이하라는 뜻입니다, 맞죠?
And if we are below zero, that means we are below the average, right?
28:54:01
그렇다면 평균 이하입니다.
So below then below average.
28:54:05
정확히 0이면, 그렇지 않으면
and if it is exactly zero else then it is
28:54:08
평균입니다. 이제 끝내고
average so that's it let's end it and
28:54:12
평균 변화를 부르겠습니다.
i'm gonna call it average change so
28:54:15
이제 실행해 보겠습니다. 다시 집중해 보세요.
let's go and execute it now if you focus again on
28:54:18
제품 중 하나에서 이 제품의 현재 판매량을 볼 수 있습니다.
one of the products you can see the current sales of this product
28:54:22
2012년에는 평균 이하입니다.
in 2012 it is below the average
28:54:25
정말 낮고, 2013년에는 평균 이상입니다. 이 제품에겐 정말 좋은 해였습니다.
it is really low and for the next year for 2013 it is above the average it was really nice year for this product and the last year
28:54:34
2014년에는 다시 평균 이하였습니다.
2014 it was again below the average so
28:54:37
그렇게 해서 우리는 평균 이상인지 이하인지 빠르게 확인할 수 있는 좋은 플래그가 생겼습니다.
with that we have really nice flag in order to see quickly whether
28:54:40
우리가 0이 있는지 확인하는 것이 흥미롭습니다.
we are above or below the average and it is interesting
28:54:43
평균과 정확히 같고, 여기서는 0이 있습니다.
to see whether we have zeros so yeah sometimes it
28:54:46
평균 이하도 아니고 이상도 아닙니다. 그래서 우리는 비교하고 있습니다.
is exactly like the average and here we have like zero
28:54:49
각 제품의 판매 성과를 평균과 비교하고 있습니다.
it's not below or above so with that we are comparing
28:54:53
정말 간단하다는 것을 알 수 있습니다.
the performance of the sales of each products with
28:54:56
윈도우 함수를 사용하여 다시 우리의 작업을 확인해 보겠습니다.
the average and as you can see it is really simple yeah
28:54:59
창 함수 사용하여 우리의 작업을 다시 확인해 보겠습니다.
using the window functions so let's go and check again our task
28:55:02
현재 판매를 평균 판매 성과와 비교했습니다.
we have compared the current sales to the average sales performance
28:55:06
이제 이전 연도와도 비교해야 합니다.
now we have to compare it as well with the previous
28:55:09
이제 현재 판매를 비교해야 합니다.
year sales so let's go back to our example over
28:55:12
현재 판매를 평균이 아닌 이전 연도와 비교해야 합니다.
here this time we have to compare the current sales
28:55:15
현재 판매를 이전 연도와 비교해야 합니다.
not with the average but with the previous year so we don't have to write like another cte or query we can continue
28:55:22
같은 결과로, 이제 접근해야 할 것은
with the same results so now all what you have to do is to access
28:55:25
이전 연도에 대한 접근을 위해
the previous year and in order to do that we have amazing
28:55:29
라그라는 창 함수를 사용해 보겠습니다.
window function called lag so let's do it step by
28:55:32
단계별로 진행해 보겠습니다.
step so now we can go and create a new column it's called lag
28:55:35
새로운 열을 생성하고 싶습니다. 그것은 라그라고 합니다.
i want to access the previous value of what
28:55:39
현재 판매의 이전 값을 접근하고 싶습니다.
the current sales right so current sales and over we still have to partition the data by the product name
28:55:46
현재 판매를 기준으로 데이터를 분할해야 합니다.
because we focus on the products so partition by
28:55:50
제품에 집중하므로, 제품 이름으로 분할합니다.
product name but now in order to access
28:55:53
이전 값을 접근하기 위해 데이터를 정렬해야 합니다.
the previous value that means we have to sort the data
28:55:56
연도별로 정렬할 것입니다.
and we're going to sort it by the years we need the previous
28:55:59
연도별로 정렬할 것입니다.
year so we're going to say order by order year
28:56:03
이렇게 두고, 이 창 함수는 이전 연도 판매를 제공합니다.
and we're going to sort it ascending from the lowest to the highest so
28:56:06
이전 연도 판매를 이렇게 부르겠습니다.
we're going to leave it like this and with that this window function going to give us the previous year sales of the products so i'm just going to call it
28:56:14
문제가 있는 것 같습니다. 실행해 보겠습니다.
previous year sales like this and i think here we
28:56:17
이 제품 중 하나에 집중해 보겠습니다.
have something wrong okay so let's go and execute it and
28:56:20
이 제품의 첫 해는 이전 연도가 null이었습니다.
let's go and focus on one of those products so now for the first
28:56:23
이전 연도에 대한 데이터가 없습니다.
year of this product the previous year was null right
28:56:26
2013년에는 2012년의 이전 연도가 있습니다.
so we don't have any data from the previous year but
28:56:29
그래서 이제 이전 연도를 가져오고 있습니다.
for the 2013 we have a previous year of 2012
28:56:32
그래서 지금 우리가 이전을 가져오는 이유입니다.
so that's why now we are getting the previous
28:56:36
작년의 판매 수치를 기반으로 하고 있습니다.
value of the sales based on the years and the same thing
28:56:39
여기에서 작년의 판매 수치를 확인할 수 있습니다.
for the last year over here you can see we are getting the
28:56:42
이전 판매 수치가 작동하고 있습니다.
previous sales so it is working and for the next
28:56:45
첫 해의 경우 null을 받을 것입니다.
window same thing for the first year you will get null and
28:56:48
이전 판매 수치를 작년에서 가져올 것입니다.
the previous sales will get it from the previous year so
28:56:51
이제 이전 판매 수치가 있습니다.
with that we have now the previous sales and if you check
28:56:54
현재 연도의 판매 수치가 있습니다.
this over here we have in the same row now the
28:56:57
작년의 판매 수치가 있습니다.
current sales of the current year and as well the
28:57:00
이 두 정보를 비교하기 위해 빼야 합니다.
sales of the previous year now what we have to do the
28:57:04
현재 판매 수치에서 빼야 합니다.
same thing we have to go and subtract those two informations in order to compare them right so we're gonna go and do
28:57:10
전체 윈도우 함수입니다.
the same thing so we will get the current sales minus
28:57:13
작년이라고 부를 수 있습니다.
the whole thing the whole window function and
28:57:16
차이를 계산하고 있습니다.
we can call it previous year so difference
28:57:20
이 제품에 대한 차이를 계산하고 있습니다.
of the brief is here and with that we are calculating the differences
28:57:23
현재 판매 수치와의 차이가 큽니다.
between them so for this year for this product as
28:57:26
현재 판매 수치와 작년의 차이가 큽니다.
you can see the difference here is really big between the current sales
28:57:30
플래그나 지표를 만들 수 있습니다.
and the previous year now of course what we can do we can go and make as well a flag or an indicator i'm gonna go and copy the whole thing from the
28:57:38
올바른 기능을 가져와야 합니다.
previous average but we have to go and get the right
28:57:41
증가하고 있다고 말할 수 있습니다.
function this and the same over here and now it
28:57:44
증가 또는 감소하고 있습니다.
is not above or below the average i'm gonna say it is increasing
28:57:47
감소라고 부를 수 있습니다.
or decreasing right so increase or
28:57:51
변화가 없다고 말할 수 있습니다.
decrease and we can call it previous
28:57:54
실행해 보겠습니다.
year change and instead of average we can say no change
28:57:57
다시 실행해 보겠습니다.
so let's go and execute it and i'm having here an extra comma let's go and
28:58:03
실행되었습니다. 다시 한 번, 그 제품 중 하나에 집중해 봅시다.
executed so again let's go and focus on one of those products
28:58:06
이 제품의 첫 해에는 변화가 없습니다. 왜냐하면
for the first year of this product there is no change because
28:58:09
다음 해에 대한 이전 해가 없기 때문입니다.
there is no previous year for the next year of
28:58:12
이 제품은 현재 판매량이 이전 해보다 훨씬 높기 때문입니다.
this product we have an increase right because the current
28:58:16
이 제품의 마지막 해로 가면 감소가 있습니다. 현재 판매량이 이전 해보다 적기 때문입니다.
sales is way higher than the previous year and now
28:58:19
여기서 친구들, 우리는 이러한 유형의 분석을 연도별 분석이라고 부릅니다.
by going to the last year of this product we have a decrease because the current sales is less than the previous
28:58:25
연도별 분석을 하고, 만약
here so my friends we call this type of analyzes year
28:58:29
월별 분석을 계산하고 싶다면 매우
over year analyzes and if
28:58:32
간단합니다. 당신이 해야 할 일은 함수의 변화를 주는 것입니다.
you want to calculate the month over month analyzes it's very
28:58:35
연도에서 월로 바꾸면, 그로 인해 월별 데이터를 추출하게 됩니다.
simple all you have to do is to go and change the function from
28:58:38
부분과 월을 분석하는 것의 차이점은
year to a month and with that you are extracting the month
28:58:41
연도에서 월로 바꾸면, 그로 인해 월별 데이터를 추출하게 됩니다.
part and the difference between analyzing the months and
28:58:45
연도별 분석은 장기적인 트렌드 분석에 좋고, 반면에 월별 분석은 단기적인 트렌드 분석입니다.
years is of course the scope year over year is
28:58:48
당신은 데이터의 계절성에만 집중하고 있습니다.
good for long term trends analyzes where on the other hand the month over month it is short term trends analyzes
28:58:55
그래서 이것이 우리 성과를 분석하는 방법입니다.
you are just focusing on the seasonality of your data
28:58:58
우리 비즈니스는 현재 측정값을 목표와 비교하여
so this is how we analyze the performance of our
28:59:01
측정값을 사용하고 다양한 차원과 요소를 사용할 수 있습니다.
business by comparing the current measure with a target
28:59:04
그래서 판매 대신 수량을 확인할 수 있습니다.
measure and you can go and use different dimensions and stuff
28:59:07
제품 대신 고객을 확인할 수 있고, 당신은 가서
so instead of the sales you can check the quantity instead
28:59:11
현재 정보를 평균이나
of products you can check the customers and you can go and
28:59:14
이전 해와 비교할 수 있습니다. 당신은 가장 낮은 판매량과 비교할 수 있습니다.
compare the current information not only with the average or the
28:59:17
이전 해와 비교할 수 있으며, 가장 높은 판매량과 비교할 수 있습니다.
previous year you can compare it with the lowest sales
28:59:20
그리고 이는 많은 다양한 통찰력을 열어줄 수 있습니다. 그러나 우리는 항상 같은 방법을 사용하고 있습니다.
and the highest sales and it can open the door for many
28:59:24
창 함수 사용하여 현재를 비교합니다.
different insights but we are always using the same methods
28:59:27
값을 데이터 세트의 다른 값과 비교합니다.
using the window functions we compare the current
28:59:30
값을 데이터 세트의 다른 값과 비교합니다.
value with another value in our data sets
28:59:33
자, 이것이 우리가 성과 비교를 하는 방법입니다. 이제 비즈니스 성과를 분석하는 방법을 배웠습니다. 다음 단계에서는 부분 대 전체 분석을 할 것입니다.
so this is how we do performance comparison all right so with that you have learned how to analyze the performance of our business now in the next step we're gonna do part to whole analysis so let's go
28:59:48
자, 이제 부분 대 전체 분석이 정확히 무엇인지 알아보겠습니다. 우리는 부분의 비율을 전체에 대해 알아내기 위해 사용합니다.
Okay, so now what is exactly part to whole analyzes? Well, we use it in order to find out the proportion of a part relative to the whole.
28:59:55
여기서 우리는 개별 카테고리가 전체에 어떻게 기여하고 있는지를 분석할 수 있습니다.
Well, here we can analyze how an individual category is contributing to
29:00:00
전체에 대해 가장 영향을 미치는 카테고리를 이해하기 위해서입니다.
the overall in order to understand what is the most
29:00:03
전체에 대해 가장 영향을 미치는 카테고리입니다.
impacting category to the overall business so
29:00:06
이제 공식은 매우 간단합니다. 하나를 선택해야 합니다.
now for the formula it is very simple you have to go and pick one
29:00:10
측정값 중 하나를 총합으로 나누고
of your measures divided by the total of
29:00:13
100을 곱하여 특정 차원에 대한 비율을 찾습니다. 예를 들어,
the measure and then multiply it by 100 in order to find
29:00:16
판매를 예로 들면, 판매를 총 판매로 나누고 그 카테고리에 대해 100을 곱합니다.
the percentage by a specific dimension like for example if
29:00:19
그리고 국가별 비율을 찾습니다. 예를 들어 다시
you take the sales so you divide the sales by the total sales multiplied by hundreds by that category or if you take the quantity divided by the total quantity
29:00:28
우리는 카테고리별로 측정값을 나누었지만 이제는
and then find the percentage by a country so for example again
29:00:31
이 숫자를 가지고 무엇을 할 것인지, 비율을 계산할 것입니다.
we have our measure splitted by categories but now instead of
29:00:34
첫 번째로 200을 나누겠습니다.
having this number what we're gonna do we're gonna calculate the percentage
29:00:37
600을 곱하여 100을 곱하면
so for the first one we're gonna take the 200 divided by
29:00:41
600에 100을 곱하면
600 multiply it by 100 so we're gonna get the
29:00:44
비율 33이 나옵니다. 그래서 이전 카테고리에 대해 그렇게 하면 카테고리 P가 전체 숫자에 50을 기여하고 있다는 것을 쉽게 볼 수 있습니다.
percentage 33 so once we do that for the old categories it's gonna be now very easy to see that the category p it is contributing to the overall number by 50
29:00:54
그것은 물론 최고의 성과를 내는 것입니다. 그래서 당신은 머릿속에서 파이 차트처럼 시각화할 수 있고 각 부분이 전체 파이 차트에 어떻게 기여하는지 볼 수 있습니다.
which makes it of course a top performer. So you can visualize in your head as like a pie chart and you can see how each part is contributing to the whole pie chart.
29:01:03
그것을 통해 각 카테고리가 우리 비즈니스에 얼마나 중요한지를 이해하는 데 도움이 될 수 있습니다.
And with that, it can help us to understand the importance of each category to our business.
29:01:08
이제 이 공식을 우리의 측정값에 적용하여 카테고리의 중요성을 이해해 보겠습니다. 자, 시작합시다.
So now let's go and apply this formula to our measures in order to understand the importance of our categories. So let's go.
29:01:15
좋아요, 이제 부분 대 전체 분석을 해봅시다. 우리가 필요한 것은 하나의 차원과 하나의 측정값입니다. 예를 들어, 다음과 같은 작업이 있습니다. 매우 간단합니다.
Okay, so now let's do part to whole analysis. All what we need, one dimension and one measure. So for example, we have the following task. It is very simple.
29:01:22
어떤 카테고리가 전체 판매에 가장 많이 기여합니까? 이제 단계별로 진행해 봅시다.
Which categories contribute the most to the overall sales? So now let's go and do it step by step.
29:01:28
먼저 정보를 수집해야 합니다. 카테고리가 필요하고, 판매 금액이 필요합니다.
So first, we're going to go and collect the informations. So we need the category. We need the sales amount.
29:01:34
이 정보는 평소처럼 사실 판매와 우리의 차원인 제품에서 나옵니다.
And those informations come as usual from the fact sales and from our dimension, the product, right?
29:01:43
그래서 우리는 제품 키를 사용하여 빠르게 연결해야 합니다.
So we have quickly to go and connect them using the product key.
29:01:49
좋아요, 그래서 우리가 쿼리에 필요한 모든 것입니다. 이제 선택하러 가봅시다.
okay so that's all what we need for our query so let's go and select
29:01:52
여기 카테고리와 판매 금액이 있습니다.
so we have here the categories and the sales amount
29:01:55
이제 첫 번째로 총 판매액을 계산해야 합니다.
so now the first thing we have to calculate the total sales
29:01:58
각 카테고리에 대해, 그러니 가서 해봅시다. 아주 간단합니다.
for each category so let's go and do that it is very simple
29:02:01
총 판매액을 합산하고 데이터를 카테고리별로 그룹화하고 있습니다. 지금은 각 카테고리의 총 판매액이 있습니다.
so sum total sales and we are grouping up the data by the category so this is basics right now we have the total sales for each of those categories
29:02:13
비율을 계산하기 위해 두 가지 측정값이 필요합니다. 각 카테고리의 총 판매액이 이미 있습니다.
Now in order to calculate the percentage, we need two measures. The total sales for each category and we have it here already.
29:02:19
또한 옆에 모든 카테고리의 총 판매액이 필요합니다. 즉, 차원이 없는 큰 숫자입니다.
And as well side by side, we need the total sales across all categories. So the big number without any dimension.
29:02:26
결과를 보면 여기에서 카테고리의 세분화가 보입니다.
But now as you look to the result, you can see the granularity here is that category.
29:02:31
이제 다른 세분화로 다시 총 판매액이 필요합니다.
Now we need the total sales again by different granularity.
29:02:35
이것들을 함께 혼합하기 위해 윈도우 함수를 사용합니다. 이제 어떻게 할 수 있을까요?
And in order to mix those stuff together, we use the window functions. So now how we can do it?
29:02:39
여기 가서 윈도우 함수를 작성하기 시작하거나
either you go over here and start writing your window function and
29:02:43
물론 그룹화와 함께 할 수 있습니다. 또는
of course you can do it together with the group by or you can do it
29:02:46
cte를 사용하여 쿼리의 두 번째 단계로 진행할 수 있습니다.
as a second step in your query using either a cte
29:02:49
또는 서브 쿼리로 진행할 수 있습니다. 그래서 cte로 진행하겠습니다.
or sub query so i'm gonna go with the cte just
29:02:53
명확하게 하기 위해 카테고리 판매는
to make it clear so category sales like
29:02:57
이렇게, 이제 같은 정보를 다시 선택하러 갑시다. 카테고리 총 판매액은
this so now let's start again selecting the same information so category total sales from our
29:03:03
테이블 카테고리 또는 도시 판매에서 가져옵니다. 이제 실행하러 갑시다. 이제 같은 결과가 있습니다.
table category or city sales so let's go and execute it so now we have the same results and
29:03:10
이제 이렇게 윈도우 함수를 구축하러 갑니다. 우리는
now we're gonna go and build our window function like this so we're
29:03:13
모든 값을 집계하고 싶다고 말할 것입니다.
gonna say the sum we want to aggregate all those values
29:03:16
전체 데이터의 총 판매액을 얻기 위해서입니다.
right to get the total sales of the whole data
29:03:19
설정을 하므로 우리는 총 판매량을 말할 것입니다.
sets so we're gonna say sum total sales and
29:03:23
이제 큰 숫자를 얻기 위해 우리는 그 위와 안에서 아무것도 정의하지 않을 것입니다. 데이터를 분할하고 싶지 않기 때문입니다.
now in order to get the big number we're gonna say over and inside it we will not define anything because we don't want to partition the data we don't want to introduce
29:03:32
어떤 차원도 원하지 않습니다. 우리는 단지 큰 숫자를 원합니다.
any dimension we just want the big number and
29:03:35
그로 인해 우리는 전체 판매량을 얻을 것입니다.
with that we will get the overall sales
29:03:39
그러니 이제 실행해 봅시다.
so let's go and execute it now as you can
29:03:42
이것은 카테고리별 총 판매량입니다.
see this is the total sales by the category so
29:03:45
총 판매량은 카테고리별이며, 이것은
the total sales is by the categories and this is
29:03:48
모든 주문의 전체 판매량입니다.
the overall sales of all orders of everything
29:03:52
현재 나란히 두고 보니 가장 높은 수치입니다. 우리가 할 수 있는 것은 전체에 대한 경로를 쉽게 계산할 수 있습니다.
the highest number now since we have them side by side what we can do we can very easily calculate the path to whole
29:03:59
또는 비율입니다. 그러니 시작해봅시다. 우리는
or the percentage so let's start doing that we need
29:04:02
총 판매량을 원하고 이를 나누고자 합니다.
the total sales and we want to go and divide it by the
29:04:05
전체 판매량입니다. 우리는 창 함수로 이를 적용할 것입니다.
overall sales so we're going to take our window function and put it over
29:04:09
여기서 이제 곱해봅시다.
here so let's go and multiply it now
29:04:12
백 단위로, 이를 비율이라고 부를 것입니다.
with the hundreds i'm going to go and call it percentage
29:04:15
총계의 비율입니다. 이제 실행해봅시다. 보시다시피 우리는 0을 얻고 있습니다. 이는 총 판매량이
of total so let's go and execute it now as you can see we are getting zeros and that's because the total sales is not
29:04:23
부동 소수점이 아니기 때문입니다. 우리가 해야 할 것은 이를 어떤 것으로 변환하는 것입니다.
float so what we have to do is to go and cast it to something
29:04:26
소수점으로, 이렇게 부동 소수점으로.
like a decimal so float like this
29:04:29
이제 다시 실행해봅시다. 보시다시피 우리는
so let's go and re-execute it and now as you can see we are
29:04:32
현재 비율을 얻고 있지만, 많은 숫자가 있습니다.
getting now the percentages but we have a lot
29:04:35
콤마 뒤에 숫자가 많으니, 우리는
of numbers after the comma so we're gonna go around the
29:04:39
숫자를 반올림하러 가야 합니다.
numbers now so let's go to the start round and
29:04:42
그럼 끝에 쉼표로 가서 이렇게 해봅시다.
then go to the end comma and let's have like
29:04:45
두 자리 소수점으로 설정하니 이제 다시 실행해보면 완벽해 보입니다. 이제 우리가 할 수 있는 것은 백분율을 추가하는 것입니다.
two decimals so let's go and execute it again now looks perfect now what you can do we can go and add like a percentage and with that we are
29:04:53
전체를 문자열로 변환하고 있으니, 시작 부분에 연결을 하고 끝으로 가겠습니다.
converting the whole thing to a string so we're gonna do concatenation so concats at the start and go to the end
29:05:01
그리고 백분율 기호를 추가합시다. 또한, 총 판매량에 따라 데이터를 내림차순으로 정렬할 수 있습니다.
And let's add the percentage character. And as well, we can go and order the data by the total sales descending.
29:05:08
그럼 실행해봅시다. 결과를 보면 자전거 카테고리가 지배적이라는 것을 알 수 있습니다.
So let's go and execute it. So now by looking to the result, you can see the category bikes is dominating.
29:05:15
그래서 압도적으로 성과가 좋은 카테고리입니다.
So it is overwhelming, top performing the categories.
29:05:18
우리 사업의 총 판매량의 69%를 차지하고 있습니다.
It is making 69% of the total sales of our business.
29:05:23
이것은 친구들, 대부분의 사업 수익이 자전거에서 온다는 것을 의미합니다.
So this means my friends, most of the business revenue comes from the bikes.
29:05:28
그리고 보시다시피, 액세서리와 의류는 우리 사업에 미치는 기여가 정말 미미하여 좋지 않습니다.
And as you can see, the accessories and closings, they are really minor contributors to our business, which is not really good.
29:05:35
그리고 이것은 실제로 위험한 일입니다. 만약 한 카테고리가 당신의 전체 비즈니스를 지배한다면, 당신은 비즈니스에서 단 하나의 카테고리에 지나치게 의존하고 있는 것입니다.
And this is actually a dangerous thing. If you have like one category dominating your whole business, you are over relying on only one category in your business.
29:05:43
그리고 만약 이 카테고리가 실패한다면, 전체 비즈니스가 실패하게 될 것입니다.
And if this fails, this category, then the whole business is going to fail.
29:05:47
그래서 이것을 보면, 비즈니스는 두 가지 범주에서 모든 제품을 제거하거나 그 두 범주에 있는 제품의 수익을 더 높이는 데 집중해야 합니다.
So by looking to this, either the business has to decide
29:05:51
그래서 여러분이 볼 수 있듯이, 이러한 통찰력은 비즈니스에 정말 놀라운 것이며, 관리자와 의사 결정자가 상황을 빠르게 이해하고 매우 중요한 결정을 내리는 데 도움이 됩니다.
removing all those products by those two categories or to focus more on bringing more revenue for the products that are inside those two categories.
29:06:00
그리고 이제 결과를 통해 부분 대 전체 분석이 왜 중요한지 완벽하게 알 수 있습니다.
So as you can see, guys, those insights are really amazing for the business and helps the managers and the decision makers to understand what is going on quickly and make very critical decisions.
29:06:11
그 숫자만 보고는 범주의 중요성을 이해하기가 정말 어렵기 때문입니다.
And now you can see as well from the results perfectly why the part to whole analysis is very important.
29:06:17
하지만 각 범주가 전체 매출에 어떻게 기여하는지를 백분율로 보는 것은
because by just looking to those numbers it's going to be really hard
29:06:21
어떤 범주가 저조하거나 우수한 성과를 내고 있는지를 이해하는 데 더 쉽게 만들어 줍니다.
to understand the importance of the categories
29:06:24
이제 여러분은 총 매출 대신 총 주문 수로 집계를 변경하는 등 매우 간단한 공식을 가지고 있습니다.
but seeing the data as a percentage how each
29:06:27
또는 총 고객 수로 변경할 수 있으므로 어떤 유형의 측정을 가져와서 이 분석에 적용할 수 있습니다.
category is contributing to the whole sales of the
29:06:30
그리고 여러분은 의사 결정자를 위해 완전히 새로운 관점을 생성하게 될 것입니다.
business makes it easier to understand which category
29:06:33
비즈니스를 위한 새로운 전략을 개발하기 위해 매우 흥미로운 단계입니다. 이제 다음 단계에서는 제가 가장 좋아하는 주제로 넘어가서 SQL을 사용하여 데이터 세분화를 시작할 것입니다. 자, 시작해 봅시다.
is underperforming or top performing and now you have a very simple formula where you can go and change the metrics for example instead of total sales you can go and change the aggregation to total number of orders
29:06:45
좋아요, 이제 데이터 세분화란 무엇인가요? 여기서 우리가 할 것은 특정 범위를 기반으로 데이터를 그룹화하는 것입니다.
or the total number of customers so you can go and bring any
29:06:48
즉, 새로운 범주를 만들고 그 새로운 범주를 기반으로 데이터를 집계할 것입니다.
type of measures and bring it to this analysis
29:06:51
그에 대한 공식은 매우 흥미로울 것입니다. 이번에는 차원이 아닌 측정값으로 측정값을 가질 것입니다.
and you're going to generate completely new view for
29:06:55
따라서 두 개의 서로 다른 측정값을 선택하고 그 중 하나를 범위 또는 그룹으로 변환한 다음 이 측정값으로 데이터를 집계해야 합니다.
the decision makers in order to develop a new strategy for the business it was very interesting now in the next step we're going to do my favorite topic where we're going to start doing data segmentations using sql so let's go
29:07:10
예를 들어, 우리는 판매 범위에 따라 총 제품 수를 계산하거나 연령 그룹에 따라 총 고객 수를 계산할 것입니다.
okay so now what is data segmentations what we're going to do here is we're going to go and group up the data based on specific range.
29:07:17
보시다시피, 우리는 두 개의 측정값이 있으며, 새로운 통찰력을 생성하기 위해 이를 결합하려고 합니다. 다음 예를 보겠습니다.
So that means we're going to go and create a new categories and then go and aggregate the data based on the new category.
29:07:23
여기 예를 들어, 두 개의 측정값이 있습니다. 이제 첫 번째 단계는 그 중 하나의 측정값을 차원으로 변환하고 범주로 변환하는 것입니다.
And the formula for that is going to be very interesting. So it's going to be this time we're going to have a measure by a measure, not by dimension.
29:07:30
예를 들어, 값이 100 이하일 경우 '낮음'이라는 범주로 변환되고, 100과 200 사이일 경우 '중간'이라는 새로운 범주로 지정됩니다.
So you have to go and pick two different measures and convert one of those measures to a range or to a group and then aggregate the data by this measure.
29:07:37
200 이상은 '높음'으로 분류됩니다. 그래서 우리가 하고 있는 일을 보시다시피, 우리는 하나의 측정값을 가져오고 있습니다.
So for example, we're going to go and calculate the total number of products by the sales range or the total number of customers by the age group.
29:07:46
이제 이 측정값을 범주로 변환하고 있습니다.
So as you can see, we have two measures and we are trying to combine them together in order to create new insights. Let's have the following example.
29:07:52
그래서 여러분이 볼 수 있듯이, 우리는 하나의 측정값을 가져오고 있습니다.
So here for example, we have like two measures. And now the first step is that we're going to take one of those measures and convert it to a dimension, convert it to a category.
29:08:01
그리고 이제 이 측정값을 범주로 변환하고 있습니다.
For example, we're going to say if the values are like equal or below 100, it will be converted to a category called low And between 100 and 200, it's going to be assigned to a new category called medium.
29:08:13
그리고 이 측정값의 범위를 기반으로 새로운 카테고리와 새로운 차원을 구축하고 있습니다. 이제 마지막 단계는 가장 쉬운 단계입니다.
And everything above 200, it's going to be large. So as you can see what we are doing, we are taking one measure.
29:08:19
그리고 이 측정값의 범위를 기반으로 새로운 카테고리와 차원을 만들고 있습니다. 이제 마지막 단계는 가장 쉽습니다.
And based on the range of this measure, we are building a new categories, new dimension. And now the final step is the easiest one.
29:08:26
우리는 새로운 카테고리를 기반으로 또 다른 측정값을 집계할 것입니다. 그래서 낮은 것은 7, 중간은 6, 큰 것은 15가 될 것입니다.
We're going to go and aggregate another measure based on the new category. So we're going to have 7 for low, 6 for medium, and 15 for large.
29:08:33
그래서 이제 우리는 새로운 카테고리를 기반으로 새로운 카테고리나 세그먼트를 만들고 있습니다.
So with that, as you can see, we are creating new categories or segments based on a measure.
29:08:38
그리고 SQL에서 이러한 새로운 카테고리와 세그먼트를 만들기 위해 우리는 놀라운 case when 문을 사용합니다.
And then we are aggregating another measure based off these new segments.
29:08:43
왜냐하면 그것이 규칙을 정의하는 데 도움이 될 수 있기 때문입니다. 범위를 기반으로 새로운 카테고리와 레이블을 생성할 것입니다.
And in SQL, in order to create those new categories and segments, we use the amazing case when statements.
29:08:49
이제 이 공식을 데이터 세트에 적용하여 데이터를 세분화해 보겠습니다. 자, 시작합시다.
Because it can help us to define the rules. And based on the range, it's going to go and create a new category and labels.
29:08:56
좋아요, 이제 데이터를 세분화하고 필요한 것은 두 가지 측정값입니다.
So now let's go and apply this formula on our data sets in order to segment our data. So let's go.
29:09:01
이제 다음 작업이 있으며, 제품을 비용 범위로 세분화하고 각 세그먼트에 몇 개의 제품이 포함되는지 계산하라고 합니다.
Okay, so now let's go and segment our data and all what we need is two measures.
29:09:06
이 작업을 보면 두 가지 측정값이 있습니다. 첫 번째는 비용이고, 두 번째는 총 제품 수입니다.
So now we have the following task and it says segment products into cost ranges and count how many products fall into each segment.
29:09:13
물론, 우리는 이 두 가지 측정값 중 하나를 세분화해야 합니다. 이 작업에서는 비용을 세분화하고 있습니다.
So now by looking to this task, we have two measures first the costs and as well the second one is the total number of products.
29:09:21
따라서 우리는 이제 이 측정값을 가져와서 변환해야 합니다.
And of course, we have to go and segment one of those two measures. And in this task, we are segmenting their costs.
29:09:26
이 측정값을 차원으로 변환해야 하며, 이제 모든 정보가 사용 가능합니다.
So we have to focus now on taking this measure and convert
29:09:30
제품 테이블에서 이제 몇 개의 열을 선택해 보겠습니다.
it to a dimension so now all those informations are available
29:09:33
우리는 제품 키를 가져올 것입니다.
in the table products so now let's go and select few columns
29:09:36
제품 이름과 비용을 가져옵시다.
we're gonna get the product key and
29:09:40
이게 우리가 필요한 모든 것입니다. 이제 실행해 보겠습니다.
let's get the product name and the costs
29:09:43
이게 우리가 필요한 모든 것입니다. 이제 실행해 보겠습니다.
that's all what we need so let's execute it now as you can see
29:09:46
이것이 우리의 측정값인 비용입니다. 이제 이 측정값을 변환해야 합니다.
this is our measure the costs now we have to go and convert
29:09:49
이 측정값을 차원으로 변환해야 하며, 이를 위해 case when 문을 사용합니다. 우리는 항상 새로운 카테고리를 만들기 위해 case when 문을 사용합니다.
this measure to dimension and in order to do that we use the case win statements we always use the case win statement in order to create new categories so let's go and do that.
29:10:00
case when. 첫 번째 범위부터 시작합시다. 100 미만이라고 가정해 보겠습니다.
Case win. Let's start with the first range. Let's say it is below 100.
29:10:04
100 미만의 모든 비용은 새로운 값으로 레이블을 붙일 것입니다. 100 미만이 될 것입니다.
So all the costs that are below 100, we're going to label it with a new value. It's going to be below 100.
29:10:12
이제 다음 범위로 가봅시다. 100에서 500 사이의 비용이라고 말하고 있습니다.
So now let's go to the next range. We are saying win costs now between 100 and 500.
29:10:18
이 범위에 있는 모든 비용은 100과 500이라는 레이블을 받게 됩니다.
So all costs between this range, they will get the label 100 and 500.
29:10:25
이것은 매우 간단합니다. 500에서 1000 사이의 또 다른 범위를 가져가 봅시다.
so this is very simple let's go and get another range for example between 500 and 1000 then
29:10:33
500에서 1000 사이의 레이블을 받게 될 것이며,
it's gonna get a label between 500 and 1000 and
29:10:36
이제 얼마나 많은 카테고리와 세그먼트를 만들고 싶은지에 따라 다릅니다
now it depends how many categories and segments you want to create
29:10:40
각 조건이 충족될 때 이 사례의 각 행이
each row of this case when each condition will
29:10:43
차원에 대한 새로운 값을 생성하게 될 것이므로, 나는 여기서 멈추겠습니다. 마지막에 말하자면, 비용이
be creating like a new value for your dimension so i'm gonna stop with that i'm gonna say at the end else so if the cost is
29:10:50
이것들이 충족되지 않으면 1000을 초과할 것입니다
not fulfilling any of those it's gonna be above 1000
29:10:54
좋습니다. 그럼 이름을 지어봅시다. 비용 범위가 될 것입니다
right so that's it let's give it a name it's gonna
29:10:57
이제 실행해 보겠습니다
be cost range so now let's go and execute it
29:11:00
이제 결과를 확인해 보겠습니다. 예를 들어, 여기 비용은
now let's go and check the result for example the cost here is
29:11:03
0입니다. 100 미만으로 정확합니다. 이 값은
zero it is below 100 which is correct this value
29:11:06
1000을 초과합니다. 이것은 500과 1000 사이입니다
is above 1000 this is between 500 and 1000
29:11:09
그리고 이것은 100과 500 사이입니다. 모든 것이 정확해 보입니다. 좋습니다. 그래서 우리는
and this is between 100 and 500 so everything looks correct nice so with that we are
29:11:16
첫 번째 단계를 완료했습니다. 우리는 하나의 측정을 변환했습니다
done with the first step where we have converted one measure
29:11:19
차원으로. 그래서 이제 세그먼트가 있습니다
into a dimension so with that we have now our segments
29:11:22
다음 단계는 데이터를 집계하는 것입니다
the next step is that we're gonna go and aggregate
29:11:25
이 새로운 차원을 기반으로 하여
the data based on this a new dimension so either
29:11:29
한 번에 하거나, 제가 보통 하는 것은 모든 것을 하나에 넣는 것입니다
you do it in one go or what i usually do i put everything in one
29:11:32
도시 또는 서브 쿼리로, 나는 이를 제품 세그먼트라고 부를 것입니다. 이 결과를 기반으로
city or a sub query and i'm gonna call it products segments as based on these results i'm gonna go
29:11:40
데이터를 집계할 것입니다. 이것은 내 임시 결과입니다
aggregate the data so this is my temporary results
29:11:44
이제 이렇게 데이터를 집계하겠습니다. 먼저
and now we're gonna go and just aggregate the data like this so
29:11:47
우리의 차원 비용 범위를 가져오겠습니다
let's get first our dimension cost range and
29:11:50
그런 다음 우리의 측정이 필요합니다. 제품 수를 세는 것입니다
then we need our measure so it's gonna be count product
29:11:53
키를 총 제품으로
key as total products
29:11:57
우리의 도시에서 그것은 제품이었습니다
from our city it was the product
29:12:00
세그먼트와 함께 우리의 새로운 차원으로 그룹화합니다
segments and then group by our new
29:12:03
그게 전부입니다. 매우 간단합니다. 실행해 보겠습니다
dimension that's it it's very simple let's go and execute
29:12:06
이제 출력에서 세그먼트화된 것을 볼 수 있습니다
it now now you can see in the output we have our segmented
29:12:10
측정하고 각 세그먼트의 총 숫자를 볼 수 있습니다.
measure and we can see the total numbers in each of those
29:12:13
세그먼트와 범위를 정렬할 수 있습니다.
segment and range and of course we can go and order the
29:12:16
데이터를 집계하여 총 제품을 정렬해 보겠습니다.
data by our aggregation the total products let's go and
29:12:19
내림차순으로 실행해 보겠습니다. 이제 보시다시피,
execute it maybe descending so now as you can see we
29:12:22
비용이 많이 들지 않는 제품이 많이 있습니다.
have a lot of products that are not costing a lot
29:12:25
100 이하이고 그 다음은 100에서 500 사이이며, 가장 적은 수의 제품은
it is below 100 after that between 100 500 and the lowest number of products is in the range
29:12:32
1000 이상입니다. 그래서 많은 제품이 없습니다.
that is above 1000 so we don't have a lot of products
29:12:36
비용이 많이 드는 제품이 있으며, 아마도 많은
that are costing a lot and that's because maybe we have a lot
29:12:39
액세서리가 비즈니스에 있기 때문입니다. 그래서 친구들, 이것은
of accessories in the business so my friends this is
29:12:42
데이터 세트의 차원이 충분하지 않다면
very powerful if your dimensions in the data set is
29:12:45
측정값 중 하나를 차원으로 변환할 수 있습니다.
not enough to create insights you can take one of your
29:12:48
그런 다음 이 새로운 차원을 기반으로 다른 측정값을 집계합니다.
measures convert it to a dimension using casewin
29:12:51
측정값과 차원을 통해 끝없는 보고서를 생성할 수 있습니다.
and then aggregate your other measures based on this new dimension so we are deriving new informations and as i told you by just following this concept
29:13:00
비즈니스나 데이터 세트가 작더라도
measures and dimensions you can generate endless
29:13:03
이제 가서 다른 것을 세분화해 보겠습니다.
amount of reports even if your business or
29:13:06
이번에는 조금 더 복잡할 것입니다.
your data set is small okay my friends so now let's go and
29:13:09
다음 작업이 있으며 고객을 그룹화하라고 합니다.
segment something else so this time it's gonna be a little bit more complicated
29:13:13
소비 행동에 따라 세 가지 세그먼트로 나누어야 합니다.
so we have the following task and it says group customers into
29:13:16
VIB 고객이 있으며, 이들은 최소 12개월의 이력이 있고
three segments based on their spending behavior so
29:13:20
5천 이상을 소비하는 고객입니다. 두 번째 카테고리는
we have the vib customers they are the customers with at least 12 months of history and spending more than five thousands and the
29:13:28
정기 고객으로, 이들도 최소 12개월의 이력이 있지만
second category we have the regular customers they have at
29:13:31
5천 이하로 소비합니다. 마지막 카테고리는
least as well 12 months of history but they spend
29:13:34
신규 고객으로, 이들의 수명은 12개월 미만입니다.
like less than 5 000 and the last category we have the
29:13:37
고객의 총 수를 찾아야 합니다.
new customers their lifespan is less than 12
29:13:40
각 그룹별로 고객의 총 수를 찾아야 합니다.
months and we have to find the total number of customers by
29:13:44
각 그룹의 총 고객 수를 찾아야 합니다.
each group so now here we have a lot of measures and stuff so
29:13:47
첫 번째는 총 고객 수입니다.
the first one is the total number of customers this is going to
29:13:50
우리가 할 최종 집계가 될 것입니다.
be the final aggregation that we're going to do but what is interesting
29:13:53
세그먼트를 구축할 것입니다.
we're going build the segments and this time is based on
29:13:56
첫 번째는 각 고객의 총 개월 수를 기준으로 합니다.
different columns so first it is based on a measure
29:13:59
총 지출과 총 판매 수를 기준으로 합니다.
the total number of months for each customer
29:14:03
우리는 판매와 각 고객의 총 개월 수를 가지고 있습니다.
and as well the total spending the total number of sales
29:14:06
총 고객 수를 가지고 있습니다.
so we have the sales we have the total number of months
29:14:09
단계별로 진행할 것입니다.
and as well the total number of customers so now we're going to do it
29:14:12
필요한 모든 데이터를 수집하기 시작합니다.
step by step don't worry about it so now what i usually do i
29:14:15
총 고객 수를 집계하기 위해 고객 키가 필요합니다.
start collecting all the data that i need so what do we need we need a customer key in order to do the aggregation for the total number of customers we need as well the sales amount right
29:14:26
지출을 계산하기 위해 날짜가 필요합니다.
for the spending and now in order to calculate those
29:14:29
고객의 수명을 계산해야 합니다.
number of months we need a date and for that we have
29:14:32
주문 날짜를 사용하여 생성합니다.
to calculate the lifespan of a customer and usually
29:14:35
주문 날짜가 필요합니다.
we create it using the order date i'm gonna show you how we're
29:14:39
사실 테이블에서 시작하겠습니다.
gonna do it so we need the order dates and of course we have to select our tables so let's start with the fact table so fact sales and we're gonna join it with our customers
29:14:49
고객 차원과 키입니다.
so our dimension customers and the key
29:14:52
고객의 키와 테이블에서 어떤 열이 오는지 지정해야 합니다.
for that it is the customer key as well for the customers and here we have to specify which column come from which table so the
29:15:00
고객의 첫 번째 열입니다.
first one from the customers the sales from the fact and the
29:15:03
주문 날짜에서 실행합니다.
order date from the fact as well so now let's go and
29:15:06
고객과 판매를 확인할 수 있습니다.
execute now we can see we have our customers the sales
29:15:09
지출 범위를 지정하는 데 도움이 됩니다.
and the order dates so now the sales can help us in order
29:15:12
수명을 계산해야 합니다.
to specify the range of spending but now what is interesting we have to calculate the lifespan so now in order to get the lifespan we have to find
29:15:21
첫 번째 주문과 마지막 주문을 확인하십시오.
out the first order and the last order
29:15:24
각 고객 간의 몇 개월이 있는지 확인하십시오.
of each customer so how many months is between the
29:15:27
각 고객의 첫 주문과 마지막 주문 사이의 월 수
first order and the last order so in order to do that we need the min function for the order dates
29:15:34
첫 주문과 마지막 주문 사이의 최대값
so this is the first order and the max in order to get the last order right
29:15:41
최대값을 얻기 위해 데이터를 그룹화해야 합니다
and since we are using min and max we have to go and group up the data and we need to do that anyway in order to get the total spending so for the sales amount we're gonna have the sum in order
29:15:54
총 지출을 계산하기 위해
to have the total spent total spending and
29:15:57
데이터를 고객 키로 그룹화합니다
we don't need the order date and the dimension where we're gonna group
29:16:00
이제 실행해 보겠습니다
up the data is by the customer key so let's
29:16:03
모든 고객과 총 지출 목록이 있습니다
go and execute it so now in the results we have a list of
29:16:06
각 고객의 첫 주문 날짜와 마지막 주문 날짜
all our customers and as well the total spending for
29:16:10
주문 날짜 사이의 월 수를 계산하기 위해
each customer and we have the first order date and the last
29:16:13
첫 주문과 마지막 주문 사이의 월 수를 계산합니다
order dates now in order to calculate how many months between
29:16:16
일수 차이를 구하는 함수를 사용합니다
the first order and the last order we can
29:16:19
월 수를 계산하기 위해 첫 주문 날짜를 사용합니다
go and use the function day diff in order to get a
29:16:23
최신 주문 날짜를 사용할 수 있습니다
new measure so let's go and do that day diff and now since we need the number of months we're going to use the month and then the second argument gonna be the first order so order date
29:16:35
이것을 생애 주기라고 부르겠습니다
and the second one can be the latest so max order date
29:16:39
쿼리를 실행하고 결과를 확인해 보겠습니다
and we're gonna call this life span
29:16:42
고객 712의 결과를 확인할 수 있습니다
so let's go and query and let's have a look to our
29:16:45
첫 주문과 마지막 주문 사이의 11개월
results you can see for this customer 712 between
29:16:48
이 고객은 첫 주문과 마지막 주문이 같은 달입니다
the first order and the last order we have 11 months
29:16:51
이로써 생애 주기를 얻었습니다
and for this customer over here we have zero because the first order and the last order is in the same month and maybe there is only one order
29:16:59
새로운 측정을 도출했습니다
so with that we have the lifespan and as you can see
29:17:02
주문 날짜를 기반으로 새로운 측정을 도출합니다
guys we have derived a new measure from the dimension
29:17:06
새로운 측정과 차원을 변환합니다
order dates in order later to derive from
29:17:09
측정을 새로운 차원으로 변환합니다
this new measure a new dimension the segments so
29:17:12
일반적으로 분석기와 SQL에서 수행하는 작업입니다
we are converting a dimension to a measure and then from
29:17:16
모든 것을 가지고 있습니까?
a measure to a new dimension and this is usually what
29:17:19
우리가 분석기와 SQL에서 하는 일입니다. 이제 모든 정보를 가지고 있나요?
we do in analyzers and in sql so now do we have all
29:17:22
논리를 위한 정보가 있으니, 우리는 수명과 총 몬스터 수, 총 지출을 가지고 있습니다. 이제 세그먼트를 만들 준비가 되었습니다.
the informations for the logic so we have the lifespan so we have the total number of monsters we have the total spending and i think we are ready to start building our segments.
29:17:31
이제 우리가 할 일은, 준비한 결과를 바탕으로 세그먼트를 만드는 것입니다.
So now what we're going to do, we're going to create the segments based on these results that we have prepared.
29:17:35
이 결과는 최종 결과 이전의 중간 결과입니다.
So this result is the intermediate result before the final one.
29:17:39
이제 CTE에 넣거나 서브 쿼리를 사용할 것입니다. 저는 보통 CTE를 사용합니다. 더 좋습니다.
Now, either you're going to put it in a CTE or a sub query. Well, I usually go and use the CTE. It is nicer.
29:17:47
고객 지출과 관련하여 전체를 CTE에 넣고, 중간 결과를 바탕으로 새로운 쿼리를 작성할 것입니다.
So with customer spending and I'm going to put the whole thing in a CTE and we're going to start writing a new query from the scratch based on the intermediate results.
29:17:58
고객 키를 다시 선택해 보겠습니다. 총 지출과 수명을 가져올 것입니다.
So let's go and select again the customer key. I'm going to get the total spending and the lifespan.
29:18:05
실제로 첫 번째와 마지막 주문은 필요하지 않습니다. 새로운 도시에서 모든 정보를 가져올 것입니다.
So we don't actually need the first and the last order. And we're going to get all those informations from our new city.
29:18:12
이제 실행해 보겠습니다. 세그먼트를 만들기 시작합시다. 그리고 평소처럼 case when 문을 사용할 것입니다.
So let's go and execute. And now let's start building the segments. And as usual, we're going to go and use the case when statements.
29:18:19
새로운 열을 도출하고 만드는 데 놀라운 문장입니다. 첫 번째 카테고리에 대해 무엇이 있나요?
It is just amazing statements in order to derive and build new columns. So now what do we have for the first category?
29:18:26
12개월 이상이고 5000 이상 지출하는 고객들입니다.
So they are the customers over 12 months and spending more than 5000.
29:18:31
이제 수명이 12 이상이고 총 지출이 5000 이상이면 VIP 고객이 됩니다.
So now we're going to say if the lifespan is higher than 12 and the total spending is higher than 5000, then we have our VIP customers.
29:18:44
이것이 첫 번째 레이블입니다. 두 번째로 넘어갑시다. 수명이 12 이상이라고 생각합니다.
So this is the first label. Let's go to the second one. If the lifespan as well, I think more than 12.
29:18:51
확인해 보겠습니다. 최소한 12 이상입니다. 여기에 실수가 있습니다.
So let's go and check. Well, it is at least 12. I have here a mistake.
29:18:54
그래서 이제는 크거나 같아야 합니다. 이제 더 정확해졌습니다.
so it's gonna be larger or equal so now it is
29:18:57
최소 12개월 이상인 고객들입니다. 하지만
more correct so the customers that has at least 12 months but
29:19:01
5000 이하로 지출하는 고객들입니다. 즉,
they spend like five thousand or less so that means
29:19:04
조건은 동일하게 유지되지만 총 지출은 5000 이하가 될 것입니다. 이들은 일반 고객입니다.
it's gonna stay the same condition but the total spending will be less or equal five thousands and they are the regular customers so
29:19:15
이 두 조건을 충족하지 않으면 이 레이블을 받게 됩니다.
they will get this label now if it is not fulfilling those two conditions
29:19:20
이것은 새로운 고객이라는 의미입니다.
what this means this means this is a new customer
29:19:23
그렇습니다. 이 레이블을 받게 됩니다. 이제
right so they will get this label let's go and have
29:19:26
끝을 짓고 고객 세그먼트라고 부릅시다.
an end and let's call it customer segments
29:19:29
이제 실행해 보겠습니다. 고객 712를 살펴보겠습니다.
so let's go and execute it now let's
29:19:32
총 지출이 5000 이하이므로 이 고객은 VIP가 아니며, 수명도 12개월 미만입니다.
have a look for this customer 712 so the total spending is less than 5000 so this customer is not a vip and as well the lifespan is less than 12.
29:19:44
그래서 이것은 우리에게 새로운 고객이라는 의미입니다. 다음 고객은 VIP입니다.
so that means for us it is a new customer now the next one we
29:19:48
VIP 고객이므로 이 고객은
have a VIP so this customer has a history at
29:19:51
최소 12개월 동안의 기록이 있으며, 총 지출이 5000 이상이기 때문에 이 고객은 VIP입니다. 이제 검색해봅시다.
least 12 months so we have here 16 months and as well the total spending more than 5000 that's why this customer is a VIP but now let's go and search
29:20:00
또는 일반 고객 2349
or a regular customer 2349
29:20:04
이 고객은 5000 미만을 지출했습니다.
so this customer spent less than 5000 so
29:20:07
여기서 이 조건을 충족하고 있습니다.
we are fulfilling this condition over here and as well
29:20:10
이 고객은 최소 12개월의 기록이 있습니다.
this customer has at least 12 months of
29:20:13
그래서 우리는 일반 고객이 있습니다. 이제
history that's why we have a regular so now as you can
29:20:16
우리는 두 가지에서 새로운 차원을 도출했습니다.
see we have derived a new dimension from two
29:20:20
수명과 총 지출을 측정합니다.
measures the lifespan and the total spending now
29:20:23
물론 마지막 단계는 우리가 찾아야 할 것입니다.
of course the last step what is gonna be we have to go and find
29:20:26
각 카테고리의 고객 총 수
the total number of customers for each of those categories
29:20:29
이제 우리가 할 일은 모든 것을 제거하고
so now what we're gonna do we're gonna remove all those stuff and
29:20:32
우리의 새로운 차원으로 시작할 것입니다.
we're gonna start with our new dimension and then comes the
29:20:35
그 다음은 집계 고객 키입니다.
aggregation counts customer key so
29:20:39
총 고객 수로
as total customers and then we
29:20:42
새로운 차원에 따라 데이터를 그룹화해야 합니다.
have to group up the data by our new dimension so this is gonna be really annoying if i'm gonna take this here and put it in the group by because
29:20:51
이것은 매번 논리를 변경할 때마다
this means each time i'm changing the logic i have to take
29:20:54
선택 문에서 한 번, 그룹에서 두 번 처리해야 합니다.
care of that twice one in the select statements and
29:20:57
그 대신에 제가 할 일은 마음을 바꾸는 것입니다.
the second one in the group i so now actually instead of that
29:21:00
여전히 두 번째 단계에서 집계를 유지할 것입니다.
what i'm gonna do i change my mind i'm gonna still
29:21:03
고객 키가 필요하고 고객 정의가 있습니다.
having the aggregation in the second step so
29:21:07
세그먼트가 있으며, 이제 서브 쿼리를 사용할 것입니다.
we need the customer key we have the definition of our customer
29:21:10
집계를 두 번째 단계로 설정했습니다.
segments and now i'm gonna go and use the sub query where
29:21:13
중간 결과를 다시 얻을 수 있습니다.
i put the aggregation as a second step so my friends that means this is again a second
29:21:20
물론 두 번째 CTE에 넣을 수 있습니다.
intermediate results you can of course put it in a second cte
29:21:23
그래서 이것은 첫 번째 중간 결과입니다.
so that means this is the first intermediate
29:21:26
우리가 수명과 총 지출을 생성한 결과입니다.
results where we have created the lifespan and the total spending
29:21:29
두 번째 중간 결과는 고객 세그먼트를 생성하는 것입니다.
and the second intermediate result is creating the
29:21:32
그 다음에는 고객 키를 세는 것입니다.
customer segments and the third step and the last one is by doing the final aggregation so we can do it like this select our dimension customer segment
29:21:43
우리의 서브 쿼리입니다.
then we're gonna go and count the customer key from
29:21:46
우리의 서브 쿼리, 그래서 이것이 우리의
our sub query so this is our
29:21:49
서브 쿼리이며, 우리의 그룹화를 잊지 마세요.
sub query and don't forget to group by our
29:21:52
차원 고객 세그먼트, 내가 잘못 이해한 것 같아, 알겠어.
dimension customer segments i think i have it wrong all right
29:21:55
그래서 이것이 서브 쿼리이고, 이것이 마지막 단계입니다.
so this is the sub query and this is the final step
29:21:59
우리는 모든 것을 집계하고 있으며, 데이터를 정렬할 것입니다.
where we are aggregating everything i'm gonna go and order
29:22:02
총 고객 수에 따라 이렇게, 이제 전체를 실행해 보겠습니다. 잘못된 순서가 아니라 내림차순으로.
the data by the total customers like this so now let's go and execute the whole thing Well, descending, not ascending.
29:22:12
좋아요, 이제 결과에서 볼 수 있듯이, 가장 많은 고객이 새로운 카테고리에 속합니다.
Okay, so now we can see from our results, the highest number of our customers belong to the category new.
29:22:19
우리 비즈니스에는 14,000명의 신규 고객이 있습니다. 그리고 두 번째 카테고리는 정기 고객입니다.
So we have 14,000 customers that are new in our business. And then the second category, we have the regular customers.
29:22:26
우리는 약 2,000명의 고객이 있습니다. 그리고 VIB 고객이 많이 있습니다.
So we have around 2,000 customers. And in VIB, we have a lot of VIB customers.
29:22:31
우리 비즈니스에는 1,655명의 VIB 고객이 있습니다. 그래서 친구들, 우리는 데이터 세분화를 완료했습니다.
So we have 1,655 VIB customers in our business. So with that, my friends, we have done data segmentation.
29:22:37
놀랍습니다. 우리는 고객을 지출 행동에 따라 세분화했습니다.
It is amazing. we have segmented our customers based on their spending behavior.
29:22:42
그리고 보시다시피, 모든 정보는 우리의 데이터에서 완전히 파생되었습니다.
And as you can see, all those informations are totally derived from our data.
29:22:47
이것은 고객 행동에 대한 깊은 이해를 돕습니다.
And this helps us to have a deep understanding of the behavior of our customers.
29:22:51
물론, 이것은 스마트한 결정을 내리는 데도 도움이 됩니다.
And of course, this can help as well making smart decisions.
29:23:00
좋아요, 친구들, 그래서 이를 통해 SQL을 사용하여 수행할 수 있는 다섯 가지 다른 유형의 데이터 분석을 다루었습니다.
All right, my friends, so with that, you have covered the five different types of data analytics that we can do using SQL.
29:23:06
이제 제가 프로젝트에서 마지막 팁으로 하는 것은, 데이터 세트에서 수행한 다양한 탐색 및 분석 유형을 수집하려고 노력하는 것입니다.
Now, what I usually do as a last tip in my project is that I try to collect all the different types of explorations and analyzes that I have done in my datasets.
29:23:15
그래서 모든 것을 하나의 예를 들어, 보기나 테이블에 넣고 다른 사용자에게 제공할 수 있습니다.
So that I can put everything in one, for example, view or table and then offer it to other users.
29:23:20
이렇게 하면 다른 사용자나 이해관계자가 의사 결정을 위한 빠른 분석을 할 수 있습니다.
And with that, it can help the other users or stackholders to make quick analyzes for decision making.
29:23:26
이제 우리가 할 일은, 많은 다양한 분석을 하나의 큰 스크립트로 가져오는 요구 사항을 가질 수 있습니다.
So now what we're going to do, we can have like some kind of requirements where we're going to bring a lot of different analyzes in one big script in order to have insights about one object.
29:23:35
예를 들어 고객과 같은, 그래서 요구 사항을 보여드리겠습니다.
like for example the customers so i'm gonna show you the requirement
29:23:38
이 보고서의 요구 사항을 분석하고 작성할 것입니다.
of this report and we're gonna analyze it and start writing
29:23:41
스크립트를 작성할 것이니 이제 시작해 보겠습니다.
the script so let's go okay friends so now let's create
29:23:44
고객 보고서를 작성할 것이며, 다음은 요구 사항입니다.
a customer report and here are the requirements for
29:23:47
보고서는 주요 고객 지표를 통합해야 합니다.
the report so now we have like a general statement it says this
29:23:50
보고서는 주요 고객 지표를 통합해야 합니다.
report should consolidate key customer metrics
29:23:53
그리고 고객에 대한 모든 세부 정보를 수집해야 합니다. 이름, 나이, 거래 세부사항과 같은.
and behaviors so it says first we have to gather all the details about the customers like names age transaction details
29:24:01
그리고 고객을 VIP, 일반 및 신규와 같은 카테고리로 나누어야 하며, 나이 그룹별로도 나누어야 합니다.
And then we have to segment the customers into categories, VIP, regular and new, and as well by the age groups.
29:24:07
그리고 총 주문, 총 매출, 수량, 제품 등과 같은 집계도 제공해야 합니다.
And we have to provide as well aggregations like the total order, total sales, quantity, products, and so on.
29:24:14
그리고 최근성, 평균 주문 가치, 평균 월 지출과 같은 중요한 KPI를 생성해야 합니다.
And we have to generate important KPIs like the recency, the average order value, the average monthly spends.
29:24:21
그래서 우리는 할 일이 많고 단계별로 진행할 것입니다. 자, 이제 복잡한 쿼리를 구축하는 과정에서 단계별로 안내하겠습니다.
So we have a lot of things and we're going to do it step by step. Alright, now I'm going to take you step by step in the process of building a complex query that I usually use in order to build a report.
29:24:31
이제 제가 보통 하는 세 번째 작업은 데이터베이스에서 데이터를 선택하는 것입니다. 보통 사실 테이블에서 시작합니다.
Now, the third thing that I usually do is I start selecting the data from the database and I usually start with the fact table.
29:24:38
그래서 이것이 저의 시작점입니다. 그리고 보통 차원과 조인합니다. 여기서는 왼쪽 조인을 사용합니다.
So this is my starting point. And then usually I join it with the dimensions. And here I use left join.
29:24:44
그 후에 데이터를 필터링하는 방법에 대해 생각합니다. 왜냐하면 보통 데이터베이스에 있는 모든 데이터가 필요하지 않기 때문입니다.
And after that, I think about how to filter the data because usually we don't need all the data that is available in the database.
29:24:50
물론 결과에서 모든 열을 선택하지 않을 것입니다.
And of course in the result, I will not be selecting all the columns.
29:24:53
보고서에 필요한 관련 열만 선택할 것입니다.
I'm going to be selecting only the relevant columns that I need for my reports.
29:24:58
복잡한 쿼리가 있으므로 프로세스를 여러 단계로 나누겠습니다.
So since we have like complex query, we will be dividing the process into multiple steps.
29:25:02
이 단계를 기본 데이터라고 부릅니다. 이것이 다음 단계의 기초, 범위가 될 것입니다.
And I usually call this step the base data. And this is going to be the foundation, the scope for the next steps.
29:25:08
여러 단계가 있으므로 이것을 CTE에 넣겠습니다. 그래서 우리는 이것을 중간 결과로 갖게 됩니다.
And since we have like multiple steps, I'm going to put this in a CTE. So we have this as an intermediate results.
29:25:14
이 단계에서 우리가 할 일은 몇 가지 변환을 수행하는 것입니다. 예를 들어 새로운 열을 계산하고 파생시키거나 날짜를 형식화하는 것입니다.
And what we're going to do in this step as well, we're going to do a few transformations like maybe calculating and deriving a new columns, maybe formatting the date.
29:25:22
몇 가지 기본 변환입니다. 이제 보고서를 위한 결과를 구축해 보겠습니다.
So some basic transformations. So now let's go and build this results for our reports.
29:25:26
첫 번째 단계는 테이블에서 핵심 열을 검색하는 것입니다. 함께 해봅시다.
So the first step is retrieving the core columns from the tables. So let's go and do it together.
29:25:32
물론 사실 테이블인 사실 판매와 차원 고객이 필요합니다.
So we need, of course, our fact table, fact sales, and we need our dimension gold customer.
29:25:39
그리고 평소처럼 연결하겠습니다. 알겠습니다. 기본적인 것입니다.
And as usual, we're going to go and connect them. All right. Okay. So this is the basic.
29:25:45
이제 우리가 할 일은 보고서에 필요한 모든 열을 검색하는 것입니다. 시작해 봅시다.
And now what we're going to do, we're going to go and retrieve all the columns that we need for our reports. So let's start picking stuff.
29:25:51
주문 번호를 가져옵니다. poda를 가져옵시다.
So order number. let's get the poda
29:25:54
주문 날짜 판매 키
key the order date sales
29:25:57
수량 및 금액
amount quantity and
29:26:00
사실에서 모든 것을 다 한 것 같아
i think that's all from the facts let's go and get
29:26:03
고객의 통합된 정보
fused information from the customers so let's get the
29:26:07
고객 번호 키
customer key the customer number
29:26:10
이름과 성
the first name and as well the last name and
29:26:13
우리가 나이 그룹을 생성해야 하므로 생년월일을 가져올 수 있습니다
what else we can go and get the birth dates because we have to create the age groups so birth dates let's go and query so i think
29:26:22
우리가 해야 할 모든 열입니다
those are all the columns that we need in order to do the
29:26:25
다음 단계로 넘어가기 전에
next steps and now before we go and proceed with the aggregations
29:26:29
데이터 필터링에 대해 생각할 것입니다
what you're gonna do we're gonna think about filtering the data as i
29:26:32
주문 날짜가 null인 주문이 있습니다
recall we have some orders where the order date is
29:26:35
주문 날짜가 null이므로
null so i'm gonna go i remove those stuff so
29:26:38
주문 날짜가 null이 아닙니다
order date is not null so that means in
29:26:41
첫 번째 쿼리에서
the first query the base query not only i'm selecting the
29:26:44
보고서에 필요한 열을 선택하고
columns that i need for the reports also i'm defining
29:26:48
데이터 세트의 범위를 정의합니다
the scope of the data sets by filtering the data so you
29:26:51
여기서 범위를 1년으로 설정할 수 있습니다
can as well make the scope here only one year or something now
29:26:54
모든 열에 대해 생각해 볼 수 있습니다
what else we can do is to think about all those columns and
29:26:57
변환 작업을 수행할 수 있는지 여부
whether we can do any type of transformations in order to prepare
29:27:00
이들을 집계에 맞게 준비합니다
them for the aggregations like for example i'm gonna go and say you know what
29:27:03
이름과 성을 합칠 것입니다
instead of first and last name i'm gonna put them together in
29:27:07
고객 이름으로 만들 것입니다
one so it's gonna be the customer name it's better than having like
29:27:10
concat을 사용할 것입니다
two columns so let's go and do it we're gonna say concat
29:27:13
이름과 사이에 구분자를 두겠습니다
and then we can start with the first name and
29:27:17
마이너스나 공백을 사용할 수 있습니다
we can have a separator between them you can have like a minus or
29:27:20
구분 기호로 하얀 공간을 사용할 수 있습니다.
white space like this and after that the last
29:27:23
고객 이름이라고 부르겠습니다.
name so let's call it customer name and
29:27:27
그 두 열을 없앨 수 있습니다.
we can go and get rid of those two columns so let's go and
29:27:30
모든 데이터를 한 열에 넣을 수 있습니다.
execute and with that you have everything in one column now another thing
29:27:33
우리는 생년월일이 필요하지 않습니다.
that we can prepare that we don't need the birth
29:27:36
보고서에 필요한 나이 그룹입니다.
dates we actually need for our reports the age
29:27:40
나이를 계산해야 합니다.
groups so that means we have to go and calculate the age so let's
29:27:43
나이를 연도로 변환해야 합니다.
go and transform it so they live we want it
29:27:46
생년월일과 현재 날짜를 사용합니다.
in years the birth date and the current
29:27:49
모든 데이터를 확보했습니다.
date from system and we're going to call it age so let's
29:27:53
모든 데이터를 한 곳에 넣겠습니다.
execute again perfect so with that we have all the data that
29:27:56
도시라고 부르겠습니다.
we need for our reports let's go and put everything in one
29:27:59
이 도시의 모든 데이터를 넣겠습니다.
city so i'm going to call it with various query
29:28:02
도시를 완벽하게 만들겠습니다.
us and put everything in this city and i'm going to go and put this comment over here inside
29:28:09
기초부터 쿼리를 작성하겠습니다.
the city perfect and now we're gonna go and write
29:28:12
중간 결과를 기반으로 쿼리를 붙여넣겠습니다.
a query from the scratch based on
29:28:15
쿼리가 실행되었습니다.
our intermediate results so paste query it's
29:28:18
중요한 열이 있습니다.
executed all right so now by looking to our report with that we have
29:28:21
중간 결과에 대한 집계를 수행하겠습니다.
the important columns right so now in the next step
29:28:25
보고서에 필요한 모든 집계를 수행하겠습니다.
we're gonna do aggregations on top of these intermediate results
29:28:28
모듈화되고 읽기 쉽게 만들겠습니다.
so here we're gonna do all the aggregations that is needed for the reports and we're gonna put everything again in a city as an intermediate results which makes everything
29:28:37
이전에 준비한 결과에 대한 집계를 수행하겠습니다.
a modular and easy to read so now let's go and do
29:28:40
이것이 매우 중요합니다.
the necessary aggregations on the results that we have previously
29:28:43
보고서의 두 번째 단계입니다.
prepared so that's why this is very important as
29:28:46
집계를 위한 별도의 CTE를 만듭니다.
a second step in our reports always tend to make a
29:28:50
집계 전용으로 분리된 CTE이므로
separated cte only for aggregations so let's
29:28:53
이제 가서 모든 고객 정보를 다시 선택할 거예요.
go and do that i'm gonna go and select again all the customer informations like the customer key number age so i'm just gonna
29:29:01
복사해서 여기에 붙여넣고
copy and paste and put it over here and we just
29:29:04
열 이름이 필요해요.
need the column names so
29:29:07
키 번호, 이름, 나이를 이제
the key number name and age now after that
29:29:10
집계를 시작할 거예요. 예를 들어, 총 주문 수를 집계하고
we're gonna start doing aggregations so what do you want to aggregate is first for example the total number of orders so we're gonna go and count distinct order number
29:29:21
총 주문 수로, 이것은 하나의 집계입니다.
as total orders so this is one aggregation we can go and summarize all those sales amounts
29:29:29
총 판매량과
as total sales and
29:29:32
수량도 집계할 수 있어요.
the quantities as well so some quantity as
29:29:36
총 수량을 집계할 수 있고
total quantity and as well we can
29:29:39
고객이 몇 개의 제품을 주문했는지 세어볼 거예요.
go and count how many products did our customer
29:29:42
주문한 제품의 키를 총 제품으로
order so the products key as total products so what i'm doing now i'm just looking to our intermediate results and try to figure out what we can aggregate.
29:29:54
예를 들어, 나이를 집계하는 것은 의미가 없어요.
For example, it makes no sense to aggregate, for example, the ages, right?
29:29:57
주문 번호에서 총 주문 수를
So from the order number, we have total orders total
29:30:00
제품 판매 금액과 수량을 집계할 수 없어요.
product sales amount quantity and from the right side we cannot
29:30:04
고객의 세부 사항이기 때문이에요.
aggregate anything and that's because they are the details of their
29:30:07
사실 테이블에서 많은 집계를 할 수 있어요.
customers but from the fact table we can do a lot of aggregations
29:30:10
여기에서 주문 날짜로 할 수 있는 것은
so now what we can do with the order date over here we can for
29:30:13
고객의 마지막 주문 날짜를 찾는 것입니다.
example find the last order dates from our customer which is really nice information so we can say max order dates as last
29:30:23
주문 날짜와 수명을 계산할 수 있어요.
order and of course we can go and calculate the lifespan and
29:30:26
고객을 분류하기 위해 필요할 거예요.
that's we're gonna need it as you remember in order to categorize
29:30:30
이전 쿼리에서 고객의 첫 번째 주문과
our customer so i will just copy and paste it
29:30:33
마지막 주문 사이의 날짜 차이입니다.
from the previous query it is the date diff month between
29:30:36
고객의 첫 번째 주문과 마지막 주문입니다.
the first order from the customer and the last order
29:30:39
우리는 이것을 수명이라고 부릅니다.
of the customer so and we call this lifespan okay
29:30:42
그래서 우리는 두 가지 측정값 또는 집계를 도출했습니다.
so we derived two measures or aggregations
29:30:45
주문 날짜에서 이제 우리는 모든 것을 다 했다고 생각합니다.
from the order date now i think we have done everything
29:30:49
가능하고 물론 부족한 것은 그룹을 갖는 것입니다.
possible and what is missing of course is to have a group
29:30:52
우리가 집계를 수행하고 그룹화하고 있기 때문에
by because we are doing aggregations and we are grouping by
29:30:56
고객 세부정보에 따라 고객이 될 것입니다.
either customer details so gonna be customer
29:30:59
주요 고객 번호, 이름 및 나이가 될 것입니다.
key customer number name and age so
29:31:02
우리의 집계를 위한 모든 것을 갖고 있다고 생각합니다.
i think we have everything for our aggregations let's
29:31:05
모든 고객의 목록을 실행하고
go and execute it a list of all customers and
29:31:09
고객에 대한 몇 가지 세부정보가 있으며 이제 많은 측정값이 있습니다.
we have few details about the customers and now we have a lot of measures so the total order total sales total
29:31:15
총 주문, 총 판매, 총 수량, 제품, 마지막 주문과
quantity products the last order and the
29:31:18
수명과 함께 우리는 이 부분을 다뤘습니다.
lifespan and with that we have covered this part
29:31:21
여기에서 우리는 집계를 제공했습니다.
over here where we have provided aggregations on
29:31:24
고객 수준에서 세부정보를 가지고 있습니다.
the customer level so we have the details and we have
29:31:27
모든 준비가 완료되었습니다.
the aggregations all right so with that we have now all the preparations
29:31:30
최종 결과를 구축하는 데 필요한 것입니다.
that is required to build the final
29:31:33
시나리오에 따라 다릅니다.
results so you really depend on the scenario if it's
29:31:37
가능하다면 모든 데이터를 하나의 CTE에서 가져올 수 있습니다.
possible we can take all the data from one cte or if it's
29:31:40
필요하다면 여러 도시에서 가져올 수 있습니다.
needed we can get it from multiple cities but in our scenario we're
29:31:43
우리는 두 번째 도시에서 가져올 것입니다.
going to take it from the second city the aggregations and we're going to prepare
29:31:46
최종 결과를 위해 모든 것을 모을 것입니다.
the final results so here we're going to bring everything together
29:31:49
보고서에 필요한 최종 변환을 도입할 수 있습니다.
and we might introduce final transformations that
29:31:53
이제 최종 결과를 위해 쿼리를 작성하겠습니다.
is needed for the reports so let's go and write the query for
29:31:56
고객을 세분화하고 QPIs를 생성할 수 있습니다.
the final results now we can go and start segmenting
29:31:59
이제 이러한 결과를 기반으로 최종 쿼리를 작성하겠습니다.
our customer and as well creating the qpis so let's go to the third step i'm gonna go and put this in a city so let's call it customer aggregation
29:32:11
항상 코멘트를 추가하는 것을 좋아합니다.
and now based on these results we will write the final
29:32:14
쿼리에 대해 항상 코멘트를 남기고 싶습니다.
query so i like always to put a comment about
29:32:17
첫 번째 도시는 기본 쿼리입니다.
the steps so the first city is the base query where
29:32:21
데이터를 결합하고 준비했습니다.
we just joined the data and prepared it and then the second query
29:32:24
집계에 대한 쿼리입니다.
is for the aggregations and the final one is for
29:32:27
최종 결과를 작성해 보겠습니다.
the final results so let's go and start writing our final
29:32:30
고객 정보 목록을 다시 나열할 것입니다.
query we will start with select and i'm gonna go and list again all the customer information so i'm gonna go and get again same things we have
29:32:39
고객 키, 고객 번호, 이름, 나이 등입니다.
customer key customer number name age and so on
29:32:42
이제 나이 범주를 만들어야 합니다.
and now after that we need to create the age categories
29:32:45
모든 측정값을 가져오겠습니다.
and now after that i'm gonna go and get all those measures as well from our query but of course without the calculations i just need the names of it
29:32:58
고객 집계입니다.
so with that we have everything from our previous cte
29:33:01
이제 모든 것이 작동하는지 테스트해 보겠습니다.
so the customer aggregation okay so let's
29:33:04
몇 가지 카테고리를 만들어야 합니다.
just test it now everything is working so now what we have to do
29:33:07
고객 세분화의 세그먼트도 만들어야 합니다.
we have to create a few categories age category and
29:33:10
쿼리를 이미 작성했습니다.
as well the segments of the customers rights for segmenting the customers we
29:33:14
이전 분석에서 복사하여 붙여넣겠습니다.
have already done the query so i will just copy and paste it from
29:33:17
수명이 최소 12개월 이상이고 매출이 5000 이상입니다.
the previous analysis it looks like this if the lifespan
29:33:20
VIP 고객입니다.
is at least like 12 months and the sales above 5000
29:33:23
그렇지 않으면 신규 고객입니다.
then a vip if it's less or equal 5000 than
29:33:27
첫 번째 세그먼트입니다.
regular otherwise it is a new customer so this is
29:33:30
두 번째 세그먼트를 구축할 것입니다.
our first segment but the second segment about the ages we're gonna go and build it now and again how we can do it case when so if the age for example less than 20 then the customer is under 20.
29:33:41
두 번째 범위를 만들겠습니다.
let's make another range where we say if the customer age is between 20 and let's say 29 then
29:33:52
두 번째 범위에 대해 반복할 수 있습니다.
we have the second range and we can keep repeating the same
29:33:55
몇 개의 카테고리를 만들고 싶습니다.
thing for the second one it really depends how many categories
29:33:58
30대와 39대입니다.
you want to build so 30 and 39
29:34:02
이 그룹에 속합니다.
i belong to this group now the next
29:34:05
하나, 40대도 포함합시다. 맞죠? 그래서 40
one let's have the 40s as well right so 40
29:34:08
49, 여기서도 같은 일이 일어나고 있습니다.
49 same thing over here and now else
29:34:12
50세 이상으로 가정해 봅시다. 그래서 연령대별로 정리하고 싶습니다.
let's say 50 and above right and above so let's go and end it as age group i just want to sort it a little bit like this
29:34:23
좋아요, 이제 보기 좋습니다. 그래서 다시
okay now it looks nice so with that again we have turned a
29:34:26
측정을 차원으로 바꾸고 이제
measure into the dimension and let's go and
29:34:29
실행합시다. 이제 결과를 확인하면
execute it now so now by checking the results we have the details
29:34:33
고객의 세부정보가 나옵니다. 이제 새로운 카테고리가 생겼습니다.
of the customers and now we have a new category so
29:34:36
보시다시피 54가 작동하고 있습니다. 50세 이상입니다.
as you can see it is working 54 it is above 50
29:34:39
이것은 40대와 49세 사이의 범위입니다. 67이 50세 이상입니다. 20세 이하의 고객은 없다고 생각합니다.
this is in the range between 40 and 49 we have here 67 above 50 i believe we don't have any customer that is below 20 right or even between 20 and 30.
29:34:50
좋아요, 그래서 우리는 두 개의 카테고리를 만들었습니다.
Okay, so with that, we have created our two categories.
29:34:54
보고서를 보면 고객을 VIP 카테고리로 세분화할 수 있습니다.
And by looking to the reports, you see, we can segment the customers now into categories that VIP
29:35:00
정기, 신규 및 연령대와 함께 우리는
regular new and the age group and with that we have covered
29:35:03
이 세 가지 요구 사항을 모두 충족했습니다. 이제 마지막
all those three requirements and we come now to the last
29:35:06
요구 사항은 다음 KPI를 계산해야 합니다. 첫 번째
requirements we have to calculate the following kpis now the first
29:35:09
하나는 간단합니다. 최근성, 마지막 주문 이후 몇 개월이 지났는지
one it is an easy one it is the recency how many months
29:35:13
우리가 여기서 계산한 마지막 주문입니다.
since the last order we have calculated over here the
29:35:16
고객의 마지막 주문입니다. 이제
last order for the customer it is this one and now
29:35:19
최근성을 찾는 것은 매우 간단합니다. 우리가 해야 할 일은
in order to find the recency it is very simple so all we have to do
29:35:22
여기서 이 값을 가져오는 것입니다. 아마도
is to take this over here i will just put it maybe after
29:35:25
세분화 이후에 넣을 것입니다. 그리고 해야 할 일은 날짜를 사용하는 것입니다.
the segmentation and all what you have to do is to use the date
29:35:28
일반적으로 날짜 차이를 계산하는 것입니다.
diff as usual so month is the last
29:35:31
주문 날짜와 얻은 날짜입니다. 그래서
order date and the get date so as
29:35:34
우리는 많은 분석에서 이 설정을 사용하고 있습니다.
you can see we are using this setup like in many analyzes
29:35:38
우리는 항상 날짜 간의 차이를 찾습니다.
right we always find the differences between a date from
29:35:41
우리 데이터 세트와 현재 날짜 및 시간 간의 차이를 찾습니다.
our data sets and the current date and time and with that
29:35:44
최신성을 가져오겠습니다 그래서
we will get the recency so let's
29:35:47
지금 실행해 보겠습니다. 고객의 마지막 주문 이후 몇 개월이 지났는지 볼 수 있습니다.
go and execute it now you can see how many months since
29:35:50
고객의 마지막 주문 이후 몇 개월이 지났는지 볼 수 있습니다. 물론
the last order order of the customer and of course you can go
29:35:53
마지막 주문 날짜를 사용하여 테스트해 보세요. 이는 정말 중요합니다.
and test it using the last order dates and this is really important in
29:35:57
고객이 여전히 활성 상태인지 이해하기 위해서입니다.
order to understand whether the customer is still active or
29:36:00
비활성 상태입니다. 이제 첫 번째 쉬운 KPI에 대해 이야기하겠습니다.
inactive okay so this is for the first easy kpi now
29:36:03
두 번째 KPI로 넘어가겠습니다. 평균 주문 가치를 계산하라고 합니다.
let's go to the second one it says calculate the average order value
29:36:07
이걸 어떻게 할까요? 여기로 돌아가 보겠습니다.
so how we gonna do this let's go back over here
29:36:10
평균 주문 가치를 계산하기 위해 총 매출을 총 주문 수로 나누어야 합니다. 고객이
now in order to compute the average order value we have to divide the total sales by the total orders so how many revenue did the customer
29:36:19
생성한 수익을 총 주문 수로 나누고
generate and we divide by the total number of orders
29:36:22
그 후 평균을 찾아야 합니다. 아주 간단합니다.
and after that we have to find the average so it is very simple
29:36:25
그걸 작성하러 가겠습니다. 테이블의 끝으로 가겠습니다.
let's go and write that we're going to go to the end of our table where
29:36:28
여기서 KPI를 설정할 것이고 평균 주문 가치를 계산하겠습니다.
we're going to put our kpi and i'm going to say here compute average
29:36:32
총 매출을 총 주문 수로 나누고 평균 주문 가치를 부르겠습니다.
order value so as a shortcut avo so
29:36:36
이걸 실행해 보겠습니다. 마지막으로 가면
we say total sales divided by total orders and let's call it average order value so let's go and
29:36:45
고객의 평균 주문 가치를 볼 수 있습니다. 하지만 이제
execute it and if you go to the last over here you can see
29:36:48
숫자를 나누고 있을 때 주의해야 합니다. 0으로 나누지 않도록
the average order value of our customers but now
29:36:51
그렇지 않으면 오류가 발생합니다. 고객이
if you are dividing numbers together you have to be careful that you are not dividing
29:36:54
주문을 하지 않은 경우 0일 수 있습니다.
by zero otherwise you will get an error so imagine that a
29:36:57
오류가 발생할 수 있습니다. 하지만 우리 시나리오에서는 그런 일이 없습니다.
customer has zero they didn't order anything you
29:37:01
주문 테이블 또는 사실 테이블에서 시작하고 있기 때문입니다. 하지만 이 일이 발생하지 않도록
might get an error in our scenario we don't have that because we
29:37:04
확실히 하고 싶습니다. 그래서 보통
are starting from the order table or the fact table but still i like to make sure this never happens and for that i usually go
29:37:10
case when 문을 사용합니다. 아주 간단합니다. 만약
i use the case when statements very simple one if the
29:37:13
총 주문 수가 0이면
total orders is equal to zero then make
29:37:16
0으로 만들고, 그렇지 않으면 계산을 수행합니다.
it zero otherwise do the calculation that
29:37:19
우리가 이야기한 대로 이렇게 하고
we talked about so like this and at
29:37:22
마지막에 끝을 추가할 것입니다. 그래서 그게 전부입니다.
the end we will add an end so that's it and
29:37:26
그렇게 해서 우리는 절대 0으로 나누지 않을 것입니다.
with that i make sure we will never divide by zero so
29:37:29
그게 전부입니다. 간단했죠? 마지막 KPI인 평균 월 지출로 가봅시다.
that's it it was simple right let's go to the last kpi the average monthly spend so how we will calculate that compute
29:37:39
평균 월 지출이므로 이제
average monthly spend so now since
29:37:42
우리는 지출에 대해 이야기하고 있으므로
we are speaking about the spending that means we need the
29:37:46
총 매출이 필요합니다. 고객이 얼마나 판매했는지
total sales right so how much sales did the customer
29:37:49
총 매출을 생성하고 그 다음에
generate totally and then we divide it by
29:37:52
개월 수로 나누면 평균을 얻을 수 있습니다.
the number of months and with that we will get the average
29:37:55
평균 월 지출이므로 총 매출을 수명으로 나눌 수 있습니다.
monthly spend right so that means we can divide the total sales by the lifespan as we calculated it is the period where the customer has
29:38:04
고객이 시작부터 끝까지 활동해왔습니다. 이제
been active from the starts until the end okay so now let's
29:38:07
단계별로 진행해 보겠습니다. 먼저 주의해야 합니다.
do it step by step first we have to be careful that we are
29:38:10
0으로 나누지 않도록 하고, 수명에 대해
not dividing by zero and i believe in the lifespan we have
29:38:13
우리는 0이 있습니다. 그래서 우리가 말할 것은
zeros so what we're gonna say as usual case when lifespan
29:38:17
수명이 0일 때 이 경우
is equal to zero then this
29:38:20
고객이 단지 한 달만 존재하므로
time we'll not make it zero the customer exists only for
29:38:23
고객의 총 매출을 가져올 수 있습니다. 평균을 찾기 위해
one month so what we can do we can get the total sales of the customer and we don't have to divide it by the month in order to find the average because the
29:38:30
개월로 나누지 않아도 됩니다. 평균은 현재 총 매출과 같습니다.
average is equal to the current total sales so
29:38:34
그렇게 해서 우리는 0으로 나누지 않도록 합니다.
with that we make sure we are not dividing by zero otherwise we're
29:38:37
그렇지 않으면 계산이 잘못될 것입니다. 총 매출을
gonna have our calculation so total sales divided
29:38:41
수명으로 나누면 총 매출이
by life span so the total sale divided
29:38:44
개월로 나누어 평균 월 지출을 얻습니다.
by the months and with that we will get the average monthly
29:38:47
그래서 우리는 평균 월 지출이라고 부를 것입니다.
spend so and and us and we're
29:38:51
완벽하니, 가서 시도해 봅시다.
gonna call it average monthly spend perfect so let's go and try that out let's go to the right
29:38:57
측면으로 가면 세 번째 KPI가 있습니다.
side and with that we have our third kpi and we have
29:39:00
평균 월 지출과 함께 여러분은
the average monthly spends and with that guys we
29:39:04
이제 고객에 대한 전체 보고서를 가지고 있습니다.
have now full reports about the customers and we
29:39:07
모든 요구 사항을 충족했습니다. 자, 이제
have covered all the requirements all right so with that we have
29:39:10
최종 결과를 가지고 있으며 요구 사항을 충족했습니다.
the final results and we have fulfilled the requirements so
29:39:13
우리가 할 일은 전체 쿼리를 가져와서
what we're gonna do we're gonna take the whole query and put it in
29:39:16
데이터베이스에 뷰로 넣는 것입니다. 뷰가 있으면
the database as a view and once we have the view the report in the database we can share it with the others now the other data analysts in the team
29:39:24
보고서를 데이터베이스에 공유할 수 있습니다. 이제 팀의 다른 데이터 분석가들이
can go and maybe create a dashboard in order to visual
29:39:27
대시보드를 만들어 데이터를 시각화할 수 있습니다.
the data using a bi tool like tableau or power bi
29:39:30
하지만 이 시나리오에서는 사용자가
but in this scenario the user gonna go and connect your
29:39:33
대시보드에 마지막으로 준비된 데이터를 연결할 것입니다.
review the last prepared data to the dashboard and
29:39:36
이렇게 하면 사용자가 시각화를 위해 데이터를 준비하는 데
with that the user can quickly generate insights without doing
29:39:39
많은 단계를 거치지 않고도 빠르게 통찰력을 생성할 수 있습니다.
a lot of steps in order to prepare the data for the visualizations
29:39:43
물론 데이터 분석가는 차원과 사실을 연결할 수 있지만, 이 하나의 확실한 뷰가
and of course the data analyst can go and connect the dimensions and facts but having this one solid view is going to be like way easier to consume
29:39:51
소비하기 훨씬 더 쉬울 것입니다.
And of course, the data analyst can as well write a query on top of your view in order to generate a quick insights.
29:39:57
물론 데이터 분석가는 뷰 위에 쿼리를 작성하여
So as you can see, using only SQL, you are covering
29:40:00
빠른 통찰력을 생성할 수 있습니다.
of complex steps in order to make the data ready
29:40:03
그러므로 보시다시피, SQL만 사용하여
for reporting and analyzes and this is what usually happened
29:40:07
복잡한 단계를 처리하고 데이터를 준비하고 있습니다.
in real projects we're gonna go and put the query
29:40:10
보고 및 분석을 위한 데이터 준비를 위해
in the database so that the others can use it so what
29:40:13
실제 프로젝트에서는 쿼리를
we're gonna do very simple create review and we're
29:40:16
데이터베이스에 넣어 다른 사람들이 사용할 수 있도록 할 것입니다.
gonna put it in a gold layer and we're gonna call it report underscore customers
29:40:20
우리가 할 일은 매우 간단하게 리뷰를 생성하는 것입니다.
then ask like this and let's go and execute it it is successful now if you go to our database and check the views you will find a new view called
29:40:29
그런 다음 금 레이어에 넣고 report_customers라고 부를 것입니다.
gold report customers now all what you have to do is to go and have a simple select so gold reports
29:40:37
이렇게 요청하고 실행해 보세요. 성공적입니다.
customers and you will get an amazing report
29:40:40
이제 데이터베이스로 가서 뷰를 확인하면 새로운 뷰가 있습니다.
about the customers this kind of reporting it
29:40:43
고객에 대한 이러한 보고는
is very important because you are giving a full picture 360
29:40:47
매우 중요합니다. 전체 그림을 제공하므로
degree view of all your customers so you have details
29:40:50
모든 고객에 대한 360도 뷰를 제공하므로
categories measures everything in one go and it's gonna make
29:40:53
모든 것을 한 번에 측정하고
life easier now for any user of this view to
29:40:56
고객에게 도움이 될 수 있는 이 뷰에서
quickly understand the data and generate maybe insights based
29:40:59
사용자가 보고서를 사용할 때
in this one view that can help of course your customers so
29:41:02
SQL에서 또는 파워와 연결할 수 있습니다.
i just want to show you now what this means if a user using your reports
29:41:06
피 또는 태블로에 연결하여
so either in sql or maybe they're gonna go and connect it to a power
29:41:09
즉시 인사이트를 생성할 수 있습니다.
pi or tableau they can generate immediately insights so
29:41:12
예를 들어 고객 수를 세어보면
for example they go and say count customer number so
29:41:17
총 고객 수로, 그리고
as total customers and then they're gonna go and take any dimension for example the age group
29:41:24
그들은 어떤 차원도 선택할 수 있습니다.
so something like this and then
29:41:27
예를 들어 연령대별로
go by the age group we'll just put it here
29:41:30
먼저 연령대별로
first and then they're gonna go and add any other measure
29:41:33
총 매출과
for example the total sales and
29:41:38
이 뷰에서 다른 측정값을 추가합니다.
another measure that you have in this view and then execute and
29:41:41
그들은 자신의 사실과 차원으로 가는
quickly they can do analysis on top of your view without
29:41:44
것 없이 분석을 빠르게 수행할 수 있습니다.
having them to go to their fact and dimensions so
29:41:48
이것은 데이터 모델의 추가 준비된 레이어입니다.
this is like one extra prepared layer the data model that
29:41:51
당신이 구축한 것이고, 연령별로 그룹화하고 싶지 않다면
you have built and if you don't want to group it by the ages
29:41:54
고객 세그먼트를 가질 수 있습니다.
you can go and have the customer segments and it will
29:41:57
그들은 빠르게 분석할 수 있습니다.
be working so quickly they can analyze the new derived informations that you have prepared in your reports so guys this is amazing reports about the customers
29:42:12
이제 여러분이 할 일은
and now what you're gonna do you're gonna go and prepare the
29:42:15
두 번째 보고서를 준비하는 것입니다.
second reports where you have to build complete insights
29:42:18
비즈니스 제품에 대한 완전한 인사이트를 구축해야 합니다.
about the products of the business it is very similar
29:42:21
고객에게 매우 유사한 비즈니스 제품에 대한
to the customers so we want to generate a report for the
29:42:25
제품에 대한 보고서를 생성하려고 하므로 제품 이름, 카테고리와 같은 세부정보를 제공해야 합니다.
products you have to provide details like the product name category
29:42:28
하위 카테고리와 비용을 기준으로 제품을 세분화해야 합니다.
subcategory and the costs you have to segment the products
29:42:31
수익에 따라 높은, 중간 및 낮은 카테고리를 가질 수 있습니다.
by the revenue so you can have categories like high medium
29:42:34
그리고 기본 집계를 제공해야 합니다.
and low and then you have to provide the basic aggregations
29:42:37
제품 수준에서 몇 가지 KPI를 계산해야 합니다.
at the level of the products and then calculate few kpis
29:42:41
고객에게 매우 유사하다는 것을 알 수 있습니다.
so as you can see it is very similar to the customers and
29:42:44
이제 해야 할 일은 비디오를 일시 중지하고 고객에서 동일한 단계를 따라야 합니다.
now what you have to do you have to pause the video follow the same step at the customers where we join the tables create aggregations and put everything like in ctes
29:42:54
제품에 대한 보고서를 가진 뷰를 생성해야 합니다.
and at the end once you are done create the view where you have the report about the products so i'm gonna go now and do it offline and i will see you soon
29:43:07
보고서가 완료되었기를 바랍니다.
okay my friends i hope you are done with the reports i'm gonna
29:43:10
어떻게 했는지 빠르게 보여드리겠습니다.
show you quickly how i've done it so i've just created a new view called
29:43:14
보고서 제품이라는 새 뷰를 만들었습니다.
report products and then we start with the base query where we have joined the fact table with the dimension products and collected all the columns
29:43:22
기본 쿼리에서 사실 테이블과 차원 제품을 조인했습니다.
that we need for the reports and we put everything in
29:43:25
보고서에 필요한 모든 열을 수집했습니다.
the first city so this is the first step and there was
29:43:28
첫 번째 도시에서 모든 것을 넣었습니다.
from my side no need for any transformations over here
29:43:32
여기서는 변환이 필요하지 않습니다.
so we go now to the second step and here we have to
29:43:35
이제 두 번째 단계로 넘어가겠습니다.
put all the different types of aggregations in one go so
29:43:38
모든 다양한 유형의 집계를 한 번에 넣어야 합니다.
we calculate the lifespan the last sales order total
29:43:41
우리는 수명과 마지막 판매 주문 총액을 계산합니다.
orders total customers sales quantity and as well
29:43:44
주문 총액, 고객 수, 판매 수량도 계산합니다.
i have created the average selling price of the
29:43:47
평균 판매 가격을 생성했습니다.
products it is very simple we are dividing the sales amount
29:43:51
판매 금액을 수량으로 나누고 있습니다.
by the quantity so this is the basic aggregations
29:43:54
기본 집계에 대한 것입니다.
about the products and finally we have the final query
29:43:57
제품에 대한 최종 쿼리가 있습니다.
so we start with selecting the basic informations about the
29:44:00
기본 정보를 선택하는 것으로 시작합니다.
products so we have the key name category and then we have
29:44:03
여기 최근성과 우리의 새로운 세그먼트가 있습니다.
here the recency and we have our new segments this
29:44:06
이것은 제품에 대해 매우 간단합니다.
one is very easy for the products so we are seeing if the total sales
29:44:09
총 판매량이 50,000 이상이면 이것은
is higher than 50 000 then this is a
29:44:12
높은 성과를 내는 제품이며 50과 10,000 사이이면
high performer and if it's like between 50 and 10k
29:44:16
중간 범주로, 그렇지 않으면 낮은 성과입니다.
then this is a mid-range otherwise it is low
29:44:19
그래서 제품의 세분화는 매우 간단합니다.
performer so the segmentations of the products is very simple
29:44:22
그 후 우리는 모든 측정값을 집계했습니다.
and after that we have like all our measures that
29:44:26
이제 두 가지 KPI로 넘어가겠습니다.
we aggregated in the cte and now we come to the two
29:44:29
첫 번째는 평균 주문 수익으로, 판매를 총 주문 수로 나누는 것입니다.
kpis it is very similar to the customers so the first one the average order revenue it is simply dividing the sales by the total orders and you have to take care of the
29:44:38
물론 제로를 주의해야 하고, 평균 월 수익은
zeros of course and the average monthly revenue we
29:44:41
총 판매를 제품의 수명으로 나누는 것입니다.
divide the total sales by the lifespan of the products
29:44:44
물론 수명이 제로이면 한 달 동안만
and of course if the lifespan is zero so it is only
29:44:47
총 판매량이 되며, 이를 통해
one month then it is the total sales and with that you generate
29:44:50
평균 월 수익을 생성합니다. 보시다시피 매우
the average monthly revenue so as you can see it is very
29:44:53
고객과 유사하지만 여전히 여기에 초점이 있습니다.
similar to the customers but still the focus here is the
29:44:56
제품입니다. 이제 이 쿼리를 뷰에 넣습니다.
products now of course we put this query in view so
29:45:00
우리는 제품 보고서를 나란히 가지고 있습니다.
we have the report products side by side by
29:45:03
고객 보고서와 함께 정말 놀라운 보고서가 있습니다.
the report customers and now we have really amazing report
29:45:06
제품에 대한 모든 것이 있으며, 많은 세부 정보가 있습니다.
about the products where we have everything so we have a lot of details
29:45:09
고객에 대한 세부 정보도 있으며, 우리는
about the customers we have as well a dimension in
29:45:12
제품을 세분화하기 위한 차원이 있습니다.
order to segment our products and we have a
29:45:15
각 제품에 대해 정말 중요한 많은 측정값이 있습니다.
lot of measures that are really important about each
29:45:18
총 주문 수, 판매량, 고객 수를 포함합니다.
product so we have the total number of orders sales how many customers
29:45:22
제품을 주문한 고객 수, 평균 가격, 평균 수익
did order the products the average price the average revenue
29:45:25
및 월 평균 수익이 있으며, 이는 각 제품에 대한 깊은 통찰력을 제공합니다.
and the monthly average revenue and this gives you really deep insights about each product of your business and of course
29:45:32
제품을 올바르게 비교하는 데 매우 유용합니다.
this is very helpful in order to compare the products right and
29:45:35
물론 이것은 당신이 필요로 할 핵심 분석입니다.
now of course this is core analysis that you're gonna need it
29:45:38
우리의 두 가지 놀라운 보고서에 대해 이제 생각해 보겠습니다.
a lot in your business that's why we offer it as a view
29:45:41
모든 데이터
so i think we have now two amazing reports about our
29:45:44
모든 데이터
data all
29:45:49
좋아요, 친구들, 이제 모든 작업을 넣는 것을 잊지 마세요.
right my friends so now don't forget to put all your work in
29:45:52
다른 사람들과 공유하기 위해 git 저장소에
the git repository in order to share it with the others as
29:45:55
성공적인 프로젝트를 위해, 그래서 평소처럼 데이터 세트가 있습니다.
successful projects so as usual we have the data sets
29:45:58
주석과 여러분이 수행한 스크립트도 있습니다.
the commentations and as well the scripts that you have done
29:46:01
이 프로젝트를 통해 모든 것을 함께 모으고 있습니다.
through these projects and here i'm putting everything together so
29:46:05
탐색의 모든 활동과 함께
we have all the activity of the exploration as well with
29:46:08
우리가 수행한 고급 분석의 변화도 있습니다.
the advanced analysis that we have done so we have the change of
29:46:11
우리의 시간, 누적 분석 성과 데이터 세분화
our time the cumulative analysis performance data segmentations
29:46:15
부분 대 전체 분석과 두 개의 새로운 보고서도 있습니다. 아직 하지 않았다면 지금 저장소를 만들고 모든 작업을 거기에 넣어 모든 사람이 여러분의 작업에 접근하고 볼 수 있도록 하세요.
part to whole analyzes and as well our two new reports so i recommend you if you haven't done that yet go and create now a repository, put all your work there to make sure that everyone can access and see your work.
29:46:26
그리고 친구들, 코드에 멋진 주석을 추가하는 것을 잊지 마세요. 코드의 형식과 스타일은 완벽해야 합니다.
And my friends, don't forget to add nice commenting on your code and formatting and styling your code should be perfect.
29:46:34
아직 하지 않았다면 지금 가서 하세요. 알겠죠, 친구들? 그래서 그렇게 해서 우리는 로드맵의 마지막 단계를 완료했습니다.
So if you haven't done that yet, go and do it now. All right, my friends. So with that, we have done the last step in our roadmap.
29:46:40
우리는 사용자에게 두 개의 확실한 보고서를 만들었습니다. 그리고 그렇게 해서 우리는 고급 분석 프로젝트의 모든 단계를 완료했습니다.
We have created two solid reporting for our users. And with that, we have completed all the steps of our advanced analytics projects.
29:46:47
이 프로젝트와 이전 프로젝트를 통해 SQL을 사용하여 데이터 세트에 대한 데이터 분석을 수행하는 전체 그림을 이제 볼 수 있습니다.
And with this project and the previous projects, you can see now the full picture on how to do data analytics on any data sets using SQL.
29:46:55
첫 번째 단계에서 데이터베이스를 탐색하고 모든 것을 하나의 보기로 통합한 매우 확실한 보고서를 얻는 것으로 시작합니다.
So starting by the first step where we have explored the database and end up having a very solid reports where we have consolidated everything in one view.
29:47:04
그리고 그렇게 해서 우리는 비즈니스와 데이터에 대해 정말 잘 이해하게 되었습니다.
And with that, we have now really great understanding about the business, about our data.
29:47:09
이제 여러분이 할 수 있는 것은 인터넷에서 어떤 데이터 세트를 가져가고 이 모든 단계를 다시 거치는 것입니다.
And now what you can do, you can go and grab any data sets in the internet and you can go through all these phases again.
29:47:14
그리고 약속합니다, 마지막에는 비즈니스에 대한 전체 그림과 이해를 갖게 될 것입니다.
And I promise you at the end, you will have a full picture and understanding of the business.
29:47:19
이것이 제가 각 프로젝트에서 어떤 유형의 데이터 세트를 이해하고 싶을 때 정확히 하는 것입니다.
And this is what I exactly do in each project if I want to understand any type of data sets.
29:47:24
좋아요, 친구들, 그렇게 해서 우리는 SQL 프로젝트의 마지막 유형인 고급 데이터 분석을 다뤘습니다.
All right, my friends, with that, we have covered the last type of SQL project, the advanced data analytics.
29:47:30
그리고 그렇게 해서 이제 SQL을 사용하여 세 개의 확실한 프로젝트가 있습니다. 이들은 산업의 실제 프로젝트와 매우 유사합니다.
And with that, you have now three solid projects using SQL. And they are very similar to real world projects in the industry.
29:47:37
특히 데이터 엔지니어 또는 데이터 분석가가 되고 싶다면
especially if you want to be a data engineer or a data analyst and
29:47:40
친구들, 우리는 이제 과정의 마지막 장을 다뤘습니다
my friends we have covered the last chapter in our course
29:47:43
그래서 이것은 SQL의 고급 수준이며, 그것들은
so this is the advanced level in sql and those are
29:47:47
여러분이 수강할 수 있도록 제가 설계한 모든 장입니다
all the chapters that i have designed for you to take
29:47:50
기초에서 중급, 그리고 고급으로 나아갑니다
you from the basics to intermediate and then to the advanced
29:47:53
주제들, 친구들, 축하합니다, 정말 자랑스러워해야 합니다
topics my friend you made it congrats you should
29:47:56
여러분은 정말 자랑스러워해야 하며, 이제 저는 SQL에 대해 제가 아는 모든 것을 공유했다고 말할 수 있습니다
be really proud of yourself and now with that i can say that i have shared everything that i know about sql and you can now solve any complex task using SQL like I do in my real projects.
29:48:07
여행을 즐기셨기를 바랍니다. 만약 그렇다면, 더 많은 무료 강의를 원하신다면
And I hope that you have enjoyed the journey. And if you do, and you want me to create more free courses like this, make sure to support the channel by subscribing, liking, and commenting.
29:48:16
이것은 물론 그 채널이 성장하고 다른 사람들에게 도달하게 하며, 저에게도 더 많은 콘텐츠를 만들도록 동기를 부여합니다
This of course can make that channel grow, reach the others, and as well motivates me to make more content like this.
29:48:22
더 이상 할 말이 없습니다. 시청해 주셔서 감사합니다, 다음 강의에서 뵙겠습니다. 안녕.
So nothing left to say. Thank you so much for watching, and I will see you in the next course. Bye.
Get synced captions in Chrome Add to Chrome