【问题标题】:How to select rows where values changed for an ID如何选择 ID 值更改的行
【发布时间】:2020-05-26 06:49:57
【问题描述】:

我有一个如下所示的表格

id         effective_date    number_of_int_customers
123        10/01/19            0
123        02/01/20            3
456        10/01/19            6
456        02/01/20            6
789        10/01/19            5
789        02/01/20            4
999        10/01/19            0
999        02/01/20            1

我想编写一个查询来查看每个 ID,以查看销售人员是否在 10 月 1 日至 2 月 1 日之间新开始国际工作。

我正在寻找的结果如下:

id         effective_date    number_of_int_customers
123        02/01/20            3 
999        02/01/20            1

结果将仅返回最初有 0 个国际客户但现在至少有 1 个的销售人员。 我在这里看到过类似的帖子,它们使用嵌套查询来提取第一个日期和最后一个日期具有不同值的记录。但我只想提取原始值为 0 的记录。有没有办法在 SQL 的一个查询中做到这一点?

【问题讨论】:

    标签: sql database subquery mysql-workbench


    【解决方案1】:

    在你的情况下,一个简单的聚合就可以了——假设 0 是最早的值:

    select id, max(number_of_int_customers)
    from t
    where effective_date in ('2019-10-01', '2020-02-01')
    group by id
    having min(number_of_int_customers) = 0;
    

    显然,如果值可以减小到零,则这是不正确的。但是这个having 子句解决了这个问题:

    having min(case when number_of_int_customers = 0 then effective_date end) = min(effective_date)
    

    另一种方法是使用窗口函数,例如first_value():

    select distinct id, last_noic
    from (select t.*,
                 first_value(number_of_int_customers) over (partition by id order by effective_date) as first_noic,
                 first_value(number_of_int_customers) over (partition by id order by effective_date desc) as last_noic,
          from t
          where effective_date in ('2019-10-01', '2020-02-01')
         ) t
    where first_noic = 0;
    

    嗯,转念一想,我更喜欢lag()

    select id, number_of_int_customers
    from (select t.*,
                 lag(number_of_int_customers) over (partition by id order by effective_date) as prev_noic
          from t
          where effective_date in ('2019-10-01', '2020-02-01')
         ) t
    where prev_noic = 0;
    

    【讨论】:

    • 您好!非常感谢你。老实说,我不知道滞后功能或分区(开始在 Youtube 上观看一些视频以了解这两个)。但这正是我需要它做的。再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多