2016-06-13 41 views
0

我有1900个位置,我试图找到订单的最大日期。以及相关位置/日期的订单成本和订单数量。SQL Server - Max有关多条记录和相关数据的日期

如何构建子查询或连接以检索此数据。

举例如下尝试:

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 

我敢肯定,我的逻辑是关闭的加我得到了“关于谓语运营商的每一边的元素数量不匹配”的错误。可能是因为我在主查询中需要更多的列,而不是我在查询子查询中。

任何指导表示赞赏。

+0

? – Backtrack

+0

@Backtrack标题和标签表明是的,除非OP非常困惑,我敢肯定这不是真的:-) –

+0

你可以为每个表格添加一些样例记录,并且您希望样品返回的输出结果? –

回答

0
;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 

如果您正在使用MSSQL,您可以您使用MSSQL使用CTE

+0

对不起,我正在使用SQL Server。更具体地说,我正在通过SSIS包构建数据流任务。 –

+0

我想查看|商店1 | 6/13/2016 | $ 200 | 245 ....正在定位|商店最大日期下订单|订单成本|订单数量 –

+0

@rashaad_hannah,新增订单。它会给你结果 – Backtrack