Database/SQL

SQL :: 기초2

Dongkkase 2008. 11. 12. 16:25
반응형
use asample

select * --컬럼필터링
 from sample
where col004 >'서울' --인스턴스 필터링

select *
from sample
where col003 >= 26 and col004='서울'

select *
from sample
where col003 >= 26 or col004='서울'  --나이가 26이상 혹은 서울인 사람들은 모두 필터링

select *
from sample
where col002 like '%은%'  --퍼센트를 어디에 붙이냐에 따라 검색 결과가 틀려진다.

select *
from sample where col005 is not null --값이 다 입력이 된것만 찾고 not 이 없으면 값이 없는 레코드만 출력

select *
from sample
order by col003 asc --정렬문 : asc는 값이 작은 것 부터 정렬 [asc를 입력을 안해줘도 디폴트가 적은 값이다]

select * from sample
order by col003 desc --정렬문 : desc는 값이 큰 값부터 정렬

select top 3 * from sample --top 이라는 걸 붙이면 밑의 명령어에서 출력
order by col003

select top 3 with ties * --값은 값이면 같이 출력
from sample
order by col003 desc

select *
from sample
order by col003 desc, col005 asc


--예제 : 돈을 만원 이상받는 사람들을 이름순으로 정렬해서 이름과 돈을 출력

select * --3
from sample --1
where col005 >=10000 --2
order by col002 --4

--예제 : 돈 받은 사람만 출력

select *
from sample
where col005 is not null

--예제 : 돈 받지 않은 사람 출력
select *
from sample
where col005 is null


--예제 : 성시경과 김경호의 모든정보 출력

select *
from sample
where col002 ='김경호' or col002= '성시경' --or이 나오면 컬럼명도 나와야 한다.


-- 예제 : 김씨성과 한씨성을 가진 사람들을 조회하되 나이순으로 정렬
select *
from sample
where col002 like'김%' or col002 like '한%'
order by col003  asc


--예제 : 각지역의 지역명을 출력(고유하게 출력)

select count (distinct(col004)) as[지역수] --distinct()-같은 이름을 축약해서 출력 /  count()-값의 수를 출력 / as[] -별칭
from sample


--회원중 나이가 가장 많은 나이와 가장 적은 나이를 출력

select max(col003)as[가장큰나이], min(col003)as[가장작은나이] --max()-가장큰값을출력 / min()-작은값을 출력
from sample

--총 회원은 몇명인가?
select count(*) as[회원수]
from sample

--김씨는 몇명이냐

select count(col002)as[김씨의 숫자]
from sample
where col002  like '김%'




select count(col001), count(col005) --이런식으로 하면 값이 서로 다른것이 이 함수는 null을 빼고 출력한다,
from sample

select sum(col005), avg(col005), sum(col005)  --널을 제외한 평균값
from sample

select sum(col005),avg(col005), sum(col005), sum(col005) /count(col001) --널을 포함한 평균값
from sample

--함수 : sum(), avg(), count(), min(), max(), distinct()
--함수는 널값을 고려하지 않는다.

--각지역별로 지역명과 인구수를 구하고 싶다.

select col004, sum(col005)
from sample
group by  col004--뭔가에 의해 그룹을 만들다

select col004, count(col001) as[인구수]
from sample
group by  col004--뭔가에 의해 그룹을 만들다

--각지역별로 인구수가 많은 top2를 구하고싶다.
select top 2 col004, count(col001) as[인구수]
from sample
group by  col004--뭔가에 의해 그룹을 만들다
order by count(col001) desc


--각지역별로 돈을 가장 많이 낸사람의 금액을 출력하되 금액순으로 정렬(지역명,금액)

select col004 as[지역], max(col005)as[금액]
from sample
group by col004
order by max(col005) desc
반응형