Mysql-排除具有相同分钟的行

时间:2015-07-23 04:47:14

标签: mysql

我想要排除具有相同分钟数的行的结果

示例:customers表

id date
1 2015-07-23 00:06:56
2 2015-07-23 00:11:38
3 2015-07-23 01:10:16
4 2015-07-23 01:10:13
5 2015-07-24 01:13:26
6 2015-07-24 01:13:13

我希望查询排除ID:3,4,5& 6因为(3& 4)和(5& 6)具有相同的分钟

所以预期的结果是:

id date
1 2015-07-23 00:06:56
2 2015-07-23 00:11:38

提前致谢!

3 个答案:

答案 0 :(得分:3)

试一试。子查询找出重复的小时和分钟。外部查询选择除子查询返回的记录之外的所有记录。

select *
from customers
where date_format(dt, '%H%i') not in
(
  select date_format(dt, '%H%i')
  from customers a
  group by date_format(dt, '%H%i')
  having count(*) > 1
)

示例:http://sqlfiddle.com/#!9/88a24/4

按天过滤重复小时+分钟

select *
from test
where date_format(dt, '%Y%j%H%i') not in
(
  select date_format(dt, '%Y%j%H%i')
  from test a
  group by date_format(dt, '%Y%j%H%i')
  having count(*) > 1
)

示例:http://sqlfiddle.com/#!9/fa2da/2

另一个例子:http://sqlfiddle.com/#!9/7eeaf/1(使用来自更新问题的数据)

答案 1 :(得分:1)

您可以使用date列的年,日,小时和分钟部分组成一个组,然后只保留具有一条记录的组。这会过滤掉所有具有重复分钟的记录。然后我JOIN将此临时表返回给您的customers表以获取结果。此解决方案不使用子查询。

SELECT id, date
FROM customers c
INNER JOIN
(
    SELECT id
    FROM customers
    GROUP BY
        EXTRACT(YEAR FROM date),
        EXTRACT(MONTH FROM date),
        EXTRACT(DAY FROM date),
        EXTRACT(HOUR FROM date),
        EXTRACT(MINUTE FROM date),
    HAVING COUNT(*) = 1
) t
ON c.id = t.id

答案 2 :(得分:0)

尝试此查询

select * from tablename
group by date
having count(*)=1