2 alphaes alphaes 于 2015.06.29 09:55 提问

mysql 按月分组,取每月日期小的

DROP TABLE IF EXISTS t_test;

/*!40101 SET @saved_cs_client = @@character_set_client /;
/
!40101 SET character_set_client = utf8 /;
CREATE TABLE t_test (
id int(11) NOT NULL AUTO_INCREMENT,
org varchar(10) DEFAULT NULL,
status date DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
/
!40101 SET character_set_client = @saved_cs_client */;

-- Dumping data for table t_test

LOCK TABLES t_test WRITE;
/*!40000 ALTER TABLE t_test DISABLE KEYS /;
INSERT INTO t_test VALUES (1,'qwe','2015-02-09'),(2,'qqq','2015-03-03'),(3,'www','2012-02-11'),(4,'qwe','2015-03-10'),(5,'asd','2015-04-10'),(6,'fff','2015-05-10'),(7,'aaa','2015-10-10'),(8,'fff','2015-03-10'),(9,'www','2012-02-01'),(10,'asd','2015-03-02'),(11,'qwe','2015-03-26'),(12,'www','2012-03-11');
/
!40000 ALTER TABLE t_test ENABLE KEYS */;
UNLOCK TABLES;


上面是表里面测试数据,按照月份分组,取每个月日期最小的数据

2个回答

alphaes
alphaes   2015.06.29 16:35
已采纳

select * from t_test t where t.status=(select min(status) from t_test tt where t.org=tt.org
and TIMESTAMPDIFF(MONTH,t.status,tt.status)=0);


alphaes
alphaes   2015.06.29 13:26

就没人回答下吗,按照org分组,如果有相同月份的,取时间最早的一条数据,例如 1 qwe 2015-3-22 4 qwe 2015-3-11 6 qwe 2015-4-11 取id为4和6的数据

Csdn user default icon
上传中...
上传图片
插入图片