You are on the right track, but you're missing a few things.
SELECT max(OrderDate), CustomerID, EmployeeID,
( select sum(ShipperID) from [Orders]
WHERE OrderDate <= '1996-07-15'
)
FROM [Orders]
WHERE OrderDate <= '1996-07-15';
SELECT OrderDate, CustomerID, EmployeeID,
( select sum(ShipperID) from [Orders] inside
WHERE inside.OrderDate <= outside.OrderDate
)
FROM [Orders] outside
WHERE OrderDate between '1996-07-11' and '1996-07-15';
WITH SumZ as (select sum(ShipperID) as zColumn from [Orders] inside
WHERE inside.OrderDate <= '1996-07-15')
SELECT OrderDate, CustomerID, EmployeeID, SumZ.zColumn
FROM [Orders] outside, SumZ
WHERE OrderDate between '1996-07-11' and '1996-07-15';
I used a different dataset, but to the same effect.*
https://www.w3schools.com/sql/trysql.asp?filename=trysql_op_in
Since you want all the z
columns to be the same, using a WITH
(actually called a "common table expression" or CTE) prevents your query from running the same sub-query multiple times. Since there's nothing to JOIN
with, I didn't do one, but you can JOIN
on a CTE just like any other table, view, etc.
Further readin on CTEs:
https://www.essentialsql.com/introduction-common-table-expressions-ctes/
and
When to use Common Table Expression (CTE)
It queries the Orders
table based on the "largest" Date
, gets the data from 3 columns of that row, and sums the values of a 4th column based on the same criteria as the outer query.
*In my example, the data is just there for an example and doesn't mean anything useful. Also, I simplified the date selection, since the data I used didn't actually include a Date
column. Turns out, it is a Date
column.