简体   繁体   English

过滤日期 同 SQL

[英]Filtering date With SQL

I have table like this:我有这样的表:

customer_id    date    order_id
12           1/11/2021     2
12           22/11/2021    3
12           31/11/2021    5
42           1/11/2021     2
42           15/11/2021    2
42           31/11/2021    2
43           22/11/2021    1
43           25/11/2021    2

Yemen I want to select only the customer_id that are 30 days between their first and last purchase, Then make a join with the product table, which means something like this:也门我想 select 仅是他们第一次和最后一次购买之间 30 天的customer_id ,然后与产品表进行连接,这意味着这样的事情:

customer_id    date    order_id   Product_name
12           1/11/2021     2         apple
12           22/11/2021    3         car
12           31/11/2021    5         orange
42           1/11/2021     2         apple
42           15/11/2021    2         apple
42           31/11/2021    2         apple

for example:例如:

select customer_id, date, order_id, product_name
left join product on order_id = product_id
where customer_id.max(date) - customer_id.min(date) = 30 

Select original rows matching the criteria Select 原始行符合条件

select customer_id, date, order_id
from 
    (select customer_id, date, order_id
     , max(date) over (partition by customer_id) dmax
     , min(date) over (partition by customer_id) dmin
     from myTable
    ) t
where date in (dmax, dmin) and datediff(day, dmin, dmax) = 30  

and join the output and Products on order_id = product_id并在 order_id = product_id 上加入 output 和Products

select s.*, p.product_name
from (
    select customer_id, date, order_id
    from 
        (select customer_id, date, order_id
         , max(date) over (partition by customer_id) dmax
         , min(date) over (partition by customer_id) dmin
         from myTable
        ) t
    where date in (dmax, dmin) and datediff(day, dmin, dmax) = 30  
) s
join Product p on s.order_id = p.product_id;

If I understand you correctly and you want to select only the customer's id (not the rows with min and max dates for each customer), a statement using GROUP BY , HAVING and DATEDIFF() is an option:如果我理解正确并且您只想 select 客户的 ID(不是每个客户的最小和最大日期的行),则可以选择使用GROUP BYHAVINGDATEDIFF()的语句:

SELECT customer_id
FROM (VALUES
   (12, CONVERT(date, '20211101'), 2),
   (12, CONVERT(date, '20211122'), 3),
   (12, CONVERT(date, '20211130'), 5),
   (42, CONVERT(date, '20211101'), 2),
   (42, CONVERT(date, '20211231'), 2),
   (43, CONVERT(date, '20211122'), 1)
) t (customer_id, date, order_id)
GROUP BY customer_id
HAVING DATEDIFF(day, MIN(date), MAX(date)) <= 30

Result:结果:

customer_id
12
43

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM