Questions tagged [window-functions]

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

Filter by
Sorted by
Tagged with
0 votes
0 answers
14 views

How to rank over result of window function in postgres efficiently?

I have a db table like shown below: Table "public.counters_by_app_category_app" Column | Type | ...
dimitris lepipas's user avatar
0 votes
2 answers
61 views

Fill missing values in a ratio table based on ProvinceNo(Branch)?

IF OBJECT_ID('tempdb..#ReflectionRatio') IS NOT NULL DROP TABLE #ReflectionRatio CREATE TABLE #ReflectionRatio( [ReflectionRatioKey] [int] IDENTITY(1,1) NOT NULL, [StartDate] [date] NULL, [...
Ozan Sen's user avatar
  • 2,527
-1 votes
1 answer
29 views

BigQuery - How can I compute an average window by window?

I have a table looking this: I am trying to compute an average number of orders for each client, every 3 month. I am not looking to compute a moving average month by month but an average of the ...
Grégoire de Kermel's user avatar
0 votes
2 answers
19 views

aggregate function with Window functions vs aggregate function with Group By [closed]

Can anyone explain me the actual difference between the window functions and Group by, like how the things work internally when we try to do sum using window functions and group by. Which one works ...
Likhith Chakravarthi K C's user avatar
0 votes
1 answer
15 views

how to order a series of date column over a row in redshift?

I have this table where there are so many date column in the table. row date_a date_b date_c date_d date_x 1 2023-07-18 2023-07-19 2023-07-22 2023-07-24 2023-07-20 2 2023-...
nomnom3214's user avatar
0 votes
1 answer
27 views

Count previous null values in redshift

I have a table that is sorted by the 'date' column date value 1/1/2023 10 1/2/2023 1/3/2023 1/4/2023 20 1/5/2023 1/6/2023 40 1/7/2023 42 1/8/2023 3 1/9/2023 1/10/2023 1 I want to create a ...
Woody's user avatar
  • 77
0 votes
1 answer
21 views

Not in aggregate function or group by clause but summing column in a window function

I'm getting the following error when trying to run the code below however usedslots is in a sum function. Column '#temp.UsedSlots' is invalid in the select list because it is not contained in either ...
Shadocvao's user avatar
0 votes
1 answer
49 views

Max interval between occurrences of two values - Spark

I have a spark dataframe in the format below. I wanted to calculate the max travel streaks to other countries from India before returning back to India. I have created a flag to indicate if India was ...
Abishek's user avatar
  • 787
2 votes
1 answer
35 views

BigQuery's QUALIFY Clause Access Columns differently based on the Position of Window function?

I'm working with BigQuery and came across the QUALIFY clause, which I understand can be used for filtering results based on window functions. However, I noticed some nuances in terms of how the ...
Hui Zheng's user avatar
  • 2,479
-2 votes
2 answers
76 views

Is there a way to bring the ProcessDate value in First table based on the cumulative total of a column in another table?

I have 2 tables: Table1 Definition: -- Table 1 Definition drop table if exists #Table1 create table #Table1 ( TREATY_COMPANY_CODE varchar(3), CURRENCY varchar(3), ProcessDate date, ...
Ozan Sen's user avatar
  • 2,527
0 votes
1 answer
17 views

Postgres window function to number partitions

Similar to how ROW_NUMBER and RANK apply numbers to rows within a partition, I want to apply a sequential number to each partition, with each number within the partition being the same. For example, ...
devklick's user avatar
  • 2,134
0 votes
0 answers
73 views

Counting unique column values in a rolling N day window in bigquery

I have data (results of a subquery or base data) that looks like below: And I am trying to create two new columns to it such that they count the distinct values under CLASS_DESC column in a 60 day ...
Scott Grammilo's user avatar
0 votes
2 answers
55 views

Why is the sum( ) function needed here in MySQL?

I'm working on an exercise from "Murach's MySQL 3rd Edition" which gives the following prompt: "11. Write a SELECT statement that uses an aggregate window function to calculate a moving ...
Kat's user avatar
  • 21
0 votes
2 answers
73 views

Using rank() in Postgres

I have the following tables (simplified) in Postgres: CREATE TABLE party( id int PRIMARY KEY, family_name varchar(50) NOT NULL ); CREATE TABLE election( id int, country_name varchar(...
menteith's user avatar
  • 606
4 votes
1 answer
36 views

Group row values by the sequence of their appearance

In BigQuery I have a table like this: Order Value 1 A 2 A 3 A 4 B 5 B 7 A 8 A 10 A 11 C The order column is increasing but not continuously in every case. The Value column can have ...
zoxigen's user avatar
  • 43
0 votes
1 answer
20 views

Apply lag function and .when conditions to create a new variable in Pyspark

I am trying to create a new variable, "Round", to indicate treatment round that is conditional on days missed between each treatment "Event", "Gap_Day". I am trying to ...
sarah17's user avatar
1 vote
1 answer
66 views

Cumulative sum of a counted column

I'm trying to count from a table and then sum the counted column numbers into a new column in Confluence with Table Transformer plugin. So far, what I've got is: YDT Daily Execution Sep 04, 2023 10 ...
Jason Zi's user avatar
0 votes
0 answers
13 views

Postgres Get Other Column Value Using Max Window Function

I am trying to return the row number at the highest close over the past 2 sessions. Here is a sample of the data I am working with. Date Symbol Close Row Number Max Close 1996-05-10 BRKB 24 1 24 ...
Robert Lartigue's user avatar
0 votes
2 answers
39 views

Comparison operators with a CASE statement and Window Function [duplicate]

I'm trying to use a case function with a window function, but the data I'm getting doesn't add up. Everything seems to work, but I'm only receiving "Above Average" for that entire CASE ...
Bobby's user avatar
  • 3
0 votes
2 answers
48 views

Groupby, sort within groups, and aggregate the sorted data

I have a table data containing three columns: id, time, and text. Rows with the same id comprise the same long text ordered by time. The goal is to group by id, order by time, and then aggregate them (...
element's user avatar
1 vote
2 answers
54 views

Limit RANGE window function amount of rows considered

I have a PostgreSQL scenario where I have a database table with packet captures (each packet has a timestamp and a length), and I want to calculate the “current” bandwidth in use. I’m currently using ...
mirabilos's user avatar
  • 5,144
0 votes
1 answer
38 views

How can I generate recursive rows for my table using LAG?

Sample data and current attempt: https://dbfiddle.uk/A6zVd_Qy I've got a table that looks like this: CREATE TABLE base_table ( FUND_CODE varchar(255), OPENING_BALANCE float, TRANSACTION_DATE ...
SQLGIT_GeekInTraining's user avatar
-4 votes
1 answer
52 views

How to write SQL query to read most recent timestamps (using window function)? [closed]

I have a table in my database that has rows inserted without updating old ones. That leads to having records with same ID but diffrent timestamps. How to write SQL query that uses window function to ...
Oliwier Mroczkowski's user avatar
2 votes
2 answers
45 views

SQL get last column in a group based on order by and value of another column

From the table below, I am trying to create another column (last_k2X) that will show the last key2 where type was set to 'X' over time (ti). In case X was set at the same time (ts) for multiple key2, (...
Alg_D's user avatar
  • 2,242
0 votes
2 answers
26 views

BigQuery - How to remove rows after the last action in a session

I have a table looks like the following: Session ID Action Position session_1 1 0 session_1 0 1 session_1 1 2 session_1 0 3 session_2 0 0 session_2 1 1 session_2 0 2 session_2 0 3 I would ...
eric's user avatar
  • 1
2 votes
4 answers
171 views

Replace SQL Cursor with alternative to improve performance

I'm trying to do some processing over the following Customer_Item view CustomerId Amount ItemId ItemPrice IsActiveStore Priority 1 1000 1 100 1 1 1 1000 2 200 1 2 1 1000 3 300 0 3 2 5000 4 4000 1 ...
Merna Mustafa's user avatar
0 votes
1 answer
57 views

Sum Consecutive Months Based on Groups with Criteria where Only Certain Months Show

Building off a question I asked before "Sum Consecutive Months Based on Groups with Criteria". The main difference between these two is how would I do this when not all months are present ...
UserX's user avatar
  • 159
0 votes
2 answers
63 views

Trying to count consecutive values for user in slow changing dimension table if most recent record has a certain value

I have a table with users, dates of the entry, a flag and the type of the entry. It looks like this. User InDate Flag Type 1 2023-06-01 E A 2 2023-06-01 E AS 3 2023-06-01 E A 4 ...
Michael's user avatar
  • 769
-1 votes
1 answer
26 views

How to write a sql query that will output the percentage of the sum of all values for 30,60 and 90 days. MySQL

I have written a sql query that outputs customer credit data (contracts, amount owed, etc). Now I want this query to output a share of 30,60 and 90 days overdue amount. But for now I can only write a ...
Senserverno's user avatar
0 votes
1 answer
34 views

How to group in BigQuery with window functions?

I'm trying to find the range of values for events within each visit_id in a data set, where each visit_id is returned once. I'm using this code: SELECT visit_id , min(event_start_datetime) over (...
Matthew Justin's user avatar
4 votes
3 answers
106 views

Use LAG with a specific condition on what LAG value to take?

Suppose I have a table as follows: Row Volume 1 10000 2 8000 3 0.01 4 0 5 5000 6 0 Now, if I were to use the LAG() function in SQL Server, I believe the ...
Ethan Mark's user avatar
3 votes
3 answers
91 views

Postgresql - How to calculate cumulative sum based on threshold value

This is my sample dataset. Seq_no and value columns are given, Cum.sum and Bucket columns we need to find using postgresql. To Find cumulative sum , i can write sum(value) over (order by seq_no rows ...
Learn Hadoop's user avatar
  • 2,768
0 votes
2 answers
84 views

Row-level calculations within a windows function?

I'm working on this problem from LeetCode.com: Column Name Type machine_id int process_id int activity_type enum timestamp float The table shows the user activities for a factory website. (...
Burton_Gustice's user avatar
0 votes
0 answers
29 views

A quarantine period for contracts

I am trying to find 3 months quarantine period for some contracts. More specifically, the rule is: the contract goes into quarantine when it is more then 90 days past due and should stay in quarantine ...
Junior1's user avatar
  • 11
-1 votes
1 answer
65 views

Count column without grouping

Below is my 1st Table1 Column A Column B A Cell 2 A Cell 4 B Cell 2 A Cell 4 B Cell 2 A Cell 4 Below is my result that I want to achieve based on Table1 I need column C in select query which ...
Shablu Rizvi's user avatar
1 vote
2 answers
48 views

Oracle - Calculate Previous balance using Current Balance

I have 2 tables. Table TRAN has Account_no, Transaction_date and Transaction_Amount Table BAL has Account_no and Current_balance I want to populate results from table TRAN for an account number ...
ShariefXUsman's user avatar
1 vote
1 answer
55 views

Using the SQL LAG() function

I'm trying to use the LAG function in SQL to attempt this but I'm unsure if I am using this incorrectly or not. What I am trying to do is where you see a NULL under the LOCAL_ID column, fill that NULL ...
Sunny0101's user avatar
  • 444
-1 votes
1 answer
40 views

Microsoft SQL Server "DENSE LAG()"

I artificiialy inserted to a calls history db a bunch of hypothetical future calls for each user id we have, as you can see in the picture, I hope its clear. The call_numbered are obviously ordred ...
asaf delmedigo's user avatar
0 votes
1 answer
40 views

Find items for which the price has changed the most number of times

I have a Presto table as show below: Item Price Date A 25.96 20/11/2022 B 11.89 21/11/2022 B 11.89 22/11/2022 A 26.67 23/11/2022 A 26.45 24/11/2022 B 11.75 25/11/2022 A 26.45 26/11/2022 The ...
mang4521's user avatar
  • 750
2 votes
1 answer
49 views

PySpark group by with rolling window

Suppose I have a table with three columns: dt, id and value. df_tmp = spark.createDataFrame([('2023-01-01', 1001, 5), ('2023-01-15', 1001, 3), ...
Abhishek Parab's user avatar
-2 votes
3 answers
57 views

Postgresql problems

i have a table like this: name used time asd 10 15:00 bsf 15 15:00 asd 20 14:55 bsf 0 14:55 i need to make a query that returns values like this: the result i ...
Mauricio Del Aguila's user avatar
-3 votes
1 answer
41 views

SQL Server 2022: Latest Update CU6 - Why does Last_Value does not work when there is no Partition? [duplicate]

Can anyone explain why Last_Value does not take the last value (which is last as per order by) for all rows ? select * from mytableone Initial Data (Please click on link) Query Used: select t.*, ...
Aswin K's user avatar
0 votes
2 answers
32 views

How to concatenate N rows of a column based on a specific column value based on a few conditions in Google BigQuery?

TimeStamp USER ID string_col 1 100001 Here 2 100001 there 5 100001 Apple 1 200002 this is 2 200002 that is 3 200002 Apple 4 200002 some 5 200002 summer 6 200002 winter 8 200002 Apple 9 ...
user22329205's user avatar
0 votes
2 answers
31 views

How to concatenate N rows of a column based on a specific column value using a condition in Google BigQuery?

TimeStamp USER ID string_col 1 100001 Here 2 100001 there 3 100001 Apple 4 200002 this is 5 200002 that is 6 200002 Apple 7 200002 some 8 200002 summer 9 200002 winter 10 200002 Apple That ...
user22329205's user avatar
2 votes
2 answers
37 views

How to concatenate N rows of a column based on a specific column value in Google BigQuery?

USER ID string_col 100001 Here 100001 there 100001 Apple 200002 this is 200002 that is 200002 Apple 200002 Cell 4 That is my raw table & I want to use the word "Apple" as a ...
user22329205's user avatar
0 votes
1 answer
34 views

Remove Duplicates based on Separate Column

I have a weird problem at hand. In the picture below I want to remove 2nd row, since it is the same as the first row, but the employee ids are in different columns. Ideally, my final output should ...
user20391531's user avatar
0 votes
1 answer
36 views

Displaying the aggregation value of the prior sibling's parent grouping using SQL

I'm trying to figure out how to display the aggregation value of the prior sibling's parent grouping using SQL. Hope the following example will make this clearer: Given this table: Region Department ...
itaydafna's user avatar
  • 1,968
0 votes
3 answers
47 views

Oracle SQL: How to filter out rows based on different row values

I want to filter my data, based on the following condtion For an ID, if a part appears twice or more than twice under the specific Types A and B, then I want to filter the data on that. data | ID | ...
Shantanu's user avatar
  • 839
1 vote
2 answers
58 views

How can I add a SUM clause for a certain variable to a WHERE statement in SQL Server

I am using SQL Server view design: SELECT RaceDateTime, Meeting, Horse, Jockey, Trainer, CardNumber, Result, [WinSP ], Going, Furlongs, Prize, FROM dbo.[RACE-TEMPLATE] WHERE (1 = 1) ...
racepro's user avatar
  • 23
1 vote
3 answers
39 views

How do I compare changes in text over time?

I'm not able to quite figure out how to capture the changes over time. I have the following: db<>fiddle CREATE TABLE term_changes (load_id int, merchant_id int, load_date date, terms varchar(50))...
Kermit's user avatar
  • 33.8k

1
2 3 4 5
82