How can I write this correlated subquery by using with clause?

73 views Asked by At

As you can see OrderDate is fetching details from ORDERS but ORDERS has reference in outer query, if I bring inner subquery and store in an object for using with clause that gives me an error. for reference of table I am putting link of tables to follow :

{tables links: source(w3school.com/sql) orders- https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

products- https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all }

Please suggest method to rewrite this subquery by using with clause.

SELECT 
   OBJECT
FROM 
   ( SELECT DISTINCT 
      ( select distinct ORDERS.OrderDate
        from 
           PRODUCTS
        where 
           PRODUCTS.CategoryID = ORDERS.EmployeeID) AS OBJECT 
     FROM
       ORDERS)
1

There are 1 answers

0
Luuk On

The code does run on w3schools.com, but that does not make it correct SQL.

See DBFIDDLE which has the first records of the products table, and some records from the ORDERS table, which shows an error ("Every derived table must have its own alias")

When correcting the query to:

SELECT 
   xyz.*
FROM 
   ( SELECT DISTINCT 
      ( select distinct ORDERS.OrderDate
        from 
           PRODUCTS
        where 
           PRODUCTS.CategoryID = ORDERS.EmployeeID) AS OBJECT 
     FROM
       ORDERS) xyz

You will get an answer in MySQL, see: DBFIDDLE