关于一个sql,六一儿童节快乐~

*查询test表中lotetype字段中有且只有两个相同的记录,且这两条记录中的date_time时间间隔为十分钟,取其中的一条作为结果输出。

表:

CREATE TABLE `test` (
	  `id` varchar(20) COLLATE utf8_swedish_ci,
	  `lotetype` varchar(20) COLLATE utf8_swedish_ci,
	  `date_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
	   UNIQUE KEY `un_id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=331 DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci;


数据:



查询SQL:

select group_concat(distinct t1.lotetype), t1.id,t1.date_time 
from 
	 				(select t.id,t.lotetype,t.date_time from test t ,(select lotetype, count(*) as c from test group by lotetype) tc where tc.c=2 and t.lotetype = tc.lotetype) t1 , 
	 				(select t.id,t.lotetype,t.date_time from test t ,(select lotetype, count(*) as c from test group by lotetype) tc where tc.c=2 and t.lotetype = tc.lotetype) t2 
where  t1.id!=t2.id 
and 		abs(TIME_TO_SEC(timediff( t1.date_time,t2.date_time)) div 60)<10 
and 		t1.lotetype=t2.lotetype 
group by t1.lotetype;
	 

查询结果:



说明:

1. group_concat函数结合group by去除group_concat包含的字段重复项。
2.取lotetype字段总数为2,关键用到group by分组。
3.时间撮是10分钟用到几个函数,abs(TIME_TO_SEC(timediff( t1.date_time,t2.date_time)) div 60) ,abs取正数,TIME_TO_SEC结果是秒钟,div除法函数
期待优化,这是一个面试题(同事面试遇到的,出这样的题目)。



太阳系 - http://blog.csdn.net/fellting


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值