Questions tagged [subquery]

"subquery" is vague SQL terminology, used to describe when there's either more than one `SELECT` statement in a query, or when used in Data Manipulation Language (DML) statements (IE: DELETE, UPDATE, INSERT, MERGE). The subquery's SELECT statement is always found within brackets/parenthesis.

Filter by
Sorted by
Tagged with
0 votes
1 answer
23 views

Error in Select multi Column from Subquery

I wrote following SQL command select * from [Monitoring].[dbo].[MaintTaskMonitor] where (JobStartDate,TaskType) in ( select max(JobStartDate),TaskType from [Monitoring].[dbo].[MaintTaskMonitor] ...
a.Paryab's user avatar
-1 votes
0 answers
30 views

MySQL use ORDER BY, LIMIT and ORDER BY at the end of projection

I'm using MySQL and I'd like to run a query on a table containing a date field and a value. To keep things simple, here's the creation code (this is an example): CREATE TABLE my_table( pull_date ...
Tancelin MAZZOTTI's user avatar
0 votes
2 answers
63 views

SQL query with multiple criteria in it

I'm trying to query into a database, but I have to insert multiple conditions. Fake example: #of books in the library currently, Of those books, count how many are overdue, Of those books, count how ...
Ian Oh's user avatar
  • 11
0 votes
0 answers
20 views

Get the total number of items in a main category and all its subcategories (and levels)

I want to get the total number of items (articles) in a main category and all its subcategories. Joomla determines this only for each category separately. Here is the generated DB query from Joomla 4 -...
mikael's user avatar
  • 1
-1 votes
1 answer
36 views

Call a CTE based on a criterion - Case statement SQL [closed]

I have two CTEs with the same structure but reading data from two different tables. Based on a date filter how do I call a CTE using an IF or CASE statement in SQL? Something like this: with ...
moikoi's user avatar
  • 25
-1 votes
1 answer
35 views

How to more efficiently write multiple EXISTS subquery in Postgresql

I'm querying my database where a workflow has multiple of a specific property in a related table. I've managed to write a query that correctly gets the results but it is using multiple subqueries, and ...
CorayThan's user avatar
  • 17.2k
-1 votes
2 answers
73 views

getting message Incorrect syntax near ')' in the last line

I am getting this message in SQL Server 2019: Msg 102, Level 15, State 1, Line 17 Incorrect syntax near ')'. I am getting the error in the last line. What mistake am I making? Select count(*) from ( ...
rereer's user avatar
  • 3
1 vote
0 answers
9 views

TypeOrm - pass column result to a subquery

I want to create a query builder in TypeOrm and search for accounts by some criteria, but I am using a subquery in the where clause, and there I have an equality check (id1 = id2), but one of them (...
Yurii Pakhota's user avatar
-2 votes
2 answers
39 views

SQL - Remove Duplicate Rows Based on a Single Column

I have a dataset with duplicate IDs, different scores, and different days like this I want one row per ID based on the maximum value of day. This is the output I want The query I currently have is ...
mapleleaf's user avatar
  • 756
2 votes
1 answer
79 views

how to get number of records from last 30 days using SQL query

I am fetching a data for current day with the following SQL but i want the data to for last 30 days with percentage of each of stage here is my SQL DECLARE @date DATE SET @date = CONVERT(DATE, GETDATE(...
Pratex's user avatar
  • 55
-1 votes
0 answers
67 views

MariaDB subquery returns different rows when joined

I have a problem with an SQL query on MariaDB. I am using a subquery, either as JOIN (SELECT ...) or as CTE to get some grouped values and two additional rows to join those values. WITH Systems AS ( ...
Alex Bernhard's user avatar
0 votes
1 answer
21 views

Stuck on single row subquery returning more than one row in SQL update statement

Hoping somebody might be able to shine some light on this predicament. How can I work around this, and why does SQL think it's returning multiple lines. It's just a case statement which should ...
allenator's user avatar
0 votes
0 answers
40 views

how to select and sum both in subquery and query?

I want to sum all the logs. Each log has a facility_id, card_id, and login date. I join table logs with table members to calculate the age and gender. The table I want: However, the returned value ...
FaFa's user avatar
  • 358
-1 votes
1 answer
64 views

Isn't JOIN's ON clause predicate?

For the below query to find customer growth YOY based on product orders. SELECT Cur.orderyear, Cur.numcusts AS curnumcusts, Prv.numcusts AS prvnumcusts, Cur.numcusts - Prv.numcusts ...
wenn32's user avatar
  • 1,264
-1 votes
3 answers
37 views

Efficient MySQL SELECT last occurence <= date, IF this last occurence matches an additional condition

I have a MySQL dev_table with thousands of products identified by their Name, containing changes to price and availability (among other values) over time. The table contains only the dates where a ...
co-operate's user avatar
-1 votes
3 answers
105 views

SQL query to get the lowest salary

I have been given a task to get the lowest salary of all employees of each department and job (ignoring the commission earned) from our SQL Server database. Here is an example: emp_id emp_name ...
avaerl liem's user avatar
-2 votes
2 answers
43 views

SQL query to exclude rows from the main query based on a sub-query that checks ALL rows exist

I have a query that returns data from a main table (Works) and pulls in some addition data (Publishers) using a sub-query in the SELECT list, that is then grouped up into a CSV list. Something like ...
DevTC's user avatar
  • 3
1 vote
1 answer
99 views

How to simplify repeating CASE statements containing subqueries

I've built a query that satisfies the following logic: For current month pull current values from table H joined on Material. For previous 2023 months pull values from historic table HHistory joined ...
Jack Morris's user avatar
-2 votes
1 answer
27 views

How to prevent the same result from appearing multiple times in a subquery

I am working in a dataset that I have captured and brought to MySQL tables for analysis. We do not have the source code for the original software, and pulled our data down using an API. In this ...
Sam Alsalem's user avatar
0 votes
2 answers
41 views

PostgreSQL: Combine two JSON objects into a single JSON object

I am using PostgreSQL 15 and have the following two statements in PL/pgSQL: -- Statement 1 SELECT to_json(T) FROM (SELECT * FROM category WHERE category.id = 43) T) -- Statement 2 SELECT ...
user1107173's user avatar
  • 10.4k
-2 votes
1 answer
42 views

Combine multiple columns from multiple rows with unique id?

I am trying to figure out how to create a query that will take the data below, which has a UniqueId column, and name value pairs for the additional columns and display it like the second table, but ...
KateMak's user avatar
  • 1,619
1 vote
0 answers
25 views

PostgreSQL - Subquery gives different results inside and outside function

I have 2 identical queries except for one being inside a function and the other outside a function and they produce different results. Originally I wrote the query outside a function substituting ...
dev01's user avatar
  • 97
-1 votes
1 answer
21 views

MySQL Calculate the sum of four different columns under two different grouping

I am trying to calculate total purchases in USD and LRD, and total sales in USD and LRD I have a table in my datable called wp_wpdt_clients_purchases_n_sales, which has the following columns: id, ...
JoseLawrence's user avatar
-2 votes
3 answers
43 views

what sql query should i write to find rollno of student whose average marks are maximum where marks and student are different tables?

this is my student table stud table rollno name 1 A 2 B 3 C 4 B 5 D 6 C this is my marks table marks table rollno mar eng maths phy chem 1 40 45 38 50 50 2 28 50 45 41 38 3 41 42 43 44 45 ...
samarjeet desai's user avatar
-1 votes
1 answer
47 views

filter where the last value is not status = 'cancel' with cte and subquery

CREATE TABLE origin_polis ( cif INT, no_polis TEXT, status TEXT, tgl_produksi DATE, tgl_awal DATE, tgl_akhir DATE ); INSERT INTO origin_polis (cif, no_polis, status, ...
Napier's user avatar
  • 227
0 votes
1 answer
33 views

Getting "Scalar subquery produced more than one element" Error

SELECT CONCAT(warehouse.warehouse_id,warehouse.warehouse_alias) AS warehouse_name, (SELECT COUNT(*) FROM focused-mote-392209.warehouse_orders.orders AS orders GROUP BY orders....
Fahrettin Gazi's user avatar
-1 votes
2 answers
40 views

Optimizing MySQL query with group_concat

I have an old PHP5 MySQL webapp whose code had to be adapted to PHP8/MySQL14.14 There's a view, querying few tables and based on that code: (SELECT `db_demandes`.`bdd`.`id` AS `Id`, `...
popolon59's user avatar
0 votes
1 answer
47 views

SQL Sub Query in Case statement

I have two tables: Employee Name Salary Gaurav 2000 John 5500 Wayne 6500 Sam 1000 Threshold id MinSalary Maxsalary band Startdate Enddtl 1 0 3000 Junior 2023-08-01 2023-08-01 2 3001 5000 ...
Gaurav Jan's user avatar
-1 votes
1 answer
33 views

Getting Invalid Identifier error when I do not use ALIAS in the second Sub Query after LEFT JOIN

I am joining two subquery tables (Code below) using LEFT JOIN, and I am getting SQL compilation error: error line 72 at position 19 invalid identifier 'PO.OI_EBELN' error when I do not use ALIAS for ...
Kartik's user avatar
  • 1
0 votes
1 answer
71 views

How to set default values from a query?

I need to include a new column to my table, the column is not nullable, I want to set the default value from another table, is there possible? I'm trying to do something like that: ALTER TABLE ...
TryMe's user avatar
  • 25
-4 votes
2 answers
46 views

Msg 512, Level 16, State 1, Line 78

I am getting above error in following code: select CustomerName, OrderDate from [Sales].Customers join Sales.Orders on Sales.Orders.CustomerID = Sales.Customers.CustomerID where OrderDate = (select ...
Amritpal Singh's user avatar
0 votes
1 answer
36 views

Sub Select using different where coluimns

I have a table and I want the sum of column 1 (just an example) if column 2 has a data the average of column 1 (just an example again) if columns 2 is empty it to be grouped by name and have the ...
XcelNewbie's user avatar
0 votes
0 answers
46 views

Oracle SQL query with Left Joins and concatenated values taking too much time to run

I have joined 3 subqueries to obtain a final result. However, the issue is that it is taking 45 minutes to return the result. I need help in optimizing the time taken to run the query and return the ...
ShariefXUsman's user avatar
2 votes
1 answer
92 views

Filtering snowflake view subquery

I have a view definition in a Snowflake database that involves a subquery with some join conditions. When I select data from the view and apply certain filters to the main query, the filters don't ...
working-yoghurt-1995's user avatar
0 votes
0 answers
34 views

MySQL INNER JOIN subquery select one row from second table

I am trying to merge two separate queries that work into one query that would also work. I have several tables and need some data from all of them. I have a table of tasks (this is just the tasks ...
AeroMaxx's user avatar
  • 207
-3 votes
1 answer
60 views

Charindex error invalid length in RIGHT function

I have a SQL Server View similar to this: SELECT BATCHID, BATCHNO, OPENDATE, RIGHT(LEFT(BATCHNO, LEN(BATCHNO) - LEN(RIGHT(BATCHNO, CHARINDEX('-', REVERSE(BATCHNO)) - 1)) - 1), CHARINDEX('-', ...
AlexisPa's user avatar
0 votes
0 answers
39 views

Dynamic instantiation in a sub-query is unsupported

I have a Car entity that contains a list of Price entities. When retrieving the car from the database I can map it directly to my ViewCar DTO, but not so the list of prices. Here is my ViewCar Dto: ...
overheated's user avatar
0 votes
0 answers
36 views

django, order parent object list by child list attribute

I have some items that change hands and i keep track of all the owners and when they changed (using an sqlite3 db). i want to get only the most recent owner for each item, ordered by owner's name. For ...
Erd's user avatar
  • 1
0 votes
0 answers
60 views

Convert SQL Query with Subquery to Drift notations

How to convert this SQL query to Drift syntax without using custom query? SELECT t.*, a."end" FROM trackers as t LEFT JOIN ( SELECT tracker, MAX(activities."end") as ...
Bang Dida's user avatar
-2 votes
2 answers
86 views

Please explain the execution of this simple SQL query

DDL & DMLs for creating this table: Create table If Not Exists Delivery (delivery_id int, customer_id int, order_date date, customer_pref_delivery_date date); Truncate table Delivery; insert ...
ZEESHAN AHMED's user avatar
0 votes
2 answers
78 views

Convert Inner Join to Subquery in PostgreSQL

I am joining two tables with the student table using the inner join below: select (first_name || ' ' ||last_name) as "Student Name", gender, race from student inner join gender on student....
Sam's user avatar
  • 1
0 votes
0 answers
12 views

Struggling with a DAX Measure and Need Assistance

I am trying to recreate this Tableau LOD calculation in Power BI using DAX. The data is sourced from a single table and there will be slicers applied to the PBI report page, as well as potentially ...
Mike's user avatar
  • 1
0 votes
1 answer
22 views

Oracle - Select rows from a table based on ID's stored in a column

I have written a stored procedure to do some data matching. When it completes I update a MATCH_DETAILS column stating that it has matched with an ID but it could have matched with other ID's also. I ...
mcquaim's user avatar
  • 159
0 votes
0 answers
31 views

Django: How to count objects from subquery filtered by ArrrayField

I have three models linked by ForegnKeys. For the sake of example let`s say they look like this: class Study(models.Model): obligatory_assignments = fields.ArrayField(models.CharField(max_length=...
Panklac662's user avatar
0 votes
0 answers
12 views

GROUP BY on a FROM SUBQUERY takes too long [duplicate]

This was supposed to be a fairly easy query but somehow i'm stuck at it. I have a history table with two column, (string)barcode_member and (timestamo)borrow_date. I want to get the five member that ...
meuthecat's user avatar
0 votes
0 answers
12 views

SQL Nested Query - Count not returning correct results

The inner query works perfectly and gives me a count of correct and incorrect answers of a quiz for each student, I have a student that is assigned two questions, They have answered one question ...
Observer's user avatar
0 votes
1 answer
40 views

Is there a way to limit a query based on the result of another in sqlite?

I'm searching for something similar to this question, but for sqlite3. Is this possible?
Maz's user avatar
  • 63
0 votes
0 answers
36 views

ERROR: subquery must return only one column - postgresql

I'm trying to query a report and it's returning this and I don't know how to resolve it. Can someone help me? select ` public.produtofornecedor.id_fornecedor,` `` public.fornecedor....
Luiz 's user avatar
1 vote
2 answers
56 views

SQL Join based on two different date columns

Given that I have these two following tables: level_table id level_date level 300 2021-05 C 300 2020-04 C 300 2019-08 C 300 2022-06 C 300 2019-02 C 300 2018-01 C 300 2023-05 C 300 2021-11 C ...
Alf's user avatar
  • 117
0 votes
0 answers
11 views

In scalar subquery getting error in column alias [duplicate]

Select Movie_Title , cast(replace(Box_Office_Revenue_,'$','') as signed) movieCol From sales.google_movie_data movie Join (Select round(avg(replace(Box_Office_Revenue_,"$","")),2) ...
Anubhav Srivastava's user avatar

1
2 3 4 5
227