【问题标题】:Select first row numeric values in SQL (Redshift) group by选择 SQL (Redshift) 分组中的第一行数值
【发布时间】:2019-07-12 19:39:20
【问题描述】:

我有一个如下结构的表:

ID    latitude   longtitude   other..columns
A12    54.55        -43.26       .
A21    57.00        -43.25       .
V51    54.55        -44.25       .
V51    54.50        -43.25       .
A12    55.11        -43.15       .
B43    50.16        -43.25       .

我按ID 对表格进行分组,并按平均值和最小值/最大值聚合其他列。 然而,当谈到纬度/经度时,我想通过任何聚合(最小值或最大值,无关紧要)选择一个纬度,并选择它的等效经度(例如 A12 -> 54.55&-43.26) ,而不是单独聚合为平均值或最小值/最大值。

是否有一种智能且简单的方法来构建此查询?

当前查询类似于:

select 
avg(other_columns),
min(latitude),
?(longtitude)
from table
group by ID;

编辑:在 cmets 之后明确要求。

【问题讨论】:

  • 没有“第一对可用”之类的东西,除非列指定了顺序。
  • "...the first pair available..." -- 由于表格行没有任何固有顺序,因此没有“第一”行。你需要告诉我们你的句子使用什么顺序才有意义。
  • 没有指定顺序的列。假设我选择了最小纬度,我想选择它对应的经度。这就是我所说的配对(编辑问题以进行澄清)

标签: sql group-by gis amazon-redshift latitude-longitude


【解决方案1】:

您总是可以根据纬度和经度制作一对,例如通过转换为字符串并将它们连接起来(我相信 Redshift 不支持结构,否则它会是更好的选择):

cast(lat as string) || '&' || cast(lon as string)

然后选择例如这对的最小值,最后使用 SPLIT_PART 函数将其拆分回来。

【讨论】:

    【解决方案2】:

    如果您有指定排序的列,则可以使用first_value()。唉,虽然没有聚合函数,所以你可以将select distinct 与窗口函数一起使用:

    select distinct id, 
           avg(other_columns) over (partition by id),
           first_value(latitude) over (partition by id order by ? rows between unbounded preceding and current row),
           first_value(longitude) over (partition by id order by ? rows between unbounded preceding and current row)
    from table;
    

    或者,您可以使用子查询和row_number()

    select id, 
           avg(other_columns),
           max(case when seqnum = 1 then latitude end),
           max(case when seqnum = 1 then longitude end)
    from (select t.*, row_number() over (partition by id order by ?) as seqnum
          from t
         ) t
    group by ID;
    

    【讨论】:

    • 我也许可以为所有行添加不同的索引,以使用 first_value()
    • @guyts 。 . .我认为 Redshift 不支持索引。
    • 我最终使用 lat 和 long 作为排序列,因为顺序无关紧要。并使用了first_value,但语法完全不同
    • @guyts 。 . .我不确定“语法完全不同”是什么意思。这是 Redshift 语法:docs.aws.amazon.com/redshift/latest/dg/r_WF_first_value.html.
    • 是的,从他们的示例中,我得到了实际工作的代码。缺少rows between docs.aws.amazon.com/redshift/latest/dg/… 的关键部分
    猜你喜欢
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    相关资源
    最近更新 更多