728x90

declare @날짜datetime

set @날짜='0000-00-00'

 

전월 첫째날

SELECT dateadd(d,-day(@날짜)+1,@날짜)

 

전월 마지막 날짜

SELECT dateadd(d,-day(dateadd(m,1,@날짜)), dateadd(m,1,@날짜))

현재월의 첫째날

SELECT dateadd(d,-day(@날짜)+1,@날짜)

 

현재월의 마지막날


SELECT dateadd(d,-day(dateadd(m,1,@날짜)), dateadd(m,1,@날짜))

 

** DATEADD 함수

SELECT DATEADD(날짜형식, 값, 날짜)

 

728x90
728x90

MS SQL TEMP TABLE 사용 :

select 시 테이블이 무거울 경우 temp 테이블에 넣고 작업할 수 있다

 

임시테이블 만들기 / drop
CREATE TABLE #Temp(
 Idx int ,
 UserId varchar(36)
)

DROP  TABLE #Temp

** 두개(##)가 쓰이면 전역임시Table

 

 

데이터 select 후 임시테이블에 insert
INSERT INTO #TMP_TABLE
SELECT Idx ,
UserId
FROM (
넣으려는 데이터
)

 

 

OBJECT_ID 함수

테이블에 개체 ID가 있는 지 확인한 후 drop 할 수 있음

IF OBJECT_ID('tempdb.dbo.#TMP_TABLE', 'U') IS NOT NULL
BEGIN DROP TABLE #TMP_TABLE END

(오라클의 경우 CREATE OR REPLACE 를 사용하면 CREATE 할 때 기존에 같은 이름의 개체가 있으면

REPLACE 하고 개체가 없으면 CREATE 하는 기능이 있지만 MS SQL Server 에는 없음)

728x90
728x90

>프로시저란?

프로그래머가 생성해놓은 쿼리문을 마치 하나의 메서드 형식으로 관리하는 것

 

>프로시저 생성, 조회, 삭제 쿼리

생성

CREATE PROC [프로시저명] AS [쿼리문]

 

조회

sp_helptext [프로시저명]

 

삭제

DROP PROCEDURE [프로시저명]

 

> MSSQL에서 내가 원하는 내용이 포함된 프로시저를 찾는 쿼리

SELECT OBJECT_NAME(object_id),

OBJECT_DEFINITION(object_id)

FROM sys.procedures

WHERE OBJECT_DEFINITION(object_id) LIKE '%검색할 키워드%'

 

>개체 탐색기에서 찾기

- 프로그래밍 기능 > 저장 프로시저 > 필터 후 > 새 스크립팅하면 기존 프로시저 정보 볼 수 있음

728x90

'MS SQL > MS SQL' 카테고리의 다른 글

MSSQL : UNION , UNION ALL, INTERSECT  (0) 2023.02.27
MS SQL : TEMP TABLE, OBJECT_ID  (0) 2023.01.31
MS SQL : @@rowcount 영향받은 행 수 반환  (0) 2022.11.28
MS SQL : distinct 중복 값 제거  (0) 2022.05.04
MS SQL : ROW NUM  (0) 2022.04.28
728x90

[형태]
select로 DB에서 조회할 때 중복되는 값을 제거, distinct를 붙인 컬럼은 중복을 합쳐 한번만 출력된다
select distinct 필드 from 테이블

[예제]

해당 테이블에서 sell_date별로 product를 뽑을 때, 항목이 겹침 > product에 distinct를 써줌

 select
      distinct product,
      sell_date
  from activities  

 

[특징]
1) count와 함께 사용가능함
count(distinct product) as num_sold -> product 항목 중복없이 개수 카운팅

2) distinct 뒤에 2개 이상의 컬럼 사용
모든 컬럼을 하나로 인식하여 그 행의 중복을 제거함
select distict product name, product type from table -> 두 컬럼 모두 중복 제거

 

3) 동일한 결과를 출력할 수 있다면 distinct 보다 group by가 db부담을 줄이고 속도도 빠름

728x90

'MS SQL > MS SQL' 카테고리의 다른 글

MSSQL : UNION , UNION ALL, INTERSECT  (0) 2023.02.27
MS SQL : TEMP TABLE, OBJECT_ID  (0) 2023.01.31
MS SQL : @@rowcount 영향받은 행 수 반환  (0) 2022.11.28
MSSQL - 프로시저 생성,조회,삭제,찾기  (0) 2022.05.13
MS SQL : ROW NUM  (0) 2022.04.28
728x90

[정의]

쿼리에 의해 반환되는 행 번호를 출력

데이터에 순번을 메기거나, 특정 번호 데이터를 출력할 때 사용

 

[문법] 

select * from 테이블 where rownum between 1 and 5
> between과 함께 사용가능


select * from (select rownum num, member.* from member) where num between 1 and 5
-> select rownum 부분을 member테이블에 합침 num이라는 별칭을 붙임

rownum 뒤에 별칭 붙일 수 있음

select * from (select rownum num, notice.* from notice)
where num between 1 and 5;
>rownum으로 테이블을 따로 생성해서 데이터 출력할 수 있다. 기존 notice가 아니고 활용한 새로운 결과 집합임

 

ROW_NUMBER() OVER ([PARTITION BY value_expression, ... [n]] order_by_clause)

> over partition by와 함께 사용가능

 

[예제]

SELECT JOB, ENAME, SAL 
     , RANK( ) OVER (ORDER BY SAL DESC) RANK
     , ROW_NUMBER() OVER (ORDER BY SAL DESC) ROW_NUMBER
  FROM EMP; 

JOB       ENAME             SAL       RANK ROW_NUMBER
--------- ---------- ---------- ---------- ----------
PRESIDENT KING             5000          1          1
ANALYST   FORD             3000          2          2
ANALYST   SCOTT            3000          2          3
MANAGER   JONES            2975          4          4
MANAGER   BLAKE            2850          5          5
MANAGER   CLARK            2450          6          6
SALESMAN  ALLEN            1600          7          7
SALESMAN  TURNER           1500          8          8
CLERK     MILLER           1300          9          9
SALESMAN  WARD             1250         10         10
SALESMAN  MARTIN           1250         10         11
CLERK     ADAMS            1100         12         12
CLERK     JAMES             950         13         13
CLERK     SMITH             800         14         14

 

참고 : http://www.gurubee.net/lecture/2382

728x90
728x90

https://leetcode.com/problems/swap-salary/

 

Swap Salary - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

[problem]

성별 f,m 인경우 전체 바꿔버리기

[analysis]

1. update이용해서 데이터 업뎃

-> UPDATE 테이블이름

SET 필드이름1=데이터값1, 필드이름2=데이터값2, ...

WHERE 필드이름=데이터값

 

2.. case when 이용해서 f인 경우, m인 경우 분리

-> case when 문법 : CASE WHEN 조건절 THEN 참일때 값 ELSE 거짓일 때 값 END 컬럼명

 

[solution]

728x90
728x90

https://leetcode.com/problems/customer-placing-the-largest-number-of-orders/

 

[problem]

 order_number가 가장 많은 customer 출력

[anlysis]

1. order no 가장많은 =  select top 1이용

2. count(*) 

select 변수 order by count(*)를 통해 행의 개수를 출력할 수 있다

 

[solution]

728x90
728x90

https://leetcode.com/problems/game-play-analysis-i/

 

[problem]

[analysis]

1. eventdate가 여러 데이터가 있으므로 min을 이용

2. id group by

 

[solution]

728x90
728x90

https://leetcode.com/problems/customers-who-never-order/

 

Customers Who Never Order - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

[problem]

Write an SQL query to report all customers who never order anything.

Return the result table in any order.

 

[analysis]

1. 두 테이블 left join

2. cutomnerID가 null인 경우 where을 사용해서 리스트 출력해야함

join 과 where은 같이 사용할 수 있따!!

 

[soultion]

728x90
728x90

https://www.hackerrank.com/challenges/weather-observation-station-2/problem

 

Weather Observation Station 2 | HackerRank

Write a query to print the sum of LAT_N and the sum of LONG_W separated by space, rounded to 2 decimal places.

www.hackerrank.com

 

[problem]

[analysis]

1. SUM 이용

2. ROUND(컬럼명/값,n) 값을 소수점이하 n자리수로 반올림

 

[solution]

728x90

'MS SQL > MS SQL : HackerRank' 카테고리의 다른 글

MS SQL- HackerRank Japan Population(sum, where)  (0) 2022.04.25

+ Recent posts