我有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
我确定我的逻辑已关闭,而且我得到了一个"谓词运算符每一侧的元素数量不匹配"错误。可能是因为我在主要查询中需要更多列而不是我拉入子查询。
感谢任何指导。
答案 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 ,则可以使用CTE