4,240
questions
0
votes
3
answers
50
views
Preceding rows sum and subtraction using SQL
I have the following dataset which I'm trying to create SQL to generate the FEE column.
CUSTOMER
YEAR
MONTH
REVENUE
FEE
NOTES
CUSTOMER A
FY24
1
0
0
CUSTOMER A
FY24
2
0
0
CUSTOMER A
FY24
3
0
0
...
-2
votes
4
answers
73
views
Select first occurrence of a value per group with condition based on the most recent record of group
I currently have a credit risk default table where default status of parties are stored. I have a business requirement to get the earliest date where default has occurred and where the most recent ...
0
votes
1
answer
38
views
How to find previous of a value in one column looking from another column in Snowflake?
I have a table as below. How can I find the previous of each non null value in col5 looking from col4 in the most efficient manner using a SQL query in Snowflake?
col1 col2 col3 col4 ...
0
votes
1
answer
106
views
Use one column to group rows and the minimum of another column to order
I'm using kysely client to connect to a Postgres database, but you can also provide the solution in plain SQL.
You can understand the database structure by looking at this migration function:
await db....
3
votes
1
answer
73
views
Filter rows inside window function in Python Polars?
I need to compute the Herfindahl–Hirschman index ("HHI", the sum of squared market shares) but leaving out the firm represented in the row. Here's an example:
df = (pl.DataFrame({
'year':...
4
votes
4
answers
110
views
Is it possible to create ROW_NUMBER-column with repeating values?
I need to create an id-column: on every TRUE statement it should be a normal serial number, but on every FALSE statement the field value should contain the previous number in this column. In other ...
3
votes
2
answers
86
views
How to Handle Rows with and without Status Changes in History Table
I have a table in SQL Server that tracks the status of different IDs over time. The table includes both historical data and current data, and I need to write a query that will return the correct ...
1
vote
1
answer
101
views
Get a min of maxes over a moving window in SQ
I'm trying to compute when a charge event will next occur in an event table at any given point in time. Specifically, when a new charge date is entered for a given group, I want to ignore all prior ...
0
votes
2
answers
52
views
Using window functions to filter by a date range
I have a table with only two columns: Date, Customer.
The table records sales, so for the same day there may be duplicate customers (they can make more than one purchase).
I want to calculate a table ...
0
votes
2
answers
47
views
merge duplicate rows where one row is null
I am using AWS Redshift. I have a table that looks like this:
Id key value1 value2 value3
1 xxx A NULL ...
1
vote
1
answer
47
views
How to build sequence in MySQL using ROW_NUMBER while some values of sequence are present?
Hello stack overflow community. I've got a following problem.
Given the following, I have an entries table
CREATE TABLE `entries` (
`name` varchar(50) DEFAULT NULL,
`sort_order` int(11) DEFAULT ...
1
vote
0
answers
81
views
Create a custom function for the OVER clause, similar to the MAX function? [closed]
I want to create a custom function MAXBy([Amount], [Id]) for the OVER clause in SQL Server, as this function does not currently exist.
I want to find the maximum amount in the previous 100 records, ...
0
votes
2
answers
54
views
Window Function with multiple conditions to DELETE records from Table
This is my table:
I need to delete those records where there is NL46 ShopCode, but only if the ProductCode has ShopCode 'FR43','FR44' or 'FR45'.
I only need to keep the rows with NL46 if these ...
0
votes
1
answer
52
views
Number of Tasks - for Window function without PARTITION BY statement
As per the documentation (https://docs.databricks.com/en/optimizations/spark-ui-guide/one-spark-task.html) , Window function without PARTITION BY statement results in single task on Spark.
Is this ...
0
votes
1
answer
45
views
Skipping Order if Older order is present
I need help with item # 3.
Skip duplicate orders
Skip cancelled orders
Skip order if an older order is present
In the given data, we need to:
skip id # 2,
skip id # 3 or 4.
skip id # 5 (as it ...
1
vote
1
answer
61
views
Filtering out duplicates within a CTE
The data in this cte looks like this:
h_pit as (
select
*
from "h_pit"
)
id hash_key1. hash_key2 business_key date value
1 ...
0
votes
1
answer
39
views
How can I rank after filtering inside a window function?
I have a huge BigQuery table "taskperformance" that attributes tasks to sales (ordered in this example for easier
understanding):
sale_id
sale_timestamp
task_id
task_timestamp
is_same_store
...
2
votes
2
answers
67
views
SQL filter rows by range overlap
I have a snowflake table that roughly resembles the below. I want to filter out all rows that have the same name, provider and an overlapping voltage range.
Before:
NAME
Provider
Min_Volt
Max_Volt
...
0
votes
1
answer
68
views
Looker data studio: sum over running total formula
I have the following table.
The raw data columns are:
Fruit
Sweetness
Number of fruits
weighted_ is equal to Fruit * Sweetness
i want the tes weigthed values is 8,750,000 from the first row unit ...
-1
votes
1
answer
38
views
PostgreSQL Window Function with equality predicate
I have the following query in PostgreSQL. Everything works as expected. It returns a single row for each grp. The row returned has the greatest id within the grp.
with tbl1(id, grp, name) as (
...
0
votes
1
answer
20
views
Creating query for count of rows in a 24 hour window with window_start_dates
I have a table of rows in bigquery that has a userid and timestamp field createddate. I want the query to output userid, window_start_date, count(*) grouped by userid, window_start_date. The ...
0
votes
1
answer
20
views
Count Distinct Window Function Workaround
Let me start with explaining the data and the problem. We have a data table that is transactional detail and a table called TimeSortOrder30 which list each of the 30 min intervals in a day with ...
0
votes
3
answers
75
views
Using nested lag or any other window function
I am working on a transaction dataset with one date column & one identifier column. Now retroactively I want to create a boolean column to check whether any particular activity (e.g. marketing ...
2
votes
2
answers
74
views
Compute the sum of the previous group of rows and the sum of the current group of rows in SQL
I have a SQL table containing profit for a customer group, customer, project and year. I want to add the sum of the profit of the previous year for the current customer group and the sum of the profit ...
0
votes
0
answers
33
views
when an message match a filter how can i look back 10s before that message arrive and return all message that came before
I'm working with PySpark Streaming and need to implement a feature where, when a message matches a certain filter condition, I can look back 10 seconds before that message arrived and return all ...
-1
votes
2
answers
91
views
MariaDB Rank Query
I am very new to PHP and SQL and building a project for hockey statistics.
For this page, I am looking to create a SQL query to rank hockey leaders based on goals scored. I am trying to take a table ...
0
votes
2
answers
33
views
How to assign flag to a group of rows depending on a specific combination of values
I am trying to produce a case statement (if that's the best solution) that can help me capture the following:
ID
Codes
Flag
ID-001
C712
1
ID-001
W943
1
ID-001
W371
1
ID-002
C751
2
ID-002
C712
2
...
3
votes
0
answers
106
views
Is `ROW_NUMBER() OVER (ORDER BY xml.node)` well defined? [duplicate]
While researching the answer to another question that required extracting XML nodes in the original element order, I came across several answers (here, here, and here) that used expressions of the ...
1
vote
1
answer
50
views
FIRST and LAST VALUE bringing conflicting row quantities in the same query. WHY?
I have a SQL query with the objective to extract the values of the row with the last date for each different value that exists in column_2.
I used the window function on all the columns that might ...
1
vote
1
answer
95
views
Distinct cumulative count in PostgreSQL window function
I've got a table with many columns some of these are:
product_id, territory_id, quarter_num (it's a number of a quarter from 1 to 28 for instance).
There are some other columns but they aren't ...
0
votes
1
answer
78
views
How to generate a line number based on condition
I have an InvoiceLineItem table where line number is not added to the table. I have to create it on the fly while processing the table.
The line items can be grouped by
Invoice Id and
Row that end ...
2
votes
1
answer
76
views
Discount accumulated negative sum from column
I have the following dataset in PostgreSQL 15:
Generate data
SELECT id, value, expected_output, comment
FROM (VALUES
(1, 0.89, 0.89, ''),
(2, 0.17, 0.17, ''),
(3, -0.30, 0, 'accum ...
2
votes
1
answer
52
views
Oracle SQL_Macro and analytic functions
The following SQL Macro returns all (three) rows or just one, depending on P_ID parameter. Logic consists in basic appended records and an analytic LAG function:
create or replace function ...
0
votes
0
answers
63
views
QueryDSL 5.1 (JPA), Hibernate 6.3 and Window Functions
Context: I want to find the next and previous Entity ID, according to a search criteria and an ordering.
Hibernate is now supporting Window Functions, such as RANK, in the SELECT Clause.
Following ...
1
vote
1
answer
104
views
STRING_SPLIT and ROW_NUMBER() - maintaining order [duplicate]
I have a requirement to split a string based on a delimiter and to pull the values based on their ordinals. As I am on SQL Server 2019, I cannot use String_Split with ordinal enabled. Trying to ...
2
votes
2
answers
110
views
Function to encapsulate lookup logic
I want to write a Postgres function that looks up the value of a column in a given table.
Example setup:
CREATE SCHEMA IF NOT EXISTS example;
CREATE TABLE example.price_table (
symbol text NOT ...
1
vote
1
answer
65
views
Postgres search missing date in hourly sequence
I have a table period_of_hours in PostgreSQL. This table contains several column but for my case is important column timestamp (timestamp without time zone) and key(character varying).
I have a ...
0
votes
1
answer
140
views
Window functions in Trino: ordering changes length of array
TL;DR: If I order a window-function partition, then the length of the resulting array changes.
Here's a minimal example. We first generate some toy data:
select *
from (
values
(date('1900-01-01'...
1
vote
1
answer
63
views
UPDATE column with cumulative sum
I have a column a_increment and I want to use it to calculate a column a_cumulative, which is the sum of all earlier a_increment, including the current row. "Earlier" as defined by the ...
1
vote
1
answer
92
views
Is there any order of precedence in window functions of SQL?
I have a table as follows:
I just want the previous entry for every row from the column 'marks'.
Table structure:
test_id marks
100 55
101 55
102 60
103 58
...
0
votes
3
answers
104
views
Select first column for multiple occurrences of second column and a condition from third column
I have a table which looks like this
Individual_ID Household_ID AccountType
-------------------------------------------
101 HH_101 CHK
102 HH_101 SAV
103 ...
0
votes
1
answer
300
views
Snowflake SQL | How to sum over distinct values in one pass?
I am working with survey response data, where a user could have taken the survey multiple times. Users have a "weight" assigned to them, which is an integer. I am trying to calculate the sum ...
1
vote
2
answers
81
views
take a value of a column based on a condition of a window function
So I need to create a new column with CurrentPrice where I need to put the latest price inside the GROUP based on column DATE.
So I should look at the newest Date of each Group and put the price of ...
0
votes
1
answer
91
views
window function for analysing a string
So when the record has the same VAR, same Group but different SalesPrice: i need to comment it as 'need to define'
i was trying to use window function but cannot succeed with it.
any help is ...
2
votes
1
answer
55
views
PostgreSQL cluster uninterrupted series of data
here's an example of the input and the desired output, I think this is easier to grasp than me describing the need.
input data
(business logic explanation: everything with a duration > 1M is set ...
2
votes
2
answers
105
views
Build Session Logic based on DateTime in Snowflake SQL
I'm trying to build session logic based on DateTime value for a group of columns (like Userid, DeviceId)
For a given userid, deviceid the session can start any time of the day(first event) and
I want ...
4
votes
3
answers
96
views
Postgres Select Row From Group With Opposite Sort Order
I have a Postgres table foobar with the following schema:
id: integer
group: integer
foo: integer
bar: integer
timestamp: integer
I keep track of updates to various groups, and those updates mutate ...
0
votes
2
answers
145
views
Moving SUM analytic function from PostgreSQL to Redshift with RANGE window frame clause
I have the following code in PostgreSQL, which I need to reproduce on Amazon Redshift:
select *
from
( select distinct
a.id
, sum(case when a.is_batch_empty then 1 else 0 end)
...
1
vote
1
answer
86
views
Spark (Scala): Moving average with Window function
The input dataframe it looks like this:
+---+----------+----------+--------+-----+-------------------+
| id|product_id|sales_date|quantity|price| timestampCol|
+---+----------+----------+--------...
1
vote
3
answers
122
views
PostgreSQL window function for sum per interval
The table is represented by following scripts:
CREATE TABLE sales (
id SERIAL PRIMARY KEY,
product_id INTEGER,
sales_date DATE,
quantity INTEGER,
price NUMERIC
);
INSERT INTO sales (...