Monday, July 20, 2020

Analytical & Window Functions


Please refer to my previous post in which schema and data for EMP and DEPT tables available.

In this article we are about to discuss about SQL Server Analytical and Window functions. As stated in Microsoft docs, analytic functions calculate an aggregate value based on a group of rows. Unlike aggregate functions, however, analytic functions can return multiple rows for each group. Use analytic functions to compute moving averages, running totals, percentages or top-N results within a group.

These functions are common in most of the RDBMS applications and are widely used by the data and business analysts.

NTILE
It divides/distributes an ordered data set (or partition) into a specified number of groups which we call it buckets and assigns an appropriate (bucket) number to each row. The bucket number will represent each row to which bucket it belongs to.

In other words, it is used to divide rows into equal sets and assign a number to each row.

SELECT Ename, sal, NTILE(2) OVER (ORDER BY sal DESC) Bucket FROM Emp;


SELECT Ename, sal, NTILE(5) OVER (ORDER BY sal DESC) Bucket FROM Emp;


The following query retrieves the records from the first bucket.

SELECT * FROM (
SELECT          Ename,
sal, NTILE(4) OVER (ORDER BY sal DESC) Bucket
FROM Emp
) EmpAlias
WHERE Bucket=1;
ROW NUMBER:
This function represents each row with a unique and sequential value based on the column used in OVER clause. Here, we are having 10 rows in our Emp table and will use ROW_NUMBER on these records.

This can also be used to assign a serial /row number to the rows within the provided dataset.

SELECT DeptNo, sal, ROW_NUMBER() OVER (ORDER BY sal) AS row_num FROM emp;

SELECT 
     DeptNo, 
     sal, 
     ROW_NUMBER() OVER (PARTITION BY deptno ORDER BY sal DESC) AS row_num 
FROM emp;

RANK:
This function is used to assign a rank to the rows based on the column values in OVER clause.

The row with equal values assigned the same rank with next rank value skipped.   

SELECT DeptNo, sal, RANK() OVER(ORDER BY sal DESC) AS rnk FROM emp;


SELECT   DeptNo, 
                 sal, 
                 RANK() OVER(PARTITION BY DeptNo ORDER BY sal DESC) AS rnk 
FROM emp;
DENSE_RANK: The DENSE_RANK analytics function used to assign a rank to each row. The rows with equal values receive the same rank and this rank assigned in the sequential order so that no rank values are skipped.

SELECT 
          DeptNo, 
          sal, 
          DENSE_RANK() OVER(PARTITION BY DeptNo ORDER BY sal DESC) AS dns_rnk 
FROM emp;
Let us use all the above functions in one query to see the difference in the results.

SELECT DeptNo AS dept, sal AS sal,
ROW_NUMBER() OVER (PARTITION BY DeptNo ORDER BY sal DESC) AS RowNumber,
RANK() OVER (PARTITION BY DeptNo ORDER BY sal DESC) AS iRank,
DENSE_RANK() OVER(PARTITION BY DeptNo ORDER BY sal DESC) AS DenseRank
FROM emp;


CUME_DIST:
This function stands for cumulative distribution. It computes the relative position of a column value in a group. Here, we can calculate the cumulative distribution of salaries among all departments. For a row, the cumulative distribution of salary is calculated as:

SELECT DeptNo, sal, CUME_DIST() OVER (ORDER BY sal) AS cum_dist FROM emp;

SELECT DeptNo, sal, CUME_DIST() OVER (ORDER BY sal) AS cum_dist FROM emp
WHERE DEPTNO in(20,30);


CUME_DIST(salary) = Number of rows with the value lower than or equals to salary / total number of rows in the dataset.

In the above example, due to ORDER BY clause, 1st row from salary will be counted as 1 and it will be divided by the total number of rows. That is 1/14 = 0.1

For the second row, it is 2/14 = 0.14;

For the 4th row and the next immediate row too has the same value, it will be calculated as 5/14 = 0.35 and assign it for the both rows.

Look at the outcome to understand.

PERCENT_RANK:
It is very similar to the CUME_DIST function. It ranks the row as a percentage. In other words, it calculates the relative rank of a row within a group of rows.

The range of values returned by PERCENT_RANK is between 0 to 1 and first row in the dataset is always zero. This means the return value is of the double type.

Let’s rank the salary by department wise as percentage:

Percent_Rank = (rank decreased by 1)/(remaining rows in the group)

SELECT DeptNo, sal,
RANK() OVER (PARTITION BY deptNo ORDER BY sal DESC) AS iRank,
CUME_DIST() OVER (PARTITION BY deptno ORDER BY sal) AS cum_dist,
PERCENT_RANK() OVER (PARTITION BY deptNo ORDER BY sal) AS perc_rnk 
FROM EMP;
Go

If you observe its behavior when it calculates the relative rank for the rows with same values, it assigns same percentage rank value (0.75) to both of them. The behavior is similar to rank function.

Range Between & Rows Between:
These functions are called window functions which fetches records right before and after the current record to perform the aggregation. It is similar to lead and lag functions however a window function defines a frame or window of rows with a given length around the current row, and performs a calculation across the set of data in the window. Mostly these functions will be used to get the cumulative sum/average, running or moving sum or averages.

Examples:
SELECT DISTINCT    DeptNo, --sal,
            SUM(sal) OVER(ORDER BY DeptNo RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS 'RangeUnbound'
FROM emp
GO


SELECT DISTINCT    DeptNo, --sal,
            SUM(sal) OVER(ORDER BY DeptNo ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS 'RowsUnbound'
FROM emp
GO


SELECT DISTINCT    EMPNO, sal,
            SUM(sal) OVER(ORDER BY EmpNo ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS 'RowsUnbound'
FROM emp
GO


SELECT DISTINCT    EMPNO, sal,
            SUM(sal) OVER(ORDER BY EmpNo RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS 'RangeUnbound'
FROM emp
GO


SELECT DISTINCT    Job, sal, DeptNo,
            SUM(sal) OVER(ORDER BY DeptNo RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS 'RangeUnbound'
FROM emp
GO


lag AND Lead FUNCTIONS:
The LAG function gets the information from a past column, while LEAD brings information from an ensuing line. The two functions are fundamentally the same as one another and you can simply supplant one by the other by changing the sort request.

SELECT ename, deptno, sal,
LEAD(sal, 1) OVER(PARTITION BY deptno ORDER BY sal) AS lead1,
LEAD(sal, 2) OVER(PARTITION BY deptno ORDER BY sal) AS lead2,
LAG(sal,1) OVER(PARTITION BY deptno ORDER BY sal) AS lag1,
LAG(sal,2) OVER(PARTITION BY deptno ORDER BY sal) AS lag2
FROM emp ORDER BY deptno,sal;


Hope this article helped you in understanding Analytical and Window functions.


Oracle SQL Emp and Dept Tables For SQL Server

--Table definition - Dept
CREATE TABLE Dept( 
DeptNo INT
DName VARCHAR(14), 
Loc VARCHAR(13), 
CONSTRAINT pk_Dept PRIMARY KEY (DeptNo) ); 

-- Tabe Definition - Emp: 
CREATE TABLE Emp( 
EmpNo INT
EName VARCHAR(10), 
Job VARCHAR(9), 
Mgr INT
HireDate date
Sal INT
Comm INT
DeptNo INT
CONSTRAINT pk_Emp PRIMARY KEY (EmpNo), 
CONSTRAINT fk_DeptNo FOREIGN KEY (DeptNo) REFERENCES Dept (DeptNo) ); 

--Dept Table data: 
INSERT INTO Dept VALUES(10, 'ACCOUNTING', 'NEW YORK'); 
INSERT INTO Dept VALUES(20, 'RESEARCH', 'DALLAS'); 
INSERT INTO Dept VALUES(30, 'SALES', 'CHICAGO'); 
INSERT INTO Dept VALUES(40, 'OPERATIONS', 'BOSTON'); 

--Emp Table data: 
INSERT INTO Emp VALUES( 7839, 'KING', 'PRESIDENT', NULL, CONVERT(DATETIME,'17-11-1981',103), 5000, NULL, 10 ); 
INSERT INTO Emp VALUES( 7698, 'BLAKE', 'MANAGER', 7839, CONVERT(DATETIME,'1-5-1981',103), 2850, NULL, 30 ); 
INSERT INTO Emp VALUES( 7782, 'CLARK', 'MANAGER', 7839, CONVERT(DATETIME,'9-6-1981',103), 2450, NULL, 10 ); 
INSERT INTO Emp VALUES( 7566, 'JONES', 'MANAGER', 7839, CONVERT(DATETIME,'2-4-1981',103), 2975, NULL, 20 ); 
INSERT INTO Emp VALUES( 7788, 'SCOTT', 'ANALYST', 7566, CONVERT(DATETIME,'13-JUL-87',103) - 85, 3000, NULL, 20 ); 
INSERT INTO Emp VALUES( 7902, 'FORD', 'ANALYST', 7566, CONVERT(DATETIME,'3-12-1981',103), 3000, NULL, 20 ); 
INSERT INTO Emp VALUES( 7369, 'SMITH', 'CLERK', 7902, CONVERT(DATETIME,'17-12-1980',103), 800, NULL, 20 ); 
INSERT INTO Emp VALUES( 7499, 'ALLEN', 'SALESMAN', 7698, CONVERT(DATETIME,'20-2-1981',103), 1600, 300, 30 ); 
INSERT INTO Emp VALUES( 7521, 'WARD', 'SALESMAN', 7698, CONVERT(DATETIME,'22-2-1981',103), 1250, 500, 30 ); 
INSERT INTO Emp VALUES( 7654, 'MARTIN', 'SALESMAN', 7698, CONVERT(DATETIME,'28-9-1981',103), 1250, 1400, 30 ); 
INSERT INTO Emp VALUES( 7844, 'TURNER', 'SALESMAN', 7698, CONVERT(DATETIME,'8-9-1981',103), 1500, 0, 30 ); 
INSERT INTO Emp VALUES( 7876, 'ADAMS', 'CLERK', 7788, CONVERT(DATETIME,'13-JUL-87', 103), 1100, NULL, 20 ); 
INSERT INTO Emp VALUES( 7900, 'JAMES', 'CLERK', 7698, CONVERT(DATETIME,'3-12-1981',103), 950, NULL, 30 ); 
INSERT INTO Emp VALUES( 7934, 'MILLER', 'CLERK', 7782, CONVERT(DATETIME,'23-1-1982',103), 1300, NULL, 10 );
Go

SELECT * FROM Emp
SELECT * FROM Dept

Sunday, July 19, 2020

Database Restore Information with Restore Start and Completed Date Time


Following points to be accomplished -
  • Get all the databases restoration information
  • From all reporting, staging or testing environments
  • Information about when the database restoration started and completed
  • If the restoration is a full restore or differential
  • When the backup file was ready
  • Above said information is to be received through Email in a tabular format.
Well, it seems to be easy, and of course it's easy once you know it.

Below are the implementation steps.
  • Write a SQL code to retrieve the complete information about backups. This includes  when the backup file was ready, the restoration type, restoration start date time and end date time. Data restoration completed date time is unavailable in backup tables hence so get the information from the logs.
  • Create a Power-Shell script to automate this process and fetch the data restoration information from across various reporting/staging/testing servers.
  • Store this information in a table to maintain a history. This will help in analyzing if the restoration time is increasing/decreasing over a period of time. 
  • Fetch this information from the table and convert it into HTML tabular format. Send the information through Email using "db Mail".

Certainly, there will be some other work-around, or smarter methods version to achieve this goal. But since this solution solves my purpose and is working perfectly, I didn't dig deeper to find a shorter or better implementation. 

Here is my table which will hold the data restoration information.


Upon execution you will get the complete data restore information from the reporting server in which you had executed the code. However the requirement is to fetch the same information from across various servers. Hence write a Power-shell script as mentioned below.


clear;
$Servers = Get-Content "D:\Monitoring_RestoreInfo\Computers.txt"; 
   foreach($computer in $Servers) 
    { invoke-sqlcmd -inputfile "D:\Monitoring_RestoreInfo\Restore Information SQL Server.sql" -serverinstance $computer -database "msdb" -ErrorAction 'Stop' -Verbose -QueryTimeout 1800 # the parameter -database can be omitted based on what your sql script does.
    }

Note: Computers.txt has all the names of the reporting/staging/testing servers.

Create a windows scheduled task in the server in where you have an access to other servers. The screenshots are given below.




Arguments provided are as follows:
  • Program/Script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
  • Add arguments (Optional): D:\Monitoring_RestoreInfo\DBRestoreInfo.ps1
  • Start In : D:\Monitoring_RestoreInfo\

Now let's go back to SQL Server database in which you have created the table. Write a script to convert the data into HTML format.


Create an SQL Agent Job to automate this process and run it every morning after execution of the Power-shell script.

Thank you for visiting my blog. Please do let me know if you need more clarification in this implementation.

Tuesday, March 16, 2010

SQL Server - Data Export to XML

One of my friend requested me to explain how many ways are there to export the data from SQL Server 2005 into an XML file. Well, this artcle will let you know how to export the data from SQL Server 2005 to XML using different modes.

SELECT * FROM Customers (NOLOCK)

/* Result is
CustomerID CustomerName ActiveStatus
----------- ------------------------------ ------------
100 John 0
200 Kate 1
300 Julia 1
400 Maddy 0

(4 row(s) affected)
*/

SELECT * FROM Customers (NOLOCK)
FOR XML PATH, ROOT('root')

(Please note that I have placed "`" symbol after "<" and ">" in the results to avoid execution in the web) 

/* Result is
<`root`>
<`row`>
<`CustomerID>100<`/CustomerID>
<`CustomerName>John<`/CustomerName>
<`ActiveStatus>0<`/ActiveStatus>
<`/row><`row`>
<`CustomerID>200<`/CustomerID>
<`CustomerName>Kate<`/CustomerName>
<`ActiveStatus>1<`/ActiveStatus>
<`/row><`row>
<`CustomerID>300<`/CustomerID>
<`CustomerName>Julia<`/CustomerName>
<`ActiveStatus>1<`/ActiveStatus>
<`/row><`row>
<`CustomerID>400<`/CustomerID>
<`CustomerName>Maddy<`/CustomerName>
<`ActiveStatus>0<`/ActiveStatus>
<`/row>
<`/root>*/

/**************************************/
/** EXAMPLES FOR AUTO MODE **/
/**************************************/
In order to generate simple hierarchies we can use AUTO mode. Since the result will be in form of nested elements, it doesn't provide much control over the shape of the XML whereas EXPLICIT and PATH modes provide better control and shape of the XML.

SELECT * FROM Customers FOR XML AUTO, TYPE

/* Result is
<`Customers CustomerID="100" CustomerName="John" ActiveStatus="0" /`>
<`Customers CustomerID="200" CustomerName="Kate" ActiveStatus="1" /`>
<`Customers CustomerID="300" CustomerName="Julia" ActiveStatus="1" /`>
<`Customers CustomerID="400" CustomerName="Maddy" ActiveStatus="0" /`>
*/

Using Variables
DECLARE @cust XML;
SET @cust = (SELECT * FROM Customers FOR XML AUTO, TYPE)
SELECT @cust

/* Result is
<`Customers CustomerID="100" CustomerName="John" ActiveStatus="0" /`>
<`Customers CustomerID="200" CustomerName="Kate" ActiveStatus="1" /`>
<`Customers CustomerID="300" CustomerName="Julia" ActiveStatus="1" /`>
<`Customers CustomerID="400" CustomerName="Maddy" ActiveStatus="0" /`>
*/

XML Data is into another table
CREATE TABLE Test1(i int, x XML)

INSERT INTO Test1 SELECT 1, (SELECT * FROM Customers FOR XML AUTO, TYPE)

SELECT * FROM Test1

/* Result is
<'Customers CustomerID="100" CustomerName="John" ActiveStatus="0" /`>
<'Customers CustomerID="200" CustomerName="Kate" ActiveStatus="1" /`>
<'Customers CustomerID="300" CustomerName="Julia" ActiveStatus="1" /`>
<'Customers CustomerID="400" CustomerName="Maddy" ActiveStatus="0" /`>
*/
/************************************/
/** EXAMPLE FOR RAW MODE **/
/************************************/
Each row of the result set from the query will be converted into element. The column from the result set will be mapped to the attribute of the row element.

SELECT *
FROM Customers
FOR XML RAW, ELEMENTS

/* Result is
<`row>
<`CustomerID>100<`/CustomerID>
<`CustomerName>John<`/CustomerName>
<`ActiveStatus>0<`/ActiveStatus>
<`/row><`row>
<`CustomerID>200<`/CustomerID>
<`CustomerName>Kate<`/CustomerName>
<`ActiveStatus>1<`/ActiveStatus>
<`/row><`row>
<`CustomerID>300<`/CustomerID>
<`CustomerName>Julia<`/CustomerName>
<`ActiveStatus>1<`/ActiveStatus>
<`/row><`row>
<`CustomerID>400<`/CustomerID>
<`CustomerName>Maddy<`/CustomerName>
<`ActiveStatus>0<`/ActiveStatus>
<`/row>
*/

You can rename the element by using optional argument in RAW Mode.
SELECT *
FROM Customers
FOR XML RAW ('CustomerDetails'), ELEMENTS

/* Result is
<`CustomerDetails>
<`CustomerID>100<`/CustomerID>
<`CustomerName>John<`/CustomerName>
<`ActiveStatus>0<`/ActiveStatus>
<`/CustomerDetails><`CustomerDetails>
<`CustomerID>200<`/CustomerID>
<`CustomerName>Kate<`/CustomerName>
<`ActiveStatus>1<`/ActiveStatus>
<`/CustomerDetails><`CustomerDetails>
<`CustomerID>300<`/CustomerID>
<`CustomerName>Julia<`/CustomerName>
<`ActiveStatus>1<`/ActiveStatus>
<`/CustomerDetails><`CustomerDetails>
<`CustomerID>400<`/CustomerID>
<`CustomerName>Maddy<`/CustomerName>
<`ActiveStatus>0<`/ActiveStatus>
<`/CustomerDetails>
*/

/*****************************************/
/** EXAMPLE FOR EXPLICIT MODE **/
/*****************************************/
This mode is more recommended one when compare with RAW and AUTO modes. It is because of the control over the shape of the XML.

For more details refer to :
http://msdn.microsoft.com/en-us/library/ms189068.aspx

CREATE VIEW DataExport AS
SELECT
1 AS Tag,
NULL AS Parent,
'CustomerID' AS [data!1!identifier],
NULL AS [record!2!CustomerID!element] ,
NULL AS [record!2!CustomerName!element],
NULL AS [record!2!ActiveStatus!element]

UNION ALL


SELECT
2 AS Tag,
1 AS Parent,
'CustomerID' AS [data!1!identifier],
CustomerID AS [record!2!CustomerID!element] ,
CustomerName AS [record!2!CustomerName!element],
ActiveStatus AS [record!2!ActiveStatus!element]
FROM Customers SELECT * FROM DataExport
FOR XML EXPLICIT

/* Result is
<`data identifier="CustomerID">
<`record>
<`CustomerID>100<`/CustomerID>
<`CustomerName>John<`/CustomerName>
<`ActiveStatus>0<`/ActiveStatus>
<`/record>
<`record>
<`CustomerID>200<`/CustomerID>
<`CustomerName>Kate<`/CustomerName>
<`ActiveStatus>1<`/ActiveStatus>
<`/record>
<`record>
<`CustomerID>300<`/CustomerID>
<`CustomerName>Julia<`/CustomerName>
<`ActiveStatus>1<`/ActiveStatus>
<`/record>
<`record>
<`CustomerID>400<`/CustomerID>
<`CustomerName>Maddy<`/CustomerName>
<`ActiveStatus>0<`/ActiveStatus>
<`/record>
<`/data>
*/

SQL Server - vs - Oracle Functions

Many developers often ask about equivalent functions existing in various RDBMSs. I found the following link which is very useful to find technical comparison between functions of Oracle vs SQL Server.

Sunday, March 7, 2010

SQL Server - INSERT through Stored Procedure

There is one article in this blog in which we had discussed about how to use INSERT statement in various aspects. Here is one more example to insert the data into the table through a stored procedure.

/**************************/
/* Existing Table Data */
/**************************/
SELECT * FROM Customers

/**************************/
/* Procedure Creation */
/**************************/
CREATE PROCEDURE sampleProc (
@CustomerID INT,
@CustomerName VARCHAR(50),
@ActiveStatus INT)

AS


SELECT @CustomerID, @CustomerName, @ActiveStatus

**************************/
/* Procedure Ends Here*/
/**************************/


/**************************/
/* Insert Data */
/**************************/
INSERT INTO Customers
EXEC sampleProc 500, 'Harry', 1

Big Data & SQL

Hi Everybody, Please do visit my new blog that has much more information about Big Data and SQL. The site covers big data and almost all the...