DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE
 
 
SITE SEARCH SQLUSA.com VIDEOS
 
 
SQL E/BOOKS   WORLD, USA & SQL NEWS   FORMAT
SCRIPTS SQL 2005 SQL 2008 ARTICLES
How to architect dynamic ORDER BY?

Execute the following Microsoft SQL Server T-SQL script in Management Studio Query Editor to demonstrate the use of dynamic sorting on multiple columns.

-- SQL dynamic sorting - SQL sort multiple columns - ORDER BY CASE

-- SQL dynamic order by - SQL case function - SQL rank function - SQL select query

USE AdventureWorks;

SELECT   ContactID,

         FirstName,

         LastName,

         Title = COALESCE(Title,'')

FROM     Person.Contact

WHERE    LEFT(FirstName,1) = 'M'

ORDER BY CASE

           WHEN LEFT(LastName,1) = 'A' THEN RANK()

                                 OVER(ORDER BY FirstName + LastName)

           WHEN LEFT(LastName,1) = 'M' THEN RANK()

                                 OVER(ORDER BY LastName + ', ' + FirstName, Title)

           WHEN LEFT(LastName,1) = 'U' THEN RANK()

                                 OVER(ORDER BY LastName + ', ' + FirstName DESC)

           ELSE RANK()

                                 OVER(ORDER BY LastName DESC, FirstName DESC)

         END

GO

/* Partial results

 

ContactID   FirstName   LastName

1214        Michael     Zwilling

994         Michael     Zwilling

1372        Marc        Zimmerman

9500        Mackenzie   Adams

10144       Mackenzie   Allen

4558        Micah       Zhu

10241       Marshall    Zhu

*/

Exam Prep 70-461
SQL 2016 DESIGN & PROGRAMMING
 
 
 
DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE