简体   繁体   中英

SQL Server - Max Date for multiple records & related data

I have 1900 locations that I am trying to find the max(date) that an order was placed. And also the order cost and order quantity for that related location/date.

How do I build a sub-query or join in order to retrieve this data.

Example attempt below:

    select table1.location, table2.ord_dt, table2.order_cost, table2.order_qty
    from table2
    join table 3 on table2.id1 = table3.id1
    join table 1 on table1.id1 = table3.id2
    where table2.ord_dt = (
    select table1.location, max(table2.ord_dt)
    from table2
    join table 3 on table2.id1 = table3.id1
    join table 1 on table1.id1 = table3.id2
    group by table1.location

I'm sure my logic is off plus I'm getting a "Number of elements on each side of a predicate operator does not match" error. Probably because I need more columns in my main query than I'm pulling in my sub-query.

Any guidance is appreciated.

;with cte(location, odate) as 
(

   select table1.location, max(table2.ord_dt)
    from table2
    join table 3 on table2.id1 = table3.id1
    join table 1 on table1.id1 = table3.id2
    group by table1.location
)
select table1.location, table2.ord_dt, table2.order_cost, table2.order_qty
    from table2
    join table 3 on table2.id1 = table3.id1
    join table 1 on table1.id1 = table3.id2
    join cte on cte.location =  table1.location and cte.odate = table2.ord_dt
order by 
table1.location, table2.ord_dt, table2.order_cost, table2.order_qty

if you are using MSSQL , you can use CTE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM