Questions tagged [window-functions]

A function that partitions a result set and computes something within that partition without rolling up the data in that partition.

A window function partitions a row set into blocks based on some grouping but does not roll up into that grouping. A local calculation can be done within that group that will reset when the system processes the next group.

The SQL syntax for a window function takes the form:

calculation()
   over (partition by foo,
         order by bar)

The order by clause is optional, but sorts rows within a partition. This can be useful for calculations that should reset across partitions. For example, one could use the windowing function to apply a row number for sorting within the partition or to calculate a running sum within that partition based a date ordering.

The partition by clause in the window function differs from the group by clause in SQL in that it does not actually aggregate the data in the partitions.

344 questions
63
votes
6 answers

Date range rolling sum using window functions

I need to calculate a rolling sum over a date range. To illustrate, using the AdventureWorks sample database, the following hypothetical syntax would do exactly what I need: SELECT TH.ProductID, TH.TransactionDate, TH.ActualCost, …
31
votes
2 answers

MySQL and window functions

It seems that MySQL does not support window functions. E.g. the simple: COUNT(*) OVER() AS cnt does not work. What I am not sure is if this applies to commercial version as well (I assume the community version is limited subset). If not, how does…
Cratylus
  • 1,013
  • 3
  • 12
  • 18
27
votes
4 answers

Limit results to the first 2 ranking rows

In SQL Server 2008, I am using RANK() OVER (PARTITION BY Col2 ORDER BY Col3 DESC) to return data set with RANK. But I have hundreds of records for each partition, so I will get values from rank 1, 2, 3......999. But I want only up to 2 RANKs in each…
UB01
  • 947
  • 2
  • 9
  • 18
26
votes
1 answer

Rolling sum / count / average over date interval

In a database of transactions spanning 1,000s of entities over 18 months, I would like to run a query to group every possible 30-day period by entity_id with a SUM of their transaction amounts and COUNT of their transactions in that 30-day period,…
tufelkinder
  • 363
  • 1
  • 3
  • 7
25
votes
5 answers

Using DISTINCT in window function with OVER

I'm trying to migrate a query from Oracle to SQL Server 2014. Here is my query which works great in Oracle: select count(distinct A) over (partition by B) / count(*) over() as A_B from MyTable Here is the error i got after tried to run this query…
Omri
  • 383
  • 1
  • 5
  • 17
21
votes
6 answers

Find "n" consecutive free numbers from table

I have some table with numbers like this (status is either FREE or ASSIGNED) id_set number status ----------------------- 1 000001 ASSIGNED 1 000002 FREE 1 000003 ASSIGNED 1 000004 FREE 1 000005 FREE 1 …
boobiq
  • 827
  • 3
  • 9
  • 13
21
votes
1 answer

Performance comparison between using Join and Window function to get lead and lag values

I have a table with 20M rows, and each row has 3 columns: time, id, and value. For each id and time, there is a value for the status. I want to know the lead and lag values of a certain time for a specific id. I have used two methods to achieve…
20
votes
2 answers

What is the difference between COUNT(*) and COUNT(*) OVER()

Take the following code example: SELECT MaritalStatus, COUNT(*) AS CountResult COUNT(*) OVER() AS CountOverResult FROM (schema).(table) GROUP BY Marital Status COUNT(*) Returns all rows ignoring nulls right? What does…
David Folksman
  • 769
  • 3
  • 8
  • 13
20
votes
7 answers

Form groups of consecutive rows with same value

I have a situation I think can be solved using window function but I'm not sure. Imagine the following table CREATE TABLE tmp ( date timestamp , id_type integer ) ; INSERT INTO tmp (date, id_type) VALUES ( '2017-01-10 07:19:21.0', 3 ), (…
18
votes
2 answers

Using window function to carry forward first non-null value in a partition

Consider a table that records visits create table visits ( person varchar(10), ts timestamp, somevalue varchar(10) ) Consider this example data (timestamp simplified as counter) ts| person | somevalue ------------------------- 1 | bob …
maxTrialfire
  • 1,194
  • 4
  • 11
  • 23
17
votes
1 answer

Running total to the previous row

I need some help with windowing functions. I know you can calculate the sum within a window and the running total within a window. But is it possible to calculate the previous running total i.e. the running total not including the current row? I…
Steve
  • 483
  • 2
  • 5
  • 10
14
votes
2 answers

Select longest continuous sequence

I am trying to construct a query in PostgreSQL 9.0 that gets the longest sequence of continuous rows for a specific column. Consider the following table: lap_id (serial), lap_no (int), car_type (enum), race_id (int FK) Where lap_no is unique for…
DaveB
  • 319
  • 2
  • 6
  • 16
14
votes
3 answers

How to get the last not-null value in an ordered column of a huge table?

I have the following input: id | value ----+------- 1 | 136 2 | NULL 3 | 650 4 | NULL 5 | NULL 6 | NULL 7 | 954 8 | NULL 9 | 104 10 | NULL I expect the following result: id | value ----+------- 1 | 136 2 |…
peterh
  • 2,137
  • 8
  • 28
  • 41
13
votes
3 answers

Calculate rolling sum over 7 consecutive day period on PostgreSQL

I need to get the rolling sum over a period of 7 days for each row (1 row per day). For example: | Date | Count | 7-Day Rolling Sum | ------------------------------------------ | 2016-02-01 | 1 | 1 | 2016-02-02 | 1 | 2 | 2016-02-03 | 2…
josesigna
  • 233
  • 1
  • 2
  • 6
13
votes
1 answer

Combine two event tables into a single timeline

Given two tables: CREATE TABLE foo (ts timestamp, foo text); CREATE TABLE bar (ts timestamp, bar text); I wish to write a query that returns values for ts, foo, and bar that represents a unified view of the most recent values. In other words, if…
1
2 3
22 23