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
1 answer

SQL PIVOT-WINDOW FUNCTIONS

With the sql query I get table 1 with t as(QUERY) select Date, key, Type, row_number ( ) over(partition by key order by Date asc) orders from t table 1 Date Key Type orders 12/10/2007 7 Q1 1 30/06/2015 7 W 2 21/06/2019 …
wwnde
  • 26,119
  • 6
  • 18
  • 32
1
vote
1 answer

SQL to add position depending on multiple columns

I have a table that I am adding a position column in. I will need to add a numbered position to all rows already in the table. The numbering depends on 4 columns that would match each other between rows. For example id| name| fax | cart| area |…
Sol
  • 57
  • 6
1
vote
1 answer

Wider dataset in posgresql - SQL

I have the following table: CREATE TABLE my_table ( the_debt_id varchar(6) NOT NULL, the_debt_paid date NOT NULL, the_debt_due date NOT NULL ) INSERT INTO my_table VALUES ('LMUS01', '2019-05-03', '2019-05-02'), ('LMUS01',…
Manu
  • 1,070
  • 10
  • 27
1
vote
2 answers

SQL query to find continuous local max, min of date based on category column

I have the following data set Customer_ID Category FROM_DATE TO_DATE 1 5 1/1/2000 12/31/2001 1 6 1/1/2002 12/31/2003 1 5 1/1/2004 12/31/2005 2 …
GHM11O
  • 11
  • 1
1
vote
1 answer

Bucketing Data, If Bucket Size Greater Then 1 Set Value To 1 Else 0

I'm using snowflake to attempt to bucket rows based on two columns and if that bucket size is greater then 1 then I need the value of of some new column to be 1, otherwise I would set it to 0. It's similar to NTILE() except that I would need this to…
Lukasz
  • 2,476
  • 10
  • 41
  • 51
1
vote
2 answers

PostgreSQL assigning random, non-repeating values

I have a table of students that looks like this: firstname | id ----------------+---- Student1 | 1 Student2 | 2 Student3 | 3 Student4 | 4 Student5 | 5 Student6 | 6 Student7 | 7 Student8…
JedO
  • 133
  • 5
1
vote
2 answers

mysql simple moving average in last N hours

There is a cron job that populates the rate every 5 minutes in the following table, Would appreciate some pointers on how to get the simple moving average in the last 6 hours of the rate column The SQL table looks as follows: id rate …
maximus 69
  • 1,388
  • 4
  • 22
  • 35
1
vote
2 answers

get the range of sequence values in table column

I have a list of value in my column. And want to query the range. Eg. If values are 1,2,3,4,5,9,11,12,13,14,17,18,19 I want to display 1-5,9,11-14,17-19
Zen
  • 21
  • 7
1
vote
2 answers

How can I add a new calculated column using a window function to my SQL query?

I have data that looks like this: Trader Name | Currency_Code | Counterparty | Traded_Amount | Total_Traded_Volume | Baseline_Avg | Variance Jules Winnfield | GBP | GOLD | 10000 | 30000 | 10000 |…
1
vote
2 answers

Cross Join in Hive

I'm trying to create a new column time_period while running the query below. If the date difference between a given transaction and the most recent transaction in the reference table is fewer than 7 days, then mark it as a recent transaction, else…
Caerus
  • 674
  • 1
  • 8
  • 19
1
vote
1 answer

Values across multiple rows brought into one row (separate cells) if rows have matching IDs. NULL values if ID only exists once

Relatively new to Window Functions but I'm pretty sure that's what is needed here. I'm trying to combine two or more rows returned in a dataset that share the same ID/dense_rank into one row. If there are IDs in the dataset that do not have matches…
1
vote
2 answers

Using count(*) .. Over(*) in mysql

My data looks like the following, requestedDate Status 2020-04-21 APPROVED 2020-04-23 APPROVED 2020-04-27 PENDING 2020-05-21 PENDING 2020-06-01 APPROVED I would like to extarct a…
Bisoux
  • 532
  • 6
  • 18
1
vote
5 answers

MySQL 8 - Calculating Year-over-Year Metrics

I've been trying to calculate year over year growth for monthly returns and have been rewriting the same queries for hours with no luck. I've seen solutions but they're all other database solutions. I'm trying to basically achieve something like the…
Jonathan Bird
  • 313
  • 5
  • 19
1
vote
1 answer

How to count by referring date in sql

I have tables like following. table product customer surrender_date A a 2020/5/1 B a 2020/6/1 C b 2019/7/1 D b 2020/8/1 E b 2020/9/1 First I'd like to group by…
Heisenberg
  • 4,787
  • 9
  • 47
  • 76
1
vote
1 answer

MySQL: Difference outputs from group by and partition by with dense_rank() over()?

I was doing a MySQL question on Leetcode.(link: https://leetcode.com/problems/get-highest-answer-rate-question/) The question is to find the maximum. I used order by + limit 1 to get the answer. But what if there are multiple maximum? Limit 1 will…
Squirrel K
  • 25
  • 3