Sunday, July 29, 2018

Over Clause

Without using Group by you can take the count by 
===================================
SELECT  object_id, index_id, COUNT(*) OVER ()
FROM [msdb].sys.indexes;



Count base on the Object ID
===================================
SELECT object_id, index_id, COUNT(*) OVER (PARTITION BY object_id) FROM [msdb].sys.indexes;

Good example

DECLARE @Test TABLE ( Account INTEGER, TranDate DATE, TranAmount NUMERIC(5,2)); 

 INSERT INTO @Test (Account, TranDate, TranAmount) VALUES (1, '2015-01-01', 50.00), (1, '2015-01-15', 25.00), (1, '2015-02-01', 50.00), (1, '2015-02-15', 25.00), (2, '2015-01-01', 50.00), (2, '2015-01-15', 25.00), (2, '2015-02-01', 50.00), (2, '2015-02-15', 25.00); 

 SELECT Account, TranDate, TranAmount, COUNT(*) OVER (PARTITION BY Account ORDER BY TranDate ROWS UNBOUNDED PRECEDING) AS RowNbr, COUNT(*) OVER (PARTITION BY TranDate) AS DateCount, COUNT(*) OVER (PARTITION BY Account ORDER BY TranDate ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS Last2Count FROM @Test ORDER BY Account, TranDate;

Referd by: http://www.sqlservercentral.com/articles/over+clause/132079/

No comments:

Post a Comment

Postgress - Read a XML file from a postgress table XML column

SELECT xmltable.* FROM xmldata, XMLTABLE('//ROWS/ROW' PASSING data COLUMNS id int PATH ...