MySQL:按内部顺序排序

时间:2012-09-05 08:22:13

标签: mysql sql-order-by

我有一个像这样的mysql表:

mysql> select * from pt_onhand where pn = '000A569011';
+------------+-----+----+--------+------------+---------+--------------+-----+
| pn         | pa  | mn | ACTIVE | locate     | onhand  | avg_cost     | whs |
+------------+-----+----+--------+------------+---------+--------------+-----+
| 000A569011 | P/A |    |        | AA-112     | 13.0000 | 0.0000000000|     |
| 000A569011 | P/A |    |        | PF120136.1 |  1.0000 | 5.4785156200 |     |
+------------+-----+----+--------+------------+---------+--------------+-----+

我想执行这样的查询:

mysql> select sum(onhand),max(locate),avg_cost from pt_onhand where pn = '000A569011' group by pn;
+-------------+-------------+--------------+
| sum(onhand) | max(locate) | avg_cost     |
+-------------+-------------+--------------+
|     14.0000 | PF120136.1  | 0.0000000000|
+-------------+-------------+--------------+

所以我的问题是这样的:我可以在同一个查询中得到与max(locate)PF120136.1相关的avg_cost 5.4785156200,怎么样?感谢

2 个答案:

答案 0 :(得分:7)

这有点斗志,但它应该做的伎俩:

select a.onhand, a.locate, p.avg_cost
from
    (select sum(onhand) onhand, max(locate) locate from pt_onhand where pn = '000A569011' group by pn) a
    join pt_onhand p on p.locate = a.locate

答案 1 :(得分:3)

您还可以执行以下子查询:

select 
     sum(onhand)
    ,max(locate)
    ,(select avg_cost from pt_onhand where pn = pt.pn and locate = max(pt.locate)) as avg_cost 
from 
    pt_onhand pt 
where 
    pn = '000A569011' 
group by pn;

但是根据你的数据库有多大可能表现不佳,请全力以赴,看哪哪个最适合你