Questions tagged [window-functions]

A window function is a type of SQL operation that aggregates over a partition of the result set.

As a basic example of a window function, consider a table that contains a list persons along with their age and gender.
If you wanted a query to return the complete list of people along with their age rank per gender, you could accomplish this most simply by using a ranking window function.
Such a function can be used to rank individual rows within a subset of the results.

Using a window function the above function would look like this:

SELECT name, 
       age, 
       gender, 
       RANK() OVER (PARTITION BY gender ORDER BY age DESC) AS age_rank
FROM persons

Window functions as defined by the SQL standard can also access rows before and after the current row using the lag() or lead() function. The following query calculates the delta to the previous row for the amount column for each customer:

SELECT customer_id,
       order_date,
       amount, 
       amount - lag(amount) over (partition by customer_id ORDER BY order_date) as delta
FROM order
ORDER BY customer_id, order_date;

Standard aggregates (e.g. count(), sum()) can also be used as a window function. If combined with an ORDER BY (inside the partition defintion) this will generate "running" totals based on the aggregate being used.

Window functions are available in a wide range of DBMS: Oracle (called "analytical functions" there), Microsoft SQL Server, DB2 (called "olap functions" there) PostgreSQL, Teradata, Sybase, Vertica, and partially in H2 Database.

4082 questions
1
vote
2 answers

SQL - Partition restarted based on a column value

I need to create a new column that restarts at every 0 value of Column Repeated Call of each Customer_ID: +-------------+---------+----------------------+---------------+ | Customer_ID | Call_ID | Days Since Last Call | Repeated Call…
Dan Pham
  • 107
  • 6
1
vote
1 answer

How to use MYSQL to include missing rows in final table with default 0 values for all columns?

This question is part of a bigger mySQL query I have. So I have a table of 'playerIds', 'dates', 'scores' and 'problems'. It's Table T0 in the image attached. I am running a SQL query on it to get the most-recent row for all players where the…
1
vote
4 answers

Oracle SQL Hierarchy Summation

I have a table TRANS that contains the following records: TRANS_ID TRANS_DT QTY 1 01-Aug-2020 5 1 01-Aug-2020 1 1 03-Aug-2020 2 2 02-Aug-2020 1 The expected output: TRANS_ID TRANS_DT BEGBAL TOTAL END_BAL…
1
vote
1 answer

Is there a way to fill in missing data points with NULL in SQL VIEWs?

I have a table called measurement_stat that takes the following form: id sensor_name timestamp value_cal 1 measurement_status 2020-07-28 16:00:00 start_measurement 2 measurement_status 2020-07-28 17:00:00 …
1
vote
2 answers

Calculating moving average over irregular data

I am trying to calculate a moving average of several fields in a SQL Server database that involved irregularly-spaced values over time. I realized that for regularly-spaced data I can use an SELECT grp, AVG(count) FROM t ... OVER (PARTITION BY grp…
Chris Fonnesbeck
  • 4,143
  • 4
  • 29
  • 30
1
vote
3 answers

Using code to increment values in a column

I am trying to use a simple code to increment only the values in the “chat_id” column of a table. For the table lz_chat_archive_dup1, the column “chat_id” is has empty strings (no values). This is the partial excerpt of the table : mysql> select…
anaigini
  • 11
  • 2
1
vote
1 answer

Using window function to retrieve values from a column depending on another

In a dataframe like below: id date product 1 2010-02-01 c 1 2010-02-02 v 1 2010-02-03 d 1 2010-02-04 g 2 2010-02-03 h 2 2010-02-04 w 2 2010-02-05 t 2 2010-02-06 d 3 2010-02-04 x 3 …
realkes
  • 833
  • 1
  • 12
  • 20
1
vote
4 answers

Pull non blank from previous row

I have data as below (first 3 columns). I would like to create the 4th column - newstatus. Logic for the newstatus column is that for each pk2 if column status is blank then pull value from the most recent row where status is either new or…
user2543622
  • 5,760
  • 25
  • 91
  • 159
1
vote
1 answer

SQL query to put a number in a column and put an incremented number when there is a new text in a column

I have a query SELECT * from TABLE which gives the result as below table: Expected column is as below: I want to frame a new column like whenever we get the value as 0 then the number should be incremented by 1. I tried DENSE_RANK() , ROW_NUMBER()…
1
vote
3 answers

How would I conditionally insert a row based on the previous row?

I'm currently trying to figure out how I can conditionally insert a row based on a previous row. I'm fairly used to using window functions, and I figure I'll have to do so to make this work, but I don't know any other functions to make this…
1
vote
1 answer

H2 database : Error when using window function inside CTE

Using H2 database (version 1.4.200) I've encountered really strange error with usage of window functions inside CTE. When I include window function field into CTE and OVER() clause is empty it works correctly, but when I try to add ORDER…
Andrew M
  • 11
  • 3
1
vote
2 answers

partition by returns duplicate rows

Let's say I have a weather table: MONTH, DAY, LOW 6, 1, 67.47084426063374 6, 2, 66.90195288599919 6, 3, 62.16084275276963 I want to select the avg low temperature for the month and am trying this: SELECT t.* FROM ( select p.month, avg(p.low)…
mrcrag
  • 310
  • 3
  • 16
1
vote
1 answer

SQL solution to assign a group number to a set of repeated values

I have a table with columns for Customer, Order, Fruit, and Quantity, sorted by Customer and Order. I need to assign the example Desired Group Number values sequentially, starting at 1, assigning the same value until the Fruit changes and then…
Allan
  • 15
  • 3
1
vote
2 answers

window function based on condition

Input table is as follows: column1 column2 column3 column4 230 8979 abc mno 228 8979 abc mno 227 6578 abc mno 226 …
Raven Smith
  • 83
  • 1
  • 6
1
vote
2 answers

How to insert a value from another row into a column - SQL Server

I'm working on SQL for a project, I need to update Soh_Wh_A and Soh_Wh_B based on some rules. This is table_A: | Code | Warehouse | StockOnHand | Wh_A | Wh_B ---------------------------------------------------- | 001 | A | 10 …
1 2 3
99
100