日期:2014-05-16  浏览次数:20917 次

数据分组,去重复记录,急!
SQL code

//表
CREATE TABLE tt (
  `_id` int(11) NOT NULL AUTO_INCREMENT,
  `_keyValue` int(11) DEFAULT NULL COMMENT '主键值'
  `_orderCode` int(11) DEFAULT NULL COMMENT '排序码',
  PRIMARY KEY (`_id`)
)



字段_keyvalue 有重复值的

对_keyvalue进行分组,同类取出_ordercode最小的数据行
如:
_id _keyvalue _ordercode
1 1 0
2 2 1
3 1 1
4 3 1
5 2 0

结果:
_id _keyvalue _ordercode
1 1 0
4 3 1
5 2 0


------解决方案--------------------
CREATE TABLE tt2 ( 
`_id` INT(11) NOT NULL AUTO_INCREMENT, 
`_keyValue` INT(11) DEFAULT NULL COMMENT '主键值' ,
`_orderCode` INT(11) DEFAULT NULL COMMENT '排序码',
KEY (`_id`)
)

_id _keyvalue _ordercode 
 3 3 1 
 4 1 0 
 8 5 1 
 11 8 1 
 12 10 1 
 15 12 1 
 52 2 0
上述结果不对吗?
------解决方案--------------------
参考下贴中的多种方法

http://topic.csdn.net/u/20091231/16/2f268740-391e-40f2-a15e-f243b2c925ab.html
[征集]分组取最大N条记录方法征集,及散分....
------解决方案--------------------
selct a.keyvalue , a.ordercode
from tt a 
left join 
( select keyvalue,min(ordercode) as mincode from tt group by ordercode ) as bwhere 
a.keyvalue=b.keyvalue 
and 
a.ordercode <= b.mincode;
------解决方案--------------------
selct a.keyvalue , a.ordercode
from tt a
left join
( select keyvalue,min(ordercode) as mincode from tt group by keyvalue ) as b
where
a.keyvalue=b.keyvalue
and
a.ordercode <= b.mincode;


写错了 按照keyvalue分组
------解决方案--------------------
select _keyvalue,min(_ordercode)
from tt 
group by _keyvalue