SQL查询从具有单列作为日期的表中获取具有开始和结束日期的记录

时间:2019-03-24 11:08:51

标签: mysql sql

我有一个包含以下数据的表,这里的阶段(1)cr_date是开始日期,阶段(2)cr_date是结束日期,并且同一封电子邮件可以包含有关产品ID的多个条目。

email            stage    product_id   cr_date
--------------- -------- ------------ ------------
123@g.com        1         1           2019-01-10
123@g.com        1         1           2019-01-11
123@g.com        1         1           2019-01-13
345@g.com        1         1           2019-01-25
123@g.com        2         1           2019-01-28
345@g.com        1         2           2019-01-24
345@g.com        2         1           2019-01-31
789@g.com        1         2           2019-02-10
789@g.com        2         2           2019-02-15
567@g.com        2         2           2019-01-18

并且我想查询以获取2019年1月1日至2019年1月31日之间的记录,结果应如下图所示

email           product_id     start_date       end_date
-------------- ------------ ----------------- --------------
123@g.com        1            2019-01-10        2019-01-28
345@g.com        1            2019-01-25        2019-01-31

2 个答案:

答案 0 :(得分:0)

这是解决方案,您需要传递特定的product_id,仅供参考,我正在使用表名users

SELECT A.email,A.product_id,a.cr_date AS start_date,B.cr_date AS end_date 
FROM users A, users B 
WHERE a.email = b.email AND b.stage=2 AND a.stage=1 AND a.cr_date 
BETWEEN '2019-01-01' AND '2019-01-31' 
AND b.cr_date  BETWEEN '2019-01-01' AND '2019-01-31' 
AND a.product_id=1

对于所有产品,请使用以下ID:-

SELECT A.email,A.product_id,a.cr_date AS start_date,B.cr_date AS end_date 
FROM users A, users B 
WHERE a.email = b.email AND a.product_id=b.product_id AND b.stage=2 AND a.stage=1 AND a.cr_date 
BETWEEN '2019-01-01' AND '2019-01-31' 
AND b.cr_date  BETWEEN '2019-01-01' AND '2019-01-31'

答案 1 :(得分:0)

假设电子邮件/产品ID组合中连续没有多个“ 1”或“ 2”,那么您可以使用lead()作为逻辑。

因此,要计算开始日期和结束日期:

select email, product_id, cr_date as start_date, end_date
from (select t.*,
             lead(cr_date) over (partition by email, product_id order by cr_date) as end_date
      from t
     ) t
where stage = 1 and
      cr_date >= '2019-01-01' and
      cr_date < '2019-02-01' and
      end_date >= '2019-01-01' and
      end_date < '2019-02-01';

您可以在MySQL的早期版本中用相关子查询替换lead()