如何在MAX使用期间选择多个列

时间:2018-02-02 08:41:13

标签: mysql

我正在尝试编写一个查询,该查询获得了一个人支付的最高金额以及为我的数据库中的每个人处理付款的日期。我的问题是查询运行的时间我得到一个不同的日期,因为它没有将Max(pmt_amout)与记录的日期相关联。我的目标是能够为所有人运行查询。这是我到目前为止所拥有的。

select person_id, 
MAX(pmt_amount) as greatest_payment, 
pmt_date as greatest_payment_date
from payments p 
group by person_id

非常感谢你的帮助!

2 个答案:

答案 0 :(得分:0)

您可以针对您的问题尝试此解决方案:

表格结构实际已实施:

表:

CREATE TABLE payments ( 
id MEDIUMINT NOT NULL AUTO_INCREMENT,
person_id int(25),
pmt_amount int(25),
pmt_date date,
PRIMARY KEY (id) ) #ENGINE=MyISAM;

插入声明:

INSERT INTO payments (person_id,pmt_amount,pmt_date)
  VALUES(1,50500,'2017-05-12');
  INSERT INTO payments (person_id,pmt_amount,pmt_date)
  VALUES(1,50500,'2018-05-12');
  INSERT INTO payments (person_id,pmt_amount,pmt_date)
  VALUES(1,10200,'2018-05-12');
  INSERT INTO payments (person_id,pmt_amount,pmt_date)
  VALUES(2,80200,'2018-05-12');
  INSERT INTO payments (person_id,pmt_amount,pmt_date)
  VALUES(3,9300,'2018-06-12');
  INSERT INTO payments (person_id,pmt_amount,pmt_date)
  VALUES(3, 15000,'2018-04-12');
  INSERT INTO payments (person_id,pmt_amount,pmt_date)
  VALUES(4,18000,'2018-03-12');
  INSERT INTO payments (person_id,pmt_amount,pmt_date)
  VALUES(4,15000,'2018-06-12');

查询:

select person_id, 
MAX(pmt_amount) as greatest_payment, 
pmt_date as greatest_payment_date
from payments p 
group by person_id
ORDER BY pmt_date DESC

Ans也会针对您的问题访问SQLfiddle

我希望它会有所帮助。

答案 1 :(得分:0)

您的问题是group语句的错误使用,当所选列不是分组的一部分时,ANY选择值。如@philipxy所述,请检查Error related to only_full_group_by when executing a query in MySql

尝试:

select p.* 
from payments as p INNER JOIN
(select p2.person_id, MAX(p2.pmt_amount) max_amount from payments p2 group by p2.person_id) sub
on p.person_id = sub.person_id and p.pmt_amount = sub.max_amount