0

我有 1900 个位置,我试图找到下订单的最大(日期)。以及该相关位置/日期的订单成本和订单数量。

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

下面的示例尝试:

    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

我确定我的逻辑不正确,而且我收到“谓词运算符每一侧的元素数不匹配”错误。可能是因为我在主查询中需要的列多于我在子查询中的列。

任何指导表示赞赏。

4

1 回答 1

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,则可以使用CTE

于 2016-06-13T13:13:23.877 回答