【问题标题】:how to group by a specific order?如何按特定顺序分组?
【发布时间】:2018-10-12 13:28:55
【问题描述】:
eid start            end          status
6158963 11/27/2016  1/7/2017    FT
6158963 1/8/2017    5/9/2017    FT
6158963 5/10/2017   5/20/2017   LA
6158963 5/21/2017   7/31/2017   LA
6158963 8/1/2017    9/9/2017    FT
6158963 9/10/2017   10/21/2017  FT
6158963 10/22/2017  12/2/2017   FT
6158963 12/3/2017   12/16/2017  FT
6158963 12/17/2017  12/30/2017  FT
6158963 12/31/2017  3/3/2018    FT
6158963 3/4/2018    4/8/2018    FT

.

以上是我要转换的示例数据。我正在尝试根据状态转换数据。

数据应如下所示:

eid start              end        status
6158963 11/27/2016  5/9/2017    FT
6158963 5/10/2017   7/31/2017   LA
6158963 8/1/2017    4/8/2018    FT

我希望按给定顺序与状态字段进行分组。 但是当我在开始和结束时使用 max 并按状态分组时。它只是将所有状态归为一个。

eid MIN             MAX      status
6158963 11/27/2016  4/8/2018    FT
6158963 5/10/2017   7/31/2017   LA

【问题讨论】:

  • 向我们展示您的尝试,请阅读how-to-ask

标签: sql nzsql


【解决方案1】:

您可以使用row_number() 并根据row_number() 生成的序列差异进行聚合:

select eid, min(startdate) as startdate, max(endate) as endate, status
from (select t.*,
             row_number() over (partition by eid order by startdate) as seq1,
             row_number() over (partition by eid, status order by startdate) as seq2
      from table t
     ) t
group by eid, status, (seq1 - seq2)
order by startdate;

假设startdate & enddates 的格式合理。

【讨论】:

  • 首先将日期转换为可排序格式,如下所示:from_unixtime(unix_timestamp(start,'MM/dd/yyyy'),'yyyy-MM-dd') as start
猜你喜欢
  • 1970-01-01
  • 2012-02-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
相关资源
最近更新 更多