【问题标题】:select first and last record of each group horizontally水平选择每组的第一条和最后一条记录
【发布时间】:2018-06-07 04:27:39
【问题描述】:

我有一张像

我想通过 facility_id 和 created_at 水平选择每个组的第一条和最后一条记录 需要像输出一样。我可以垂直做,但需要水平做

【问题讨论】:

    标签: sql postgresql eloquent


    【解决方案1】:
    with CTE as (
      select 
      *
      ,ROW_NUMBER() over (partition by facility_id,name order by created_at asc ) ascrnk
      ,ROW_NUMBER() over (partition by facility_id,name order by created_at desc ) desrnk
      from TestTable
    )
    select T1.facility_id,T1.name,
      T1.value as "First_value",
      T1.created_at as "First created_at",
      T2.value as "Last_value",
      T2.created_at as "Last created_at"  
    from (
      select * from cte
      where ascrnk = 1
    ) T1
    left join (
      select * from cte
      where desrnk = 1 
    ) T2 on T1.facility_id = T2.facility_id and T1.name = T2.name
    

    结果:

    | facility_id | name | First_value |     First created_at | Last_value |      Last created_at |
    |-------------|------|-------------|----------------------|------------|----------------------|
    |        2011 |    A |         200 | 2015-05-30T11:50:17Z |        300 | 2017-05-30T11:50:17Z |
    |        2012 |    B |         124 | 2015-05-30T11:50:17Z |        195 | 2017-05-30T11:50:17Z |
    |        2013 |    C |         231 | 2015-05-30T11:50:17Z |        275 | 2017-06-30T11:50:17Z |
    |        2014 |    D |         279 | 2017-06-30T11:50:17Z |        263 | 2018-06-30T11:50:17Z |
    

    SQL Fiddle Demo Link

    【讨论】:

    • 我修好了@Masumbillah
    • 这是一个很好的答案,但它比必要的复杂得多。
    • 刚刚以如此聪明的方式完成...谢谢!
    【解决方案2】:

    我认为使用窗口函数和select distinct 会简单得多:

    select distinct facility_id, name,
           first_value(value) over (partition by facility_id, name order by created_at asc) as first_value,
           min(created_at) as first_created_at,
           first_value(value) over (partition by facility_id, name order by created_at desc) as last_value,
           max(created_at) as last_created_at
    from t;
    

    没有子查询。没有连接。

    您也可以使用数组来完成相同的功能,使用group by。遗憾的是 SQL Server 不直接支持 first_value() 作为窗口函数。

    【讨论】:

    • 这太棒了!
    • 查询是否适用于 AWS Athena/Presto?看起来它在 group by 子句中要求 Facility_id、name 和 created_at!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    相关资源
    最近更新 更多