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.
3,764
questions
0
votes
0
answers
21
views
Postgresql update from CTE
I have 2 simple CTEs from that return the same columns, but with diff values
with x as (select id, class from table1 where paramenter='D')`,
y as (select id, class from table1 where paramenter='F'...
0
votes
0
answers
11
views
Problem with setting cte max recursion depth value using raw sql in EF Core
Not able to set the cte max recursion depth value using raw sql with db parameterization.
I am using MySql database and have few programs which uses recursive cte's. I am trying to set the max cte ...
0
votes
0
answers
32
views
How to insert a new row of values into a table and continue with my CTE (snowflake)
I have CTE that looks like:
WITH COLS AS (
SELECT VALUE AS COL FROM ET1 LIMIT 1
),
RAW_COLS_ORDER AS (
SELECT TRY_CAST(SUBSTR(KEY, 2) AS NUMBER) AS COL_POS, VALUE --remove the c from the column ...
1
vote
1
answer
23
views
SQLite Closure Tabe: How to improve my SQL to split a tree
here is a classic tree paths table:
CREATE TABLE treepaths(
tpa_ance INTEGER NOT NULL, -- ancestor
tpa_desc INTEGER NOT NULL, -- descendant
tpa_leng INTEGER NOT NULL, -- lenght
...
-1
votes
0
answers
47
views
SQL Faster method query all columns contain
I've got a query that uses with clauses to build up a large view. The key thing with this one is keeping it nicely verbose, with sections that will allow easy maintainability in the future, so I've ...
-1
votes
1
answer
20
views
Postgres query syntax error . I am querying in navicat
I try to add quotes. But it did not work:
I'm using Postgres.
Here is my query in navicat which results in syntax errors:
WITH t1 AS
(
SELECT
*
FROM
"olympics_history&...
-4
votes
0
answers
47
views
Chain of Command in SQL using Non-recursive methods [closed]
I'm working on a project that deals with hierarchies, and my query looks like this:
WITH Hierarchy AS
(
SELECT
Employee as starting_employee,
Employee,
...
1
vote
0
answers
75
views
Defining CTE (Common Table Expressions) in R?
I have this table on a server - I am querying it with R:
library(dplyr)
library(DBI)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "iris", iris)
I was ...
0
votes
1
answer
41
views
Referencing a CTE multiple times with different variables
In BigQuery, I have a table like this
col_a
col_b
datetime_col
1
0
2022-01-01
0
1
2022-01-01
I want to get aggregates from different dates like this
SELECT
SUM(sum_col_a) sum_col_a,
SUM(sum_col_b) ...
0
votes
2
answers
80
views
Converting recursive CTE from Postgre SQL to SQL Server
I am having trouble adapting some recursive CTE code from PostgreSQL to SQL Server.
Here is my table:
CREATE TABLE flight (
src CHAR(3)
, dest CHAR(3)
, stt DATETIME
, endt DATETIME);
INSERT INTO ...
0
votes
2
answers
35
views
Use WITH clause for storing temporary data: What is the equivalent syntax to Oracle, but in SQLite?
The syntax for storing temporary data in the WITH clause looks like this in Oracle:
with data (asset_id, x, y) as (
select 100, 10, 20 from dual union all
select 200, 30, 40 from dual union all
select ...
-2
votes
0
answers
22
views
Find Numbers between 2 Numbers SQL [duplicate]
I have a table Numbers and I need to find the numbers between 2 numbers in SQL. How do I get Range column? My input table has columns V1 and V2 and I need an output like the table below. Please help ...
1
vote
1
answer
37
views
Create JSON with childrens in SQL Server (structure for web tree)
Please help me to create a query, or advise what to read. I have a tree-structure in a SQL Server table.
I need to convert table data into JSON format for web-tree - with children, when all descendant ...
0
votes
1
answer
36
views
Merge consecutive time record in SQL server 2008
Say I have data like this, timeslots is basically time with 30 mins apart.
Note there is a gap in 2021-12-24 between 15:30 and 16:30.
calender_date
timeslot
timeslot_end
2021-12-24
14:00:00
14:30:00
...
0
votes
1
answer
16
views
Executiung performant SQL queries equivalent to "nested deletes"
Consider the following ERD for Order, Item and Article entities:
I'd like to delete Orders satisfying a complex condition, and then delete Items associated to those Orders, and finally delete ...
0
votes
1
answer
90
views
Table "table" must be qualified with a dataset in CTE table
why do i get this error ( Table "table" must be qualified with a dataset (e.g. dataset.table) when calling table in CTE
-2
votes
0
answers
21
views
Pivot With CTE Table
I've got a CTE SQL query which I want to PIVOT so I can display a user, their direct manager, the grade 1 manager and then the director in one row.
Currently it's all listed.
;WITH MyCTE (Payroll, ...
-1
votes
2
answers
42
views
Join table to CTE and group by
I have a CTE that contains lots of joins and condition (mydashboard) and
I am trying to join the CTE to another table and show an additional column with the count of the second table.
What am I doing ...
1
vote
1
answer
54
views
For XML Path with nesting elements based on level after recursive CTE
I have data that looks like after writing the recursive CTE:
| EPC | ParentEPC | SerialEventId| Level| @ItemName|
|--------|--------------|--------------:|:----------:|--------------|
| a| NULL|5557|0|...
0
votes
0
answers
29
views
CTE JSON Merge Patches in SQLite?
So say I have a set of json merge patches
CREATE TABLE IF NOT EXISTS `events` (
`id` INT NOT NULL,
`entity_id` INT NOT NULL,
`patch` TEXT NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `events` (`...
0
votes
1
answer
70
views
slow performance on MYSQL recursive cte query
I want to calculate the 9 min Exponential Moving Average (EMA) for a large set of minute stock-data exceeding 30,000,000 rows with roughly 4,500 different Tickers.
The query I have makes use of ...
0
votes
1
answer
39
views
Trying to get a CTE to work in PostgreSQL
I am new with SQL and I trying to make a recursive query to work on PostreSQL without any luck.
I have a table tb_invoice with these columns:
invoice_no
cust_no
payed
tot_amount
"...
0
votes
0
answers
16
views
insert an array of photoUrls as separate records with same reference id
I have an array of values for a product review that I need to insert into two Postgres tables named reviews and reviews_photos.
const values = [product_id, rating, summary, body, recommend, ...
1
vote
1
answer
23
views
Possible to emulate a recursive CTE?
I think the short answer to this is No, but is it possible to emulate a recursive CTE with something like a table function in a database that doesn't have support for a CTE? For example:
-- get ...
0
votes
0
answers
34
views
LEFT OUTER JOIN not producing full output on time series CTE using generate_series (postgresql)
I was hoping to have a CTE that generated some time series data (hourly values based on min / max timestamp values pulled from another table) then doing a LEFT OUTER JOIN on a table of transaction ...
0
votes
1
answer
60
views
T-SQL selecting CTE into a variable
I am attempting to set a variable to the result of a CTE select statement in SQL Server / T-SQL:
DECLARE @ReportRecipients VARCHAR(MAX);
SET @ReportRecipients = WITH CTE_TableName AS (SELECT a....
1
vote
1
answer
30
views
How to Retain Multiple Results from a MySQL CTE query?
I am trying to create a pre-process to compute the lower and upper interquartile gap values and save them as variables to use in a subsequent WHERE clause. I borrowed some code and can get one of the ...
0
votes
1
answer
40
views
SQL tree recursive mean of children values
I am currently designing a catalogue system. It has 2 types of items: categories and items themselves. There also may be nested categories and some items may have a parent which is always some ...
0
votes
2
answers
21
views
How to emulate a dependent CTE
Following up from this question Possible to emulate a basic CTE in MySQL by in-lining it, would it be possible to in-line the following query in mysql5.7 without the usage of CTEs?
WITH tbl1 AS (
...
2
votes
1
answer
51
views
Why isn't a CTE evaluated one time?
If we take the following:
WITH tbl AS (
SELECT RAND() AS a
) SELECT * FROM tbl AS tbl1, tbl AS tbl2
Why does this return two values instead of one? I thought a CTE is basically evaluated one time ...
0
votes
0
answers
20
views
Possible to emulate a basic CTE in MySQL by in-lining it
There have been various questions about this but I'm not sure if they address this particular aspect of it. Let's say we have the following query on a non-recursive, non-volatile, non-depdendent CTE?
...
-1
votes
1
answer
43
views
Attempting to get monthly totals for subqueries
I'm trying to get monthly subtotals, breaking down into specific product types. This worked for one month, but when I try to do a number of months I get repeating totals inside the subqueries.
Tricky ...
0
votes
1
answer
58
views
Workaround for reproducable SQL Server bug when updating a CTE
I've encountered an issue with SQL Server when using an updatable CTE when combining a view with a derived column and a table using system versioning.
It causes a stack dump and disconnects the ...
0
votes
1
answer
41
views
SQL - Using CTE to pass CASE statement results to subsequent formulas/CASE statements
I'm trying to use CTEs to pass results from CASE statements as inputs to subsequent CASE statements on minute-level date before aggregating to daily values. The intention of the code below is to:
...
0
votes
1
answer
36
views
How can I add the outputs of one CTE to another CTE?
I have a database that consists of 8 records about the employees, and it saves both the Ssn which is the id of every employee and a Super_ssn that references their manager. Here is the code for ...
0
votes
1
answer
31
views
Incorrect Syntax near `End`
I have a database that consists of 8 records about the employees, and it saves both the Ssn which is the id of every employee, and a Super_ssn that references their manager.
Here is the code for ...
0
votes
1
answer
80
views
How to convert T-SQL Script to CTE for Snowflake / DBT
I'm having trouble converting my TSQL Script into CTE that needs to be run on Snowflake through DBT model.
declare @i integer = 1
declare @LastID varchar(38) = ''
declare @Change money
declare @ID ...
0
votes
2
answers
65
views
Extract previous row calculated value for use in current row calculations - Postgres
Have a requirement where I would need to rope the calculated value of the previous row for calculation in the current row.
The following is a sample of how the data currently looks :-
ID
Date
Days
1
...
0
votes
0
answers
25
views
Recursive CTE in Postgres - SUM at each parent node
I`m storing a hierarchical product adjacency list and a separate table for all the sales on those products.
Currently, I`m trying to present to the user a "Sales Report" with the total ...
1
vote
1
answer
28
views
Finding Unique Airline Routes with SQLite
I have two tables:
AirPorts (IATA_CODE TEXT, LATITUDE REAL, LONGITUDE REAL)
AirRoutes (ROUTE_FROM TEXT, ROUTE_TO TEXT)
The AirRoutes table includes routes from Airports that are not listed in the ...
0
votes
0
answers
59
views
Multi-level recursion using SQL Server CTE with aggregation at each level
I am trying to run a recursive query to propagate the value in column Quantity level by level in the following table:
create table propagate
(
parent varchar(50),
child varchar(50),
...
0
votes
1
answer
27
views
Multiple laravale websites - Central login system & Shared one database
I have multiple Laravel websites, and I wanted to have one central login system for that.
The idea workflow is:
User wanted login to "website 1"
by clicking to "login button" will ...
-5
votes
1
answer
76
views
How to put a CTE as a subquery
In SQL Server, I have a CTE and a select statement.
The CTE looks like
WITH Recursion AS (
SELECT Value, GroupID, Type
FROM @GroupMembership
WHERE GroupID = @requestingGroupID
UNION ...
1
vote
1
answer
50
views
Cumulative sum reset by change of year (SQL Server)
I'm using SQL Server 2017. I would like to sum up the budget per month of a year for that year and factory.
This cumulation is to be reset with each new year.
Table schema:
CREATE TABLE [TABLE_1]
(
...
0
votes
1
answer
40
views
PostgreSQL- Common table expression update column from SELECT
I have this code which intents to generate a hash password for all values of a column in a table.
The issue comes when I see the results, only one hash is created (repeated for the number of rows of ...
1
vote
1
answer
27
views
Is there a way to turn a single row from a DB2 SQL statement result set into multiple rows based on one value from that resulting row?
If I have a SQL query like this:
SELECT A.W, A.X, B.Y, B.Z
FROM A
INNER JOIN B ON A.value1 = B.value2;
Which is returning a row like this:
W | X | Y | Z
---+---+---+--
w | x | y | z
Is there a ...
-3
votes
0
answers
71
views
Cannot when add ORDER BY in a CTE
I have the following code:
WITH basequery AS (
SELECT c.baseentityid,
c.team,
c.providerid,
rank() OVER (PARTITION BY c.baseentityid ORDER BY c.version ...
0
votes
1
answer
74
views
sql split yearly record into 12 monthly records
I am trying to use common table expression to split an yearly record into 12 monthly records. I have to do it for next 20 years records . That means 20 rows into 600 rows (20*12=600 records).
What is ...
0
votes
1
answer
31
views
Save complex SQL statement as a table
I want to process one column of a joined table in MS SQL row by row and save the output to another (empty) column in the corresponding row of the table.
The column to be processed contains some kind ...
-1
votes
2
answers
48
views
SQL Server : LAG multiple Nulls
I am trying to "fill in the blanks" with my table below.
I have created a PDF reader that spits out a JSON file that I have manipulated into the below format.
There is very little scope in ...