dongwupu5991 2016-02-26 14:36
浏览 42
已采纳

检查表中较早的特定ID行是否出现

I have a table of customer orders which is something like below:

order_id | customer_id |    date    | ...
-----------------------------------------
   583         192       2015-05-01   ...
   734         143       2015-06-04   ...
   801         455       2015-07-02   ...
   ...         ...           ...      ...

I want to find how many new customers I receive in a given month. A new customer can be found by querying the orders table above and finding the number of customer_id values that appear in that month but do not appear before that month (after that month is fine). I'm looking for the first instance of a new customer_id.

Is there a way to do this in one SQL statement? I could do something like the below I think:

  • get all order_id and DISTINCT customer_id from a month by querying database using LIKE YYYY-MM-%
  • check the table for instances of customer_id with a smaller order_id (it stands to reason a smaller order_id will be an earlier order)
  • if found, skip
  • if not found, increment a counter
  • 写回答

3条回答 默认 最新

  • dongwen7187 2016-02-26 14:40
    关注

    Assuming date_From is your period start date and date_To is period end date you can do it something like:

    select distinct T1.customer_id
    from your_table as T1
        left outer join your_Table as T2 on 
           T1.customer_id = T2.customer_id and T2.date < date_From
    where
        T1.date <= date_To
        and T1.date >= date_From
        and T2.customer_id is null
    

    Here joining to the same table using same customer_id and date prior to your period and checking that join has no result (by T2.customer_id is null) ensures your customer_id first appears in the order of your period and not earlier.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分