以下表的结构和内容,
CREATE TABLE PactRate (
id int(11) NOT NULL auto_increment,
PactId int(11) default NULL,
GatheringYear int(5) default NULL,
PactCost int(11) default NULL,
PRIMARY KEY (id),
UNIQUE KEY id (id)
) TYPE=MyISAM;
INSERT INTO PactRate VALUES (1, 1, 1999, 19990);
INSERT INTO PactRate VALUES (2, 1, 2000, 12000);
INSERT INTO PactRate VALUES (3, 3, 1002, 12000);
INSERT INTO PactRate VALUES (4, 4, 2002, 50000);
INSERT INTO PactRate VALUES (5, 5, 2002, 100);
怎么样得到这样的结果
+------+--------+---------------+---------+
¦id ¦PactId ¦GatheringYear ¦PactCost ¦
+------+--------+---------------+---------+
¦ 2 ¦ 1 ¦ 2000 ¦ 12000 ¦ *
¦ 3 ¦ 3 ¦ 1002 ¦ 12000 ¦
¦ 4 ¦ 4 ¦ 2002 ¦ 50000 ¦
¦ 5 ¦ 5 ¦ 2002 ¦ 100 ¦
+------+--------+---------------+---------+
运行 mysql语句
select * from PactRate group by PactId
只能得到
+------+--------+---------------+---------+
¦id ¦PactId ¦GatheringYear ¦PactCost ¦
+------+--------+---------------+---------+
¦ 1 ¦ 1 ¦ 1999 ¦ 19990 ¦ *
¦ 3 ¦ 3 ¦ 1002 ¦ 12000 ¦
¦ 4 ¦ 4 ¦ 2002 ¦ 50000 ¦
¦ 5 ¦ 5 ¦ 2002 ¦ 100 ¦
+------+--------+---------------+---------+
先按PactId进行分组,如存在同组的记录取 GatheringYear 最大的那条记录
比如各部门每人的业绩报表
按部门号对每个人进行分组,每个人在不同时期有不同的业绩
取的时候取日期最大的那个记录
像2000年 甲业绩是 12000
2001年 甲业绩是 15000
那就取 2001年的那条记录,因为2001>2000
---------------------------------------------------------------
SELECT
SUBSTRING(MAX(CONCAT(gatheringyear,LPAD(id,8,'0'),pactCost)),5,8)+0 AS id,
pactid,
LEFT(MAX(CONCAT(gatheringyear,LPAD(id,8,'0'),pactCost)),4) AS gatheringyear,
SUBSTRING(MAX(CONCAT(gatheringyear,LPAD(id,8,'0'),pactCost)),13) AS pactCost
FROM PactRate GROUP BY pactid;
------------------------------
由于SQL中的GROUP 和 MAX是有优先级之分的,所以如果要用一条SQL语句,就必须对结果进行处理。gatgeringyear定长为4,将id用0补齐8位(应该够你用了)再用MAX(),如果你pactCost是float or double,用相应的办法处理
但如果这个表字段有20来个或者是更多。会显得很是麻烦。
mysql查询方面的功能还是有欠缺.
这是MYSQL为GROUP相关函数提供的经典例子,我稍微修改了一下。有兴趣,参阅
http://www.mysql.com/doc/en/example-Maximum-column-group-row.html