Questions tagged [common-table-expression]
A Common Table Expression (CTE) is a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE or DELETE statement. Formally named <with clause>, according to the ISO SQL standard.
4,192
questions
0
votes
1
answer
106
views
How to do SQL recursive logic
I have this sample dataset like this ;
acctid
payseq
totalamount
acctnum
expectprice
payorder
aac1
99
1000.00
1111aa
800.00
1
aac1
99
1000.00
1111bb
800.00
2
aac1
99
1000.00
1111cc
800.00
3
aac1
...
-1
votes
0
answers
28
views
Finding amount using dense_rank as loop counter in table
On MS SQL server,I have to perform calculations on the following table:
Row#
Period_begin_dt
Period_end_dt
Amount
Period_Status
:----
:---------------:
:------------:
1
2023-07-01
2023-09-30
0
...
-1
votes
0
answers
34
views
SQL using cte tables to insert into temp table [closed]
I’m trying to write a query and improve the efficiency; the query is large and complex and uses a lot of CTE tables and at one point in the code combines a 5 of these CTE tables via UNION ALL. I think ...
0
votes
0
answers
14
views
BigQuery non-incremental materialized view is not refreshing as expected. How does it refer to the base table?
I am creating a materialized view with a ROW_NUMBER() function in my query. Since it's an analytical query and incremental materialized views do not support those functions, I'm creating a non-...
0
votes
1
answer
17
views
MySQL CTE function call duplicated
I expected the function call "expensive" to be called only once, but it appears to be called for every row in "children". Can the CTE/query be tweaked to only call the function ...
0
votes
2
answers
66
views
SQL recursive cte - sort overlapping range
I have a table like below
range_from range_end created_on
100 105 2023-01-01
106 110 2023-01-01
106 111 2023-06-01
120 130 2023-01-01
112 130 2023-06-01
I need to clean it to get a most updated ...
2
votes
0
answers
92
views
Recursive Query with Django-CTE
I have a Tree model that i need to prefetch all the childs and user of the comments all at once:
class AnalysisComment(MPTTModel, TimeStampMixin):
parent = TreeForeignKey(
"self",...
0
votes
0
answers
37
views
"Melt" columns into rows [duplicate]
I have SQL Server with some information about users "name, id" and lots of columns that represent items they have: item_no, item_desc, item_val.
The problem is instead of multiple rows with ...
-2
votes
1
answer
38
views
Write SQL query to return only the latest record that is modified with CTE and inner join
I believe I'm incorrect in my CTE query.
WITH LastModified AS (
SELECT
Id, MAX(ModifiedON) as Last_Modified
FROM
EventTransaction
GROUP BY
ProductNumber)
SELECT
ProductNumber, ...
0
votes
0
answers
10
views
How to find all subordinates and their subordinates based on their multiple pernos
Given:
Two tables Employee EmployeeManager
Table Employee's columns: perno, uniqueKey. One employee can have mulitple different perno, but there's only one uniqueKey for an employee.
Table ...
0
votes
1
answer
71
views
SQL Server using CTE for Insert
I have an asterisk delimited flat file, I import it into a single column in a table to check for errors. Once happy, I then want to split it up and insert it into a table with a 17 columns that ...
0
votes
1
answer
32
views
"REAL WORLD" SQL CTE query capable of: getting a tree from a parent child table with depth-first & alphabetical ordering & filter/sum nodes subtrees
After searching hours over the internet, still missing a good example of a SQL CTE Query able to be used in real world scenarios, wondering even if CTE and MODERN SQL in general are currently capable ...
2
votes
4
answers
65
views
Using variable size in limit clause in snowflake sql
I want to limit number of rows using variable size where I get using CTE in snowflake: As a super easy example consider the following:
with num_groups as
( select count(*) as num_group from table1 )
...
1
vote
2
answers
36
views
How to rank rows based on two columns using SQLite
I have a table like this. I want to rank each row based on the date column so that the end result is the same rank if the two values of record_number and date are equal and different rank if the ...
0
votes
1
answer
48
views
Regex to capture CTEs
I've built this regex to capture snowflake CTEs.
The CTEs are defined by a first WITH reserved keyword, but the next ones need only an AS. Here's an example:
WITH first_rows AS (select top 3 * from ...
-1
votes
1
answer
33
views
Relate CTE to main part of query, or is CTE even needed?
I've been playing with CHAT GTP to create a query that I need. Together we got:
WITH employeeCompensation AS
(SELECT hourlyBonus, shiftBonus
FROM empComp
WHERE selfmanagerid = 1 AND
...
0
votes
1
answer
45
views
Trying to execute a dynamic CTE in PostgreSQL function
I'm trying to create a Postgresql function which will dynamically build the CTE and execute it to do the archive/purge.
Context: Records from main tables must be archived to their corresponding ...
1
vote
3
answers
62
views
SQL: querying the max of sum written either as subquery or CTE fails
Assume a table salaries that contains employee_id, department_id and salary, as follows.
e_id | dpt_id | salary
---- | ------ | ------
1 | 2 | 1000
2 | 2 | 2000
3 | 5 | ...
0
votes
2
answers
53
views
SQL Server : select rows with time stamp values near values in subquery
I have a log table that includes id, TimeStamp, Message where the Message value sometimes contains 'WARNING'.
SELECT TimeStamp
FROM Logs
WHERE Message LIKE '%WARNING%'
What I need are the rows that ...
0
votes
2
answers
38
views
Dividing into multiple row output based on month start date falling within range
I have a data where given two dates, it creates a range of start date and end dates with a gap of 7 days using below query.
WITH Ranges AS (
SELECT
TO_DATE('2023-10-16 00:00:00', 'YYYY-MM-...
1
vote
2
answers
82
views
Retrieve cyclic graph data without infinite loop and repeated
I need to query these records to get unique related items:
insert into items(child, parent)
values (1, 2), (2, 3), (3, 5), (3, 4),
(4, 5), (6, 7), (1, 8), (8, 1)
I need to pass the input e.g. ...
0
votes
0
answers
29
views
problem with using SQL CTE function inside prestashop
I have a problem with using WITH function (CTE) in prestashop 1.7.6.9 to make additional features in stats.
My original PHP code (works fine):
$this->query = 'SELECT SQL_CALC_FOUND_ROWS p.reference,...
1
vote
1
answer
34
views
alternatives to CTE to improve performance of query
I'm creating a query in Impala SQL that needs to perform an operation on data prior to agreggate it. This is my query:
With concatenated_addresses As (
Select site_name, concat(...
0
votes
1
answer
74
views
Row Level Security with Common Table Expression
Given this schema:
CREATE TABLE posts (
id uuid NOT NULL PRIMARY KEY DEFAULT uuid_generate_v4(),
title text NOT NULL CHECK (char_length(title) > 2),
author uuid NOT NULL DEFAULT auth.uid() ...
-1
votes
1
answer
51
views
Get the id from the table based on the condition
I have 2 table t1 & t2 both table has 3 columns id,status,run_date.
Find the id from t1 that
have different status in t2 than in the t1 AND run_date in t2 is older than t1
do not exist in t2
3)...
0
votes
1
answer
71
views
EXISTS condition in RECURSIVE CTE
I'm trying to use "EXISTS condition in RECURSIVE CTE" to stop recursion, but I get SQL Error [42P19]. PostgreSQL version 13.2.
Is there a way to bypass this limitation?
The Sql-query below ...
1
vote
0
answers
19
views
Single Store getting SQLSTATE: 42S01 namespace already exists error while using Recursive CTE in multi-threaded environment
Getting namespace already existing error in Singlestore while using recursive CTE
in mutlti threaded environment.
I have a table in db that contains enitire tree data id, parent_id and name
and the ...
0
votes
1
answer
34
views
Showing Error code: 1060. Duplicate column name 'column_name', while running common table expression in MySQL
There are 2 tables named customers and payment, when I am applying common table expression on two tables for generating temporary table 'temp' and searching for anything from the temporary table 'temp'...
1
vote
1
answer
67
views
Join a Sub-Query in EF Core
Goal: I want to select the latest versioned records of a given table:
id
version
name
1
0
Alek
1
1
Alex
2
0
Bob
Note: the temporal data feature is a no-go.
Ideally this is what I want EF Core to ...
-1
votes
1
answer
63
views
How to loop through result set from a CTE?
I have problem with SELECT, I am receiving the error
Msg 208, Level 16, State 1, Line 18
Invalid object name 'list'.
What's wrong?
DECLARE @end datetime = getdate(),
@start datetime = CAST('01/...
1
vote
2
answers
48
views
How to display the last day of month instead of first in SQL query recursion
I have the following query:
DECLARE @StartDateTime DATETIME
DECLARE @EndDateTime DATETIME
SET @StartDateTime = '2015-01-01'
SET @EndDateTime = '2016-01-12';
WITH DateRange(DateData) AS
(
...
0
votes
0
answers
52
views
Simplifying my stored procedure (cte, merge)
I have pieced together a rather long, possibly inefficient stored procedure. The sproc receives a JSON of SKUs, along with some parameters, in order to bulk update two different tables with the same ...
1
vote
1
answer
66
views
Recursive query to mimic a folder structure in PostgreSQL
I am trying to mimic a simple folder structure in PostgreSQL using this table:
CREATE TABLE folders (
id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
name text,
parent UUID REFERENCES ...
0
votes
1
answer
33
views
BigQuery - How to make a transactions report with opening and closing balances?
I am trying to create a tabular report using two tables in BQ. One table is a list of contracts with contract start dates, names and opening balances. The other is a list of transactions that occurred ...
0
votes
1
answer
43
views
Google Big Query gives me "there is no data to display"
enter image description here >>> this is image of my query
I have a dataset with over 500000 rows.
I have two columns:
one is start_station_name column.
two is member_casualcolumn. it shows ...
1
vote
1
answer
38
views
How to UNION product_groups and specifications of different hierachy level to deepest one?
Scenario - All valid classes / product groups and their valid specifications for all products in them are to be determined.
Products have different specifications / features
Products always hang on ...
-1
votes
2
answers
49
views
Create breadcrumbs navigation using HIERARCHYID?
I have Product Categories table in Microsoft SQL Server:
CategoryID (IDENTITY)
Node (HIERARCHYID)
CategoryName (NVARCHAR(100)
1
0x
Products
2
0x58
Main Category 1
3
0x68
Main Category 2
4
0x5AC0
...
0
votes
1
answer
62
views
Get next available number
I have a Bookmarks table which contains a smallint column called BookmarkNumber.
Bookmarks are created and deleted.
When a new bookmark is created, e.g. with Id="oo", I want to create a new ...
0
votes
0
answers
16
views
using common table expressions in mysql [duplicate]
I am attempting to solve an HackerRank challenge and using MySQL query engine. I'd like to use WITH and CTEs for the problem.
https://www.hackerrank.com/challenges/interviews/problem?isFullScreen=true
...
1
vote
1
answer
53
views
MySQL - Recursive CTE to fill in gaps in data over time
I am currently facing an issue that I have been trying to crack for a while now without success.
The problem is as follows:
I have a table that tracks requests and their status changes over time. Over ...
-1
votes
1
answer
55
views
Is there an alternative to rank() over(partition by...order by)
I'm trying to change the rank() over (partition by...order by...) in the subquery into a group by and min/max since the rank() is causing the query performance to be slow. This is because after the ...
1
vote
1
answer
58
views
How to repeat insert statement n times incrementing a value?
I have this SQL statement:
INSERT INTO `results` (batch_id, workstation_id, result, received, log_time)
VALUES (281, 13, ABS(RANDOM()) % (232.91 - 69.87) + 69.87,
DATETIME('now', '+1 day', '...
0
votes
0
answers
19
views
Why does this MariaDB SQL query return more values when not using a CTE?
We use MariaDB 10.6.14.
I wrote this rather messy query
SELECT DISTINCT t.text
FROM dba.questionnaire_translation t
JOIN dba.filter_translation ft ON t.translationId = ft.translationId
...
0
votes
1
answer
46
views
Calculate cumulative sum over partitions with gaps in SQL
I have a table with stock changes with different countries and different products.
The table looks like the following:
Date
Country
Product
Variation
2023-10-01
Spain
Pen
1
2023-10-01
Germany
Pen
1
...
0
votes
1
answer
42
views
SQL Server Recursive CTE to shred JSON: Types don't match between the anchor and the recursive part
I am trying to rewrite a function to an inline Table Valued Fuction.
Database is SQL Server 2022.
Please have a look at the following SQL Fiddle. I tried multiple rewrites with explicit CASTs but it ...
0
votes
1
answer
57
views
How to do a Recursive SELECT with repetitives values in table
I'm using SQL Server, and I have a table with ID father and ID son, but more than one row of this case, because I have others columns in same table.
I'm trying to do a recursive SELECT, but my query ...
-1
votes
3
answers
196
views
Is being able to refer to a CTE in a FROM-less UPDATE clause undocumented behaviour?
The syntax for the first part of UPDATE is documented as follows
UPDATE
[ TOP ( expression ) [ PERCENT ] ]
{ { table_alias | <object> | rowset_function_limited
[ WITH ( ...
1
vote
1
answer
73
views
Trouble Filtering in PostgreSQL With Recursive CTE Query
I am having trouble formulating a query to meet the following criteria (have a basic CTE query working) but am thinking I am missing/overlooking something and am hoping SO can help (much appreciated ...
0
votes
1
answer
80
views
duckdb syntax error for materialized CTEs
I am trying to create a query with Materialized CTEs but I get a syntax error (in this case with R, but the problem is independent of R, I hope...).
The query that throws an error looks like this (...
0
votes
3
answers
82
views
Sort on T-SQL unioned query with CTE
I need to do a sort on a T-SQL unioned query. No matter how I write the query, I'm getting a syntax error once I introduce the ORDER BY clause.
Incorrect syntax near the keyword 'order'
T-SQL query
...