SQL 2012:usage of New Functions: Asanka Padmakumara
SQL 2012:usage of New Functions: Asanka Padmakumara
NEW FUNCTIONS
Asanka Padmakumara
Senior BI Engineer
(CAMMS Group)
Finding the trend??? (2008)
WITH CTE AS (
SELECT rownum = ROW_NUMBER() OVER (order by
WorkOrderID),OrderQtyFROM
[AdventureWorks].[Production].[WorkOrder])
SELECT CASEWHEN CTE.OrderQty-PREVCTE.OrderQty >0 THEN 'UP'
WHEN CTE.OrderQty-PREVCTE.OrderQty <0 THEN 'DOWN'
ELSE 'NA'
END AS Trand
FROM CTELEFT OUTER JOIN CTE AS PREVCTE ON
PREVCTE.rownum = CTE.rownum – 1
Finding the trend??? (2012)
SELECT CASE
WHEN OrderQty-LAG(OrderQty) OVER(order by WorkOrderID)>0 THEN 'UP'
WHEN OrderQty-LAG(OrderQty) OVER(order by WorkOrderID)<0 THEN
'DOWN'
ELSE 'NA' END AS Trand FROM [AdventureWorks].[Production].[WorkOrder]
LAG and LEAD
No longer need to use a self-join or CTE.
LAG: Access data from previous rows in the result set.
LEAD: Access data from future rows in the result set.
About Performance ???
I used LAG to rewrite a self-join query and besides being
much smaller and simpler, the query time dropped from 2.6
sec to 1 sec. (Or from 40 sec to 1 sec if you count the bad
behavior of the query optimizer). Obviously this is just one
anecdote, but the performance difference was shocking and
highly convincing to me. – agentnega
http://stackoverflow.com/questions/12953231/lag-and-lead-
functions
Paging a result set
Start with 0, Page Size:20
WITH Paging_CTE AS ( SELECT TransactionID , ProductID ,
TransactionDate , Quantity , ActualCost , ROW_NUMBER()
OVER (ORDER BY TransactionDate DESC) AS RowNumber
FROM Production.TransactionHistory ) SELECT
TransactionID , ProductID , TransactionDate , Quantity ,
ActualCost FROM Paging_CTE WHERE RowNumber > 0
AND RowNumber <= 20
Paging a result set
SELECT TransactionID , ProductID , TransactionDate , Quantity ,
ActualCost FROM Production.TransactionHistory ORDER BY
TransactionDate DESC OFFSET 0 ROWS FETCH NEXT 20 ROWS ONLY
OFFSET FETCH
OFFSET provides a starting row from which to display the result set.
FETCH instructs the query to display the number of rows you want in your result set
from the OFFSET point
FIRST_VALUE and LAST_VALUE
FIRST_VALUE: Retrieves the first value
in a partition.
LAST_VALUE: Retrieves the last value
in a partition.