【问题标题】:sql/presto: how to find records that exist before but not current day for each daysql/presto:如何查找每天之前存在但不存在于当天的记录
【发布时间】:2021-12-08 19:26:02
【问题描述】:

我有如下数据:

 item day
  a   1
  b   1 
  c   1
  a   2
  c   2
  d   2
  a   3 
  d   3

而想要的结果是查找对于每一天,在这一天之前消失的记录。期望的结果:

disappeared_item   day_of_interest
        b           2   (as of the second day, only b disappeared)
       b,c          3   (as of the fourth day, b and c disappeared)

我想找出每个项目的最大(天),但在如何获取每天累积的项目方面得到了堆栈

【问题讨论】:

    标签: mysql sql data-manipulation presto


    【解决方案1】:
    WITH 
    items AS ( SELECT DISTINCT item
               FROM test ),
    days AS ( SELECT DISTINCT day
               FROM test )
    SELECT GROUP_CONCAT(items.item) disappeared_item,
           days.day day_of_interest
    FROM items
    CROSS JOIN days
    WHERE EXISTS ( SELECT NULL 
                   FROM test
                   WHERE test.item = items.item
                     AND test.day < days.day )
      AND NOT EXISTS ( SELECT NULL 
                       FROM test
                       WHERE test.item = items.item
                         AND test.day = days.day )
    GROUP BY days.day;
    

    https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=c35dbe8b9b0a0e00f69c542a70be4bfc

    【讨论】:

      猜你喜欢
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 2013-07-08
      相关资源
      最近更新 更多