在每个日期的材料上选择最大ID

时间:2014-02-14 17:35:32

标签: php mysql select

我的表名为sup_mon:

genmat_id    mat_name    size     Stock_balance     date   
1              aluminum   100 m       25            2014-02-27
2              aluminum   100 m       30            2014-02-27
3              steel      100 m       60            2014-02-27
4              aluminum   100 m       30            2014-02-28

这是我的独特选择查询:

select distinct mat_name, Stock_balance, date, max(genmat_id) from sup_mon where date = '2014-02-27'

输出结果为:

 genmat_id    mat_name    size     Stock_balance     date   
      3           steel      100 m       60         2014-02-27

如何在日期的最高genmat_id上选择每个唯一的材料名称? 喜欢:

 genmat_id    mat_name    size     Stock_balance     date   
    2              aluminum   100 m       30            2014-02-27
    3              steel      100 m       60            2014-02-27

2 个答案:

答案 0 :(得分:2)

如果您想为每个max(genmat_id)mat_name返回date,那么您可以使用子查询来获得最终结果:

select t1.genmat_id,
  t1.mat_name,
  t1.size,
  t1.stock_balance,
  t1.date
from yourtable t1
inner join
(
  select max(genmat_id) genmat_id, date, mat_name
  from yourtable
  group by date, mat_name
) t2
  on t1.genmat_id = t2.genmat_id
  and t1.date = t2.date
  and t1.mat_name = t2.mat_name
where t1.date = '2014-02-27';

SQL Fiddle with Demo。子查询返回每个日期和mat_name的最大ID,然后将其加入到genmat_iddatemat_name的表格中,以获得最终结果。< / p>

答案 1 :(得分:0)

这样的事情应该有效:

SELECT m1.*
FROM sup_mon m1 LEFT JOIN sup_mon m2
 ON (m1.mat_name = m2.mat_name AND m1.genmat_id < m2.genmat_id )
WHERE m2.genmat_id IS NULL and date = '2014-02-27'

注意:改编自this example