SQL用于不同日期的数据处理

问题描述 投票:0回答:1

假设我有两个表(客户和发票)。 我想根据x个月的第一个发票日期了解最新客户。例如,一个客户可能在11月加入/注册,但是有可能他在1月下了第一笔订单。因此,按照我的标准,他是新客户。示例表如下:e

所需结果:以下只是上述示例数据的一个示例。 C5客户于2019年8月加入,但他于2020年1月下了第一笔订单。所以对我来说,他是一位新客户。enter image description here

mysql sql
1个回答
0
投票

如果要过滤在给定日期之后下了第一笔订单的客户,只需使用汇总:

select customer, min(date) first_invoice_date
from invoices
group by customer
having first_invoice_date > @somedate

您可以根据需要调整(或删除)having子句。

如果您想要客户的详细信息(例如,其姓名和姓氏,那么您可以加入客户表:

select c.*, o.first_invoice_date
from customers c
inner join (
    select customer, min(date) first_invoice_date
    from invoices
    group by customer
    having first_invoice_date > @somedate
) i on i.customer = c.id
© www.soinside.com 2019 - 2024. All rights reserved.