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 sum across rows

I'm trying to make a query to obtain this result (Presto sql in case it's relevant) | State | Region | City | Sales-City | Sales-Region | Sales-State | |--------|----------|----------|------------|--------------|-------------| | Italy |…
ABO
  • 170
  • 1
  • 1
  • 10
1
vote
2 answers

Update latest record with previous record values

I have a table called Audits that has a CompanyId, Date, AuditNumber field, each Company can have many audits and the AuditNumber field keeps track of how many audits said company has. I'm trying to update all latest audit records date with it's…
SC.Cee
  • 237
  • 1
  • 4
  • 14
1
vote
1 answer

How to group data if difference between rows is mothe than 1 minute

Im trying to create a new table on SQL which will have summarized data. For example. In the original table i have this data: If you see rows 9, 10 and 11 they are consecutive, so i want to group them on one row with Begin: 2020-07-02…
Mathias
  • 19
  • 3
1
vote
3 answers

Using MAX to find the lastest time given other attribtues

Here's an example of the data set layout: https://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=b537554bb5e9dbde4f6c662fc302db5f I want to write a select query to get the last product that arrived for each Vendor, by date. Sample data: Line | date …
1
vote
1 answer

How to pick the next Datetime for same AgentID in SQL

The first column (CALL_START) is time on which somebody of some particular ID (CALLER_ID) made a call. see snippet of data here. Now I want to pick out the next call of the same ID and store it in a new column named as 'Next_call' and if there is no…
Chloe
  • 127
  • 1
  • 12
1
vote
1 answer

Partitioning rows into groups by accumulative time interval

I got a search sessions log that looks like this: +----------+-------------------------+----------+ | dt | search_time | searches | +----------+-------------------------+----------+ | 20200601 | 2020-06-01 00:36:38.000 | 1…
1
vote
1 answer

Check if sales-status in one country per campaign has changed and assign it to all countries per campaign in the results

DB-Fiddle: CREATE TABLE operations ( id int auto_increment primary key, campaign VARCHAR(255), country VARCHAR(255), sales_status VARCHAR(255), quantity INT ); INSERT INTO operations (campaign, country, sales_status,…
Michi
  • 4,663
  • 6
  • 33
  • 83
1
vote
1 answer

Create a new column from existing columns

I want to create a new column from this example table but with one more condition that so far I couldn't figure out, I want to create an average holdings column that's specific to each city. Name | City | Holdings Tom Jones | London | 42 …
1
vote
1 answer

How to filter on duration based on timestamp values

I want to filter records based on on the time interval but I have timestamps. I have a table 'df' with the following column names: id - int time - timestamp correctness - boolean subject - text Every student (id) completes tasks on particular…
Alex
  • 179
  • 10
1
vote
1 answer

SQL Trying To Find The Average of Just 1 Attribute

In SQL, I am trying to find and list the addresses of what houses have a greater rent than the average of the houses rent. So I have a PropertyForRent table which lists different houses and flats for rent. Heres that table: relation So far, I have…
1
vote
1 answer

Is there a way to alternate the order of a result based off one id while keeping groupings based off another id in SQL?

I have this query in Postgresql: (SELECT q.question, q.category_id, a.id, a.question_id, a.answer FROM questions q, answers a WHERE q.id = a.question_id AND category_id = 1 AND question_id BETWEEN (SELECT property FROM users…
1
vote
2 answers

SQL query to answer: If occurs in timepoint A, does occur in time period B-C?

I'm querying a large data set to figure out if a bunch of campaign events (i.e. event 1,2,..) during different timepoints gives a result in user activity (active, inactive) during the following 3 days after each event (but not in the same day as the…
Galaffer
  • 171
  • 2
  • 13
1
vote
3 answers

SQL - Count values in a column using criteria and partition by

I have the following data set that contains an animal and its vaccine date. I am trying to count at each record how many vaccines the pet has had in the past 90, 180, and 365 days via SQL. I am able to figure this out in Excel. Pasting the below…
AlmostThere
  • 557
  • 1
  • 11
  • 26
1
vote
1 answer

How to convert rows to columns group by multiple columns in Oracle sql

I have a table with data as below: a | b | c | d a | b | c | e a | b | c | f g | h | i | j g | h | i | k g | h | i | l I want to convert the data as below: a | b | c | d | e | f g | h | i | j | k | l Tried as below. But it didn't…
JPNagarajan
  • 802
  • 1
  • 12
  • 32
1
vote
2 answers

How to distribute ranks when prior rank is zero (part 2)

This is an extension to my prior question How to distribute values when prior rank is zero. The solution worked great for the postgres environment, but now I need to replicate to a databricks environment (spark sql). The question is the same as…