sql根据日期差异筛选行

frebpwbc  于 2021-06-17  发布在  Mysql
关注(0)|答案(4)|浏览(320)

MySQL5.6有一个我查询的表:

SELECT DISTINCT client, date_buy
FROM tickets
ORDER BY client, date_buy

这几乎给了我想要的结果:

------------------------------
client          | date_buy
-------------------------------
0027847524333  | 2018-06-13 16:03:43
0027847524333  | 2018-06-13 16:13:01
0027847524333  | 2018-06-18 22:03:01
0033652356025  | 2018-06-16 17:22:56
00353857861869 | 2018-08-13 17:37:56

我需要在查询中添加什么,以便只保留订单间隔超过24小时的客户?
期望结果:

------------------------------
client          | date_buy
-------------------------------
0027847524333  | 2018-06-13 16:03:43
0027847524333  | 2018-06-18 22:03:01
0033652356025  | 2018-06-16 17:22:56
00353857861869 | 2018-08-13 17:37:56

更新:我想排除重复销售的一个客户发生在24小时内对方。

1hdlvixo

1hdlvixo1#

您可以这样做:

SELECT * 
FROM tickets t_1, tickets t_2
where t_1.client = t_2.client
and DATEDIFF(hour, t_1.date_buy, t_2.date_buy) < 24
kknvjkwl

kknvjkwl2#

这里有一个使用lag的解决方案

SELECT client, date_buy
FROM (SELECT client, date_buy, 
        DATE_ADD(IFNULL(LAG(date_buy, 1) OVER(PARTITION BY client ORDER BY client, date_buy ASC), '1900-01-01 00:00:00'), INTERVAL 24 HOUR) prev_date
      FROM tickets) sub
WHERE date_buy > prev_date
bq9c1y66

bq9c1y663#

你可以试着用 group byDATE(date_buy) 以及 client 而不是 DISTINCT . 那就去吧 MIN(date_buy) 做你的 date_buy 架构(mysql v5.7)

CREATE TABLE tickets(
  client varchar(50),
  date_buy datetime
);

insert into tickets values ('0027847524333', '2018-06-13 16:03:43');
insert into tickets values ('0027847524333', '2018-06-13 16:13:01');
insert into tickets values ('0027847524333', '2018-06-18 22:03:01');
insert into tickets values ('0033652356025', '2018-06-16 17:22:56');
insert into tickets values ('00353857861869','2018-08-13 17:37:56');

查询#1

SELECT client, MIN(date_buy) date_buy
FROM tickets
GROUP BY DATE(date_buy),client
ORDER BY client, MIN(date_buy);

| client         | date_buy            |
| -------------- | ------------------- |
| 0027847524333  | 2018-06-13 16:03:43 |
| 0027847524333  | 2018-06-18 22:03:01 |
| 0033652356025  | 2018-06-16 17:22:56 |
| 00353857861869 | 2018-08-13 17:37:56 |

db fiddle视图

dnph8jn4

dnph8jn44#

看来 date_buy 列是smalldatetime类型(如果不是,您可以轻松地将其解析为)。
下面是实现查询的一种方法。首先创建一个包含自上一个订单以来少于或等于24小时的所有后续客户机的表:

CREATE TABLE helper AS
SELECT DISTINCT b.client AS cl
FROM tickets AS a, tickets AS b
WHERE DATEDIFF(hour, a.date_buy, b.date_buy) <= 24 AND a.client = b.client

然后,从中选择所有其他客户端 tickets :

SELECT DISTINCT client, date_buy
FROM tickets, helper
WHERE client <> cl
ORDER BY client, date_buy

通过从中删除条目,可以获得相同的结果 tickets ,尽管这会改变原始表。此解决方案考虑了一天中的小时差异。

相关问题