본문 바로가기
테크 큐레이터

[PostgreSQL] 기본 문법 구문 총정리 | SELECT, FROM, WHERE, ORDER BY, ALTER TABLE, HAVING | 컬럼 기본 조회, Join, 데이터 타입 변경, 조건 삽입, 내림차순 조회, DB 확인, 스키마 Schema 확인

by 동글네모 2020. 12. 2.
728x90
반응형

PostgreSQL

구글 데이터베이스, 구글 클라우드 데이터베이스, 무료 클라우드 데이터베이스 등 사용해서 데이터 끌어오는 분들 많으시죠? 보통 Data Analyst나 Data Scientist 등 직무로 취업을 희망하시는 분들 또한 PostgreSQL, MySQL 등 학습이 많이 필요하실겁니다. 그런 분들께 조금이나마 도움이 되고자 정리해보았습니다.

 

✦ 여러가지 데이터를 바탕으로 작성한 PostgreSQL 구문이므로, 분석하고자 하는 파일의 '테이블', '컬럼' 등에 맞게 구문 활용하시면 됩니다.


#PostgreSQL DB | 데이터베이스 확인
select * from pg_catalog.pg_namespace;

#PostgreSQL schema | 스키마 확인
select * from pg_catalog.pg_tables;

#PostgreSQL DB, schema | 특정 스키마, 데이터베이스 조회
SELECT *
FROM pg_catalog.pg_tables
WHERE
schemaname = 'public'
AND tablename LIKE 'Weath%';


#PostgreSQL diagram Visualization | 우클릭으로 Diagram Visualization 확인 (DATAGRIP)

#PostgreSQL table | 테이블명 변경
alter table "1.book2" rename to book;
alter table "3.user2" rename to "user";

#PostgreSQL column | 컬럼명 변경
alter table book rename column c1 to Book_id;
alter table book rename column c2 to Title;
alter table book rename column c3 to isbn;
alter table book rename column c4 to 분야_1;
alter table book rename column c8 to 저자;

#PostgreSQL column | 컬럼 선택
SELECT c1,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10
FROM "Weather";

#PostgreSQL select, from, order by | 내림 차순 desc
SELECT "Weather".c8, "Weather".c2
FROM "Weather"
ORDER BY "Weather".c8 DESC;


#PostgreSQL Data type | 데이터 타입 변경 numeric 실수형으로
ALTER TABLE "Weather" ALTER COLUMN c8 TYPE NUMERIC USING c8::NUMERIC;
ALTER TABLE "Weather" ALTER COLUMN c6 TYPE NUMERIC USING c6::NUMERIC;
ALTER TABLE "Weather" ALTER COLUMN c5 TYPE NUMERIC USING c5::NUMERIC;

#조건 내림 차순
SELECT "Weather".c8, "Weather".c2, "Weather".c3
FROM "Weather"
WHERE "Weather".c2 IN ('Seoul', 'Busan')
And "Weather".c8 > 3
ORDER BY "Weather".c8 DESC;

 

#JOIN
select "Weather".*
FROM "Weather", "TimeProvince"
WHERE ("Weather".c3="TimeProvince".c1) and ("Weather".c2="TimeProvince".c3);


#max-min 컬럼 파생
SELECT "Weather".c6, "Weather".c5, "Weather".c6-"Weather".c5 As Weather_gap
FROM "Weather", "TimeProvince";

#특정 값 횟수 조회
SELECT "Weather".c3, count(1) as Freq
FROM "Weather"
GROUP BY "Weather".c3
ORDER BY "Weather".c3 DESC;

#다수 특정 값 횟수 조회
SELECT "Weather".c3, "Weather".c2,
count(1) as Freq
FROM "Weather"
GROUP BY "Weather".c3, "Weather".c2
ORDER BY "Weather".c3 DESC;


#PostgreSQL join | JOIN 후 (max-min) 파생
select "Weather".*, "Weather".c6-"Weather".c5 As Weather_gap
FROM "Weather", "TimeProvince"
WHERE ("Weather".c3="TimeProvince".c1) and ("Weather".c2="TimeProvince".c3);

#PostgreSQL groupby | Join 후 평균 온도
select "Weather".c2, "Weather".c3, SUM("Weather".c6 - "Weather".c5) As TotalWeather,
Count(1) as Freq,
AVG("Weather".c6 - "Weather".c5) AS AvgWeather
FROM "Weather", "TimeProvince"
WHERE ("Weather".c3="TimeProvince".c1) and ("Weather".c2="TimeProvince".c3)
GROUP BY "Weather".c2, "Weather".c3;

#Join 후 도시별 누적환자수 집계
SELECT "TimeProvince".c3,
count(1) as Num_Patients
FROM "TimeProvince", "PatientInfo"
WHERE "TimeProvince".c3="PatientInfo".c5
GROUP BY "TimeProvince".c3;

#Join 후 도시별,성별 누적환자 수 집계
SELECT "TimeProvince".c3, "PatientInfo".c2,
count(1) as Num_Patients
FROM "TimeProvince", "PatientInfo"
WHERE "TimeProvince".c3="PatientInfo".c5
GROUP BY "TimeProvince".c3, "PatientInfo".c2;


#도시별, 성별, 연령별 누적환자 수 집계
SELECT "PatientInfo".c2, "PatientInfo".c3, "PatientInfo".c5,
count(1) as Num_Patients
FROM "PatientInfo"
GROUP BY "PatientInfo".c5, "PatientInfo".c2, "PatientInfo".c3;

#최대,최소 환자수 집계
SELECT MAX(Num_Patients) as Max_num_patients,
MIN(Num_Patients) as Min_num_patients
FROM
(
SELECT "TimeProvince".c3,
count(1) as Num_Patients
FROM "TimeProvince", "PatientInfo"
WHERE "TimeProvince".c3="PatientInfo".c5
GROUP BY "TimeProvince".c3
) AS derivedTable;


#도시별,성별 환자수 10000명 이상 결과조회
SELECT "TimeProvince".c3, "PatientInfo".c2,
count(1) as Num_Patients
FROM "TimeProvince", "PatientInfo"
WHERE "TimeProvince".c3="PatientInfo".c5
GROUP BY "TimeProvince".c3, "PatientInfo".c2
HAVING count(1)>=10000;

#테이블 조인, 컬럼 합치기
select id, Concat(last_name, ' ', first_name) as names, c4
from name inner join genre ON name.id=genre.c1;

 

database structure

 

AWS 데이터베이스, 구글 데이터베이스, 구글 클라우드 데이터베이스, 무료 클라우드 데이터베이스 등 사용해서 데이터 끌어오는 분들 그리고 Data Analyst & Data Scientist 등 직무로의 취업을 희망하시는 분들 또한 PostgreSQL, MySQL 등 학습이 많이 필요하실겁니다. 그런 분들께 이 포스팅이 조금이나마 도움이 되었으면 좋겠습니다!

 

2020.12.10 - [테크 큐레이터] - [Dimension reduction] Feature selection, Feature extration 차이, 특징, 설명

2020.12.01 - [테크 큐레이터] - [PostgreSQL] 컬럼 정렬, 데이터 베이스 확인, 스키마 확인, 테이블명 변경, 컬럼명 변경, 테이블 조인, 컬럼 합치기 | Client tool 비교

 

제 글이 조금이나마 도움이 되셨다면 좋겠습니다.
공감하기, 댓글, 구독하기는 블로그에 큰 힘이 됩니다. 🌻
열.건. (여러분의 건강을 응원합니다. 💛)
728x90
반응형

댓글