我有两个表:
操作(op_id,super,name,last) 订单(或编号,数量)
操作:
+--------------------------------+ |op_id| super| name | last| +--------------------------------+ |1 1 OperationXX 1 | |2 1 OperationXY 2 | |3 1 OperationXC 4 | |4 1 OperationXZ 3 | |5 2 OperationXX 1 | |6 3 OperationXY 2 | |7 4 OperationXC 1 | |8 4 OperationXZ 2 | +--------------------------------+
订单:
+--------------+ |or_id | number| +--------------+ |1 2UY | |2 23X | |3 xx2 | |4 121 | +--------------+
我需要查询才能获取表:
+-------------------------------------+ |or_id |number |max(last)| name | |1 2UY 4 OperationXC| |2 23X 1 OperationXX| |3 xx2 2 OperationXY| |4 121 2 OperationXZ| +-------------------------------------+
答案 0 :(得分:2)
使用corelared子查询并加入
select o.*,a.last,a.name from
(
select super,name,last from Operations from operations t
where last = (select max(last) from operations t2 where t2.super=t.super)
) a join orders o on t1.super =o.or_id
您也可以使用row_number
with cte as
(
select * from
(
select * , row_number() over(partition by super order by last desc) rn
from operations
) tt where rn=1
) select o.*,cte.last,cte.name from Orders o join cte on o.or_id=cte.super
答案 1 :(得分:0)
SELECT Orders.or_id, Orders.number, Operations.name, Operations.last AS max
FROM Orders
INNER JOIN Operations on Operations.super = Orders.or_id
GROUP BY Orders.or_id, Orders.number, Operations.name;
我目前无法测试此方法,但我认为就是这样。
此外,您没有指定外键,因此联接可能是错误的。