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 Server - ROW_NUMBER() with PARTITION, how to get multiple records?

I'm struggling with my query SELECT * FROM ( SELECT ins.ID, ins.UnitElement_ID, ins.Date, ue.Code, ROW_NUMBER() OVER (PARTITION BY ins.UnitElement_ID ORDER BY ins.Date DESC) AS lastAnomaly FROM Inspection ins INNER JOIN…
1
vote
1 answer

Is there an idiom for querying sequences in SQL?

I'm studying to interview for a job involving a lot of SQL. I've noticed a few exercises that revolve around returning values based on a sequence across rows, and I would love to know if there's a standard way of doing this. Something akin to the…
spheroidic
  • 199
  • 7
1
vote
1 answer

How to update table with field Postgres

I have table like this: Incident_id is foreign key. What I want to achieve it -> create one more column with named position (int). And populate it like this: find all rows for each incident_id and and update each row with index or list of rows I…
1
vote
1 answer

Limit to N number with one-to-many relationship

I'm looking for a way to return 100 unique events which are correlated with several records from another table. Normally I would use TOP to return a certain number of records, but I'm dealing with a one-to-many join. For example, in the included…
Arysta
  • 13
  • 2
1
vote
1 answer

Count rows with equal values in a window function

I have a time series in a SQLite Database and want to analyze it. The important part of the time series consists of a column with different but not unique string values. I want to do something like this: Value concat countValue A A 1 A…
1
vote
4 answers

Oracle SQL or PLSQL. Select rows by partitions which values have specific order

Task: select sportsmen who participate in at least 2 competitions in a row (2 competitions go one after another; 1-2-3-4-5: 2&4 or 1&3&5 are not ok, 1&2 is ok, 1&2&3 is ok, 1&2 and 4&5 is ok). Question: find the best way (faster, less…
void_eater
  • 113
  • 1
  • 3
  • 9
1
vote
2 answers

SQL: Difference between consecutive rows

Table with 3 columns: order id, member id, order date Need to pull the distribution of orders broken down by No. of days b/w 2 consecutive orders by member id What I have is this: SELECT a1.member_id, count(distinct a1.order_id) as num_orders,…
RashItIs
  • 87
  • 1
  • 1
  • 10
1
vote
2 answers

Can I use SQL to Sum() and/or count() for all elements in the group except for the returned category?

I have a table of data. Column 1 is a list of categories, and column 2 is a boolean. I have N number of categories, with N number of rows per category. I would like to return a table with the data grouped by category, and summary of the number of…
1
vote
2 answers

Numbering dates from Sunday to Saturday

Does anyone have a easy solution to make a numbering from sunday to saturday and generate the dates in PostgreSQL(version 11).I have the below solution but it is limited to only 5 weeks and i need something that is flexible. I have dates as a column…
Sandeep
  • 671
  • 2
  • 7
  • 30
1
vote
1 answer

MySQL 5.7.24 COUNT() does not work correctly with sql_mode=only_full_group_by

I'm trying to figure out the appropriate way of returning the posts & the total number of posts of a user in one query. So the simplest way of counting the total number of posts of a user would be: SELECT COUNT(id) as total FROM posts WHERE uID =…
Csaba
  • 1,945
  • 3
  • 28
  • 46
1
vote
3 answers

SQL Pivot multiple columns without forcing aggregate

I need to pivot out some denormalized data but it repeats so I need it to pivot out the columns and then return multiple rows. I have a table like this INSERT #TheTable VALUES ('StockCode' ,'a'), ('Warehouse' ,'b'), …
1
vote
1 answer

FIRST & LAST values in Oracle SQL

I am having trouble querying some data. The table I am trying to pull the data from is a LOG table, where I would like to see changes in the values next to each other (example…
llorcs
  • 79
  • 1
  • 10
1
vote
2 answers

mysql - Get records with max value for each group of grouped SQL results

I´m refering to this post from Yarin in 2012. this won't work anymore, im using mysql v 8.0.19 Given a table like that below, with person, group, and age columns, how would you get the oldest person in each group? (A tie within a group should give…
NeoGER89
  • 412
  • 4
  • 16
1
vote
1 answer

How to do complex COUNT()

On my quest to learn basic SQL I got stuck on this task: I need to find and count every instance where product prices differ by at most one (Including the product you are comparing) From this example: PRODUCTS +-----------+------------+ | name …
HuManatee
  • 67
  • 5
1
vote
1 answer

How do you calculate the minimum number of sales it took to reach a sales goal of 100 for each month?

Write a query to find out how many sales at a minimum it took each month to reach a cumulative sale of more than 100. Table Code: DROP TABLE IF EXISTS q1sales; CREATE TABLE q1sales ( year double precision, month integer, sales integer ); INSERT…