반응형

전체 글 1480

SQL Server - 데이터 변환 함수 TRY PARSE, TRY CONVERT

TRY_PARSE function - 2012년에 소개 되었다. - 문자열을 날짜/시간 이나 숫자 형식으로 변환시킴. - 만약 변환되어질 수 없다면 NULL값이 리턴된다. Syntax : TRY_PARSE (string_value AS data_type) Example : SELECT TRY_PARSE('99' AS INT) AS Result --True SELECT TRY_PARSE('ABC' AS INT) AS Result --False TRY_CONVERT function - 2012년에 소개 되었다. - 주어진 값을 특정 데이터 타입으로 변환시킨다. - 만약 변환되지 않는 값이면 NULL을 리턴한다. Syntax : TRY_CONVERT (data_type, value, [style]) 여기서 스..

Database/SQL Server 2020.12.19

SQL Server - IIF 함수

IIF 함수 - 2012년에 소개된 함수이다. - Boolean 식의 의하여 참인지 거짓인지에 따라 두개의 값중 하나를 리턴한다. Returns one of two the values, depending on whether the Boolean expression evaluates to ture or false. - IIF 는 CASE 식의 축소버전이다. Syntax : IIF ( boolean_expression, true_value, false_value) Example : Declare @GenderId INT SET @GenderId = 1 SELECT IIF(@GenderId = 1 , 'Male' , 'Female') AS Gender

Database/SQL Server 2020.12.19

SQL Server - Choose 함수

Choose 함수 - 2012년도에 소개 되었다. - 사용 가능한 값 리스트에서 지정된 인덱스의 항목을 리턴. Returns the item at the specified index from the list of available values. - 인덱스 시작 위치는 0이 아닌 1이다. - 사용 가능한 리스트에 없는 값을 불러오면 NULL값이 리턴. Syntax : CHOOSE ( index, val_1, val_2, ...) Example : SELECT Name, DateOfBirth, CHOOSE(DATEPART(MM, DateOfBirth), 'JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC') AS [Month] FRO..

Database/SQL Server 2020.12.19

SQL Server - UNPIVOT 언피벗

PIVOT 연산자는 행을 열로 바꾸고 UNPIVOT은 반대로 열을 행으로 바꾼다!! PIVOT operator turns ROWS into COLUMNS, where as UNPIVOT turns COLUMNS into ROWS. SELECT SalesAgent, Country, SaleAmount FROM tblProductSales UNPIVOT ( SalesAmount FOR Country IN (India, US, UK) ) AS UnPivotExample SELECT SalesAgent, Country, SalesAmount FROM (SELECT SalesAgent, India, US FROM tblProductSales PIVOT ( SUM(SalesAmount) FOR Country IN ..

Database/SQL Server 2020.12.19

SQL Server - 분석 함수 Window functions

윈도우 함수 내의 여러 갈래 - 집계 함수 : AVG, SUM, COUNT, MIN, MAX etc.. - 순위 함수 : RANK, DENSE_RANK, ROW_NUMBER etc.. - 분석 함수 : LEAD, LAG, FIRST_VALUE, LAST_VALUE etc... OVER절은 함수들이 적용될 행의 분할이나 순서를 담당한다. 따라서 이러한 기능들을 Window functions 이라고 한다. OVER Clause는 세가지 인수를 허용한다. OVER clause defines the partitioning and ordering of rows(i.OVER clause defines the partitioning and ordering of rows(i.e a window) for the abov..

Database/SQL Server 2020.12.18

SQL Server - 첫 번째 값 & 마지막 값 함수 FIRST_VALUE & LAST_VALUE function

FIRST_VALUE function - 2012년에 소개된 함수이다. - 지정한 함수의 첫번째 값을 가져온다. - ORDER BY clause is required - PARTITION BY clause is optional Syntax: FIRST_VALUE(Column_Name) OVER (ORDER BY Col1, Col2, ...) Example: SELECT Name, Gender, Salary, FIRST_VALUE(Name) OVER (ORDER BY Salary) AS FirstValue FROM Employees 첫 번째 값 'Mark'만 쫘악 나열 되어 있는 모습 파티션을 넣으면 어떻게 될까 SELECT Name, Gender, Salary, FIRST_VALUE(Name) OVER ..

Database/SQL Server 2020.12.18

SQL Server - Lead & Lag 함수

Lead & Lag functions - 2012년에 소개된 함수 - Lead 함수는 후속행에 올 데이터를 현재행과 함께 쓸 수 있다. - Lag함수는 이전행 데이터를 현재행 데이터와 함께 쓸 수 있다. - ORDER BY clause is required - PARTITION BY clause is optional Syntax: LEAD(Column_Name, Offset, Default_Value) OVER (ORDER BY Col1, Col2, ...) LAG(Column_Name, Offset, Default_Value) OVER (ORDER BY Col1, Col2, ...) --Offset : Number of rows to lead or lag --Default_Value : The defa..

Database/SQL Server 2020.12.18

SQL Server - NTILE 함수

NTILE function - SQL Server 2005에 소개 되어진 함수 - ORDER BY 절이 필수로 요구된다. ORDER BY clause is required - PARTITION BY 절은 선택적으로 요구된다. PARTITION BY clause is optional - 지정한 숫자만큼의 그룹으로 행을 나눈다. Distributes the rows into a specified number of groups. - 만약 지정한 숫자가 정확하게 나누어지지 않는 값이라면 그룹의 크기가 다를 수 있다. If the number of rows is not divisible by number of groups, you may have groups of two different sizes. - 이런 경..

Database/SQL Server 2020.12.18

SQL Server - 러닝 합계 Running Total

파티션 없이 러닝 합계 계산하는 쿼리문 SQL Query to compute running total without partitions. SELECT Name, Gender, Salary, SUM(Salary) OVER (ORDER BY ID) AS RunningTotal FROM Employees 파티션을 나눈 쿼리 SELECT Name, Gender, Salary, SUM(Salary) OVER (PARTITION BY Gender ORDER BY ID) AS RunningTotal FROM Employees RunningTotal이 파티션이 있는 부분에서 다시 시작하는 것을 볼 수 있음. 여기서 ORDER BY ID를 하는 것은 Unique key이기 때문이다. 유니크 하지 않은 것으로 ORDER..

Database/SQL Server 2020.12.18

SQL Server - RANK & DENSE_RANK 함수

RANK and DENSE_RANK functions - 2005년에 소개되었다.Introduced in SQL Server 2005 - ORDER BY절에서 지정한 행 순서에 따라 1부터 시작하는 순위를 리턴한다. Return a rank starting at 1 based on the ordering of rows imposed by the ORDER BY clause - ORDER BY clause is required - PARTITION BY clause is optional - 파티션으로 분리되어있으면 파티션이 바뀔때 1로 리셋이 된다.When the data is partitioned, rank is reset to 1 when the partition changes Difference be..

Database/SQL Server 2020.12.16

SQL Server - Over 절 과 ROW_NUMBER() 함수

Over clause 오버 절은 PARTITION BY와 함께 쓰이며 데이터를 파티션으로 나누는데 쓰인다. The OVER clause combined with PARTITION BY is used to break up data into partitions. The specified function operates for each partition. Syntax: function (...) OVER (PARTITION BY Col1, Col2, ...) COUNT(), AVG(), SUM(), MIN(), MAX(), ROW_NUMBER(), RANK(), DENSE_RANK() etc 어떤 함수와도 함께 쓸 수 있다. Row_Number Function - 2005년에 소개된 함수이다.Introduce..

Database/SQL Server 2020.12.16

SQL Server - 그룹핑, 그룹핑_아이디 GROUPING, GROUPING_ID

그룹핑은 무엇인가 ? What is Grouping function 그룹핑(열)은 컬럼이 GROUP BY 목록에 집계되었나 안되었나 의 여부를 나타내는 것이다. 집계된 행에는 1로 표시가 되고 아니면 0이라고 표시된다. Grouping(Column) indicates whether the column in a GROUP BY list is aggregated or not. Grouping returns 1 for aggregated or 0 for not aggregated in the result set. SELECT Continent, Country, City, SUM(SaleAmount) AS TotalSales, GROUPING(Continent) as GP_Continent, GROUPING(C..

Database/SQL Server 2020.12.16

SQL Server - 소계, 합계[롤업, 큐브] Rollup, Cube

ROLLUP이 쓰이는 예제를 보면서 이해하자. 아래의 예시 쿼리는 모두다 같은 결과를 나타낸다 --1 SELECT Country, SUM(Salary) as TotalSalary FROM Employees GROUP BY ROLLUP(Country) --2 SELECT Country, SUM(Salary) as TotalSalary FROM Employees GROUP BY Country with ROLLUP --3 SELECT Country, SUM(Salary) as TotalSalary FROM Employees GROUP BY Country UNION ALL SELECT NULL, SUM(Salary) as TotalSalary FROM Employees --4 바로 전에 배운 GROUPING S..

Database/SQL Server 2020.12.15

SQL Server - Grouping Sets 함수 Grouping Sets in SQL Server

그룹핑 셋 Grouping Sets 함수 2008년에 소개된 이 기능은 다음과 같은 예시를 간단하게 해결하기 위한 것이다. Select Country, Gender, Sum(Salary) as TotalSalary From Employees Group By Country, Gender UNION ALL Select Country, NULL, Sum(Salary) as TotalSalary From Employees Group By Country UNION ALL Select NULL, Gender, Sum(Salary) as TotalSalary From Employees Group By Gender UNION ALL Select NULL, NULL, Sum(Salary) as TotalSalary Fr..

Database/SQL Server 2020.12.15

SQL Server - 테이블 반환 매개변수 Table Valued Parameters in SQL Server

테이블 반환이란 새로운 기능은 2008년에 소개되었다. 테이블 반환 매개변수는 테이블(여러개의 데이터 행을 가지고 있는)이 어플리케이션 또는 T-SQL에서 부터 저장 프로시저에 매개변수로 전달 될 수 있다. 2008년 전에는 매개변수로 테이블을 전달할 수 없었다. Table-Valued Parameter is a new feature introduced in SQL Server 2008. Table-Valued Parameter allows a table(i.e multiple rows of data) to be passed as a parameter to a stored procedure from T-SQL code or from an application. Prior to SQL Server 2008..

Database/SQL Server 2020.12.14

SQL Server - Where절과 Having절의 차이 Difference between where and having in SQL Server

둘 다 조건을 주는 절인데 시작점이 다르다. Where은 조건을 주어 필터링을 하고 Having은 나온 결과를 필터링한다. 성능면에서 where가 좋다. 그러니 가능하면 having의 사용을 피하는게 좋다. From a performance standpoint, HAVING is slower than WHERE and should be avoided when possible. SELECT Product, SUM(SaleAmount) AS TotalSales FROM Sales WHERE Product in ('iPhone', 'Speakers') GROUP BY Product SELECT Product, SUM(SaleAmount) AS TotalSales FROM Sales GROUP BY Produc..

Database/SQL Server 2020.12.12

SQL Server - Select into 구문 / Select into statement in SQL Server

SELECT INTO 구문 이란? SQL Server에서의 SELECT INTO은 새로운 테이블에 넣을 데이터들을 다른 하나의 테이블에서 선택한다. The SELECT INTO statement in SQL Server, selects data from one table and inserts it into a new table SQL Server에서 SELECT INTO 구문이 할 수 있는 것들 SELECT INTO statement in SQL Server can do the following things: 1. 복제 가능. 백업할 때 유용함 Copy all rows and columns from an existing table into a new table. This is extremely usefu..

Database/SQL Server 2020.12.12
반응형