SQL Sunday Word Scramble

SQL Server – TSQL Analytics Word Search

ScrambleAnalytics

 

Find the following words in the word scramble above.

TOP

RANK

DENSE_RANK

ROW_NUMBER

NTILE

OVER

LAG

LEAD

FIRST_VALUE

LAST_VALUE

PERCENT_RANK

PERCENTILE_DISC

PERCENTILE_CONT

CUME_DIST

PARTITION

ROWS

PRECEDING

FOLLOWING

UNBOUNDED

 

Download the Printable PDF of the Word Search.

See Also

TOP, Ranking, NTILE, and Aggregate Functions

 

Continuing our weekly SQL Query Training for the 70-461 exam preparation, at Emergency Reporting, we are sharing this weeks class with the world. Free SQL Query training.

TOPRankingNTILEandAggregateFunctions

 

 

Here is the video of the training on TOP, Ranking, NTILE, and Aggregate Functions today. The first half was presented by Aaron Buma, and the second half I presented.

The following topics were covered in this session.

  • —TOP(N)
  • —RANK and DENSE_RANK
  • —ROW_NUMBER
  • —NTILE
  • —OVER clause enhancements
  • —LAG and LEAD,  FIRST_VALUE and LAST_VALUE
  • —PERCENT_RANK
  • —PERCENTILE_DISC and PERCENTILE_CONT
  • —CUME_DIST – Cumulative Distribution

Here is the zip file to download with slides and TSQL code.
TopRankingNtileAndAnalytics.zip.

 

See Also

Downloads for this weeks SQL Training

As posted earlier.

This weeks SQL Queries training for the 70-461 certification will be on Thursday at 9:00am (US pacific time). Please join the live broadcast on Google On Air Hangouts, or catch the recorded version on myYouTube Channel.

Aaron Buma will be presenting the first half of the session and I will be presenting the second half.

We will start off with all the features around the TOP(N) in your query, followed by using the RANK(), DENSE_RANK and ROW_NUMBER. Then on to Analytic Functions to help with your statistical analysis of data. Similar to aggregate functions, analytics functions compute over a group of rows with multiple results within each group. Learn how to properly use each of these analytics functions in combination with enhancements to the OVER clause. Learn the value of CUME_DIST and PERCENT_RANK in your analysis, use LAST_VALUE and FIRST_VALUE along with PERCENTILE_DISC, PERCENTILE_CONT, LEAD and LAG you can look at data in the next and previous rows.

 

Here is the download: TopRankingNtileAndAnalytics.zip

Check back in a day or two to get the edited video of the training.

Enjoy.

Rows and Range, Preceding and Following

SQL Server 2012 adds many new features to Transact SQL (T-SQL).  One of my favorites is the Rows/Range enhancements to the over clause. These enhancements are often times referred to as the windowing functions.

Overview:
ROWS PRECEDING, FOLLOWING, UNBOUNDED, refers to the current row and those before or after based on preceding or following.
RANGE PRECEDING, FOLLOWING, UNBOUNDED, means all values in the current range and those before or after.

An example of a need for rows preceding would be to calculate a 3 year trailing average, which needs to look at the current year and the three previous years in the calculation.

Terminology:
ROWS or RANGE- specifying rows or range.
PRECEDING – get rows before the current one.
FOLLOWING – get rows after the current one.
UNBOUNDED – when used with PRECEDING or FOLLOWING, it returns all before or after.
CURRENT ROW

To start out we need a database to work on, so we will create a tsql2012 database. you can use your own database if you wish.

CREATE DATABASE [tsql2012];
GO
USE [tsql2012];

Next we create a table to use for the over clause enhancments of rows and range preceding and following.

-- Table to be used by Over Clause Rows/Range

CREATE TABLE REVENUE
(
[DepartmentID] int,
[Revenue] int,
[Year] int
);

insert into REVENUE
values (1,10030,1998),(2,20000,1998),(3,40000,1998),
 (1,20000,1999),(2,60000,1999),(3,50000,1999),
 (1,40000,2000),(2,40000,2000),(3,60000,2000),
 (1,30000,2001),(2,30000,2001),(3,70000,2001),
 (1,90000,2002),(2,20000,2002),(3,80000,2002),
 (1,10300,2003),(2,1000,2003), (3,90000,2003),
 (1,10000,2004),(2,10000,2004),(3,10000,2004),
 (1,20000,2005),(2,20000,2005),(3,20000,2005),
 (1,40000,2006),(2,30000,2006),(3,30000,2006),
 (1,70000,2007),(2,40000,2007),(3,40000,2007),
 (1,50000,2008),(2,50000,2008),(3,50000,2008),
 (1,20000,2009),(2,60000,2009),(3,60000,2009),
 (1,30000,2010),(2,70000,2010),(3,70000,2010),
 (1,80000,2011),(2,80000,2011),(3,80000,2011),
 (1,10000,2012),(2,90000,2012),(3,90000,2012);

Take a look at the revenue table to see whats there before we start the demo.


USE [tsql2012];

-- first lets look at the REVENUE table

SELECT *
 FROM Revenue;

rows_range_preceding_following1
Contents of the REVENUE table.

Then a quick review of sum and avg.

-- first simple sum and avg aggregates
SELECT sum(Revenue) as TotalRevenue,
 avg(Revenue) as AverageRevenue,
 count(*) as NumRows
 FROM Revenue;

rows_range_preceding_following2

OVER Clause Pre SQL Server 2012

The OVER clause before SQL Server 2012 is really handy to perform aggregates over a different range than your standard grouping.

--First OVER Clause pre SQL 2012
SELECT *,
 avg(Revenue) OVER (PARTITION by DepartmentID) as AverageDeptRevenue,
 sum(Revenue) OVER (PARTITION by DepartmentID) as TotalDeptRevenue
FROM REVENUE
ORDER BY departmentID, year;

rows_range_preceding_following3

ROWS PRECEDING

Now the new features, ROWS PRECEDING specifies the the aggregate functions in the current partition in the OVER clause will consider the current row, and a specific number of rows before the current row.


--ROWS PRECEDING
-- look at the sum of revenue over a trailing 3 year period
SELECT Year, DepartmentID, Revenue,
 sum(Revenue) OVER (PARTITION by DepartmentID
 ORDER BY [YEAR]
 ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) as CurrentAndPrev3
FROM REVENUE
ORDER BY departmentID, year;

rows_range_preceding_following4

ROWS FOLLOWING

Now rows following… The ROWS FOLLOWING option specifies a specific number of rows in the current partition to use after the current row.

-- ROWS FOLLOWING
SELECT Year, DepartmentID, Revenue,
 sum(Revenue) OVER (PARTITION by DepartmentID
 ORDER BY [YEAR]
 ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING) as CurrentAndNext3
FROM REVENUE
ORDER BY departmentID, year;

rows_range_preceding_following5

Both PRECEDING and FOLLOWING

Using both ROWS PRECEDING and ROWS FOLLOWING allows you to do things like calculate an average including the current year and years both before and after the current year.


--ROWS PRECEDING AND FOLLOWING

SELECT Year, DepartmentID, Revenue,
 sum(Revenue) OVER (PARTITION by DepartmentID
 ORDER BY [YEAR]
 ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) as BeforeAndAfter
FROM REVENUE
ORDER BY departmentID, year;

rows_range_preceding_following6

UNBOUNDED

UNBOUNDED PRECEDING tells the windowing function and aggregrates to use the current value, and all values in the partition before the current value.

-- ROWS UNBOUNDED PRECEDING
SELECT Year, DepartmentID, Revenue,
 min(Revenue) OVER (PARTITION by DepartmentID
 ORDER BY [YEAR]
 ROWS UNBOUNDED PRECEDING) as MinRevenueToDate
FROM REVENUE
ORDER BY departmentID, year;

rows_range_preceding_following7

When using UNBOUNDED FOLLOWING as follows, this means the use the current row, and consider all rows after the current row in the current partition.

-- ROWS UNBOUNDED FOLLOWING
-- http://stevestedman.com/?p=1485
SELECT Year, DepartmentID, Revenue,
 min(Revenue) OVER (PARTITION by DepartmentID
 ORDER BY [YEAR]
 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) as MinRevenueBeyond
FROM REVENUE
ORDER BY departmentID, year;

rows_range_preceding_following8

ROWS vs RANGE

ROWS vs RANGE appears to cause much confusion.

ROWS means the specific row or rows specified, and RANGE refers to those same rows plus any others that have the same matching values.

Here is an example of ROWS and RANGE producing the exact same results because the years and department IDs don’t have any duplicates. In this case the ROWS and RANGE are identical.

-- ROWS vs RANGE UNBOUNDED PRECEDING

SELECT Year, DepartmentID, Revenue,
 sum(Revenue) OVER (PARTITION by DepartmentID
 ORDER BY [YEAR]
 ROWS UNBOUNDED PRECEDING) as RowsCumulative,
 sum(Revenue) OVER (PARTITION by DepartmentID
 ORDER BY [YEAR]
 RANGE UNBOUNDED PRECEDING) as RangeCumulative
FROM REVENUE
WHERE year between 2003 and 2008
ORDER BY departmentID, year;

rows_range_preceding_following9

Now if we consider the same query of ROWS vs RANGE with duplicate values. Here we insert a duplicate set of values for 2005, and the results below show that for the year 2005 there are two rows in the result set, and the RowsCumulative column is different form the RangeCumulative.  The rows counts the specific rows it the aggregate calculation, the range counts the current row, plus the other 2005 rows for that department id.

-- INSERT A DUPLICATE VALUE FOR RANGE UNBOUNDED PRECEEDING

INSERT INTO REVENUE
VALUES (1,10000,2005),(2,20000,2005),(3,30000,2005);

-- same query as above
SELECT Year, DepartmentID, Revenue,
 sum(Revenue) OVER (PARTITION by DepartmentID
 ORDER BY [YEAR]
 ROWS UNBOUNDED PRECEDING) as RowsCumulative,
 sum(Revenue) OVER (PARTITION by DepartmentID
 ORDER BY [YEAR]
 RANGE UNBOUNDED PRECEDING) as RangeCumulative
FROM REVENUE
WHERE year between 2003 and 2008
ORDER BY departmentID, year;

rows_range_preceding_following10

Summary

With all the great new features in SQL Server 2012, the windowing functions, ROWS and RANGE, PRECEDING and FOLLOWING updates to the OVER clause are a great addition.

Home after Seattle (Redmond) Code Camp 2012

What a great day at  Code Camp today.

Click here to download the slides and sample code from the presentations.

The first presentation that I attended was  Accelerating your Development Workflow presentation by Ian Davis.  What a great presentation, it touched on the lean and agile development processes, it was very well done.

The next one was a PowerShell presentation that was okay, then I presented the following three sessions.

What’s New in TSQL 2012

Unleashing Common Table Expressions in SQL Server

The CTE presentation is currently my most polished presentation, it was first presented at SQLSaturday in Redmond a few months back.

SQL Server Performance for Developers

I hope that everyone who attended had a great time, and learned something new!

Code Camp in Redmond Today—

I am headed to Code Camp in Redmond WA today.  I ended up with 3 sessions that I will be presenting, and I am really looking forward to the day.

I am looking forward to attending the Accelerating your Development Workflow presentation by Ian Davis.

Here is what I am presenting…

What’s New in TSQL 2012

This is the first time that I will be presenting this one.  Its going to be a lot of fun working with the new features in TSQL 2012.

Here is the summary of what I will be covering:

Unleashing Common Table Expressions in SQL Server

This will be about the 5th time I have used this presentation.  Just some quick polish and it will be ready to go.  I recently presented this session at SQL Saturday in Redmond and SQL Saturday in Vancouver BC.  One new addition to this session is the performance comparison between the SQL Server 2012 OFFSET/FETCH functionality and the data paging capability of a CTE.

Here is the outline of the presentation:

SQL Server Performance for Developers

Probably one of the most valuable database sessions for developers, although until you have experience bad performance with SQL Server it’s a hard sell.

  • —Is Tuning Necessary for the Developer
  • —Understanding Tables and Indexes
  • —Understanding Execution Plans
  • —Statistics IO and TIME
  • —Understanding Table Size
  • —Procedure Cache and Parameterization
  • —Seven Deadly Sins
    • —Poor or No Database Design
    • —Index Design Issues
    • —RBAR instead of Sets
    • —Not using explicit column lists
    • —Calculations in the WHERE Clause
    • —Dirty Reads
    • —Believing Moore’s Law Will Save You
  • —Tips For Writing Queries

Code Camp is today in Redmond WA, I hope to see you there.