MySQL:按组内排序
我有一个mysql表,如下所示:MySQL:按组内排序,mysql,sql-order-by,Mysql,Sql Order By,我有一个mysql表,如下所示: mysql> select * from pt_onhand where pn = '000A569011'; +------------+-----+----+--------+------------+---------+--------------+-----+ | pn | pa | mn | ACTIVE | locate | onhand | avg_cost | whs | +------------+--
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|
+-------------+-------------+--------------+
我想执行如下查询:
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|
+-------------+-------------+--------------+
所以我的问题是:我能在同一个查询中得到与最大(定位)PF120136.1相关的平均成本5.4785156200吗,如何得到?谢谢虽然有点小麻烦,但它应该可以做到:
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
您还可以执行以下子查询:
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;
但是,根据数据库的大小,可能无法很好地执行,请全部尝试,看看哪个最适合您您将不得不编写额外的内部查询。然而令人失望。这在sqlite中可以正常工作,甚至可能不会在其他dbms中编译。因为这个原因,我不喜欢mysql