繁体   English   中英

水平选择每个组的第一条记录和最后一条记录

[英]select first and last record of each group horizontally

我有一张桌子 在此处输入图片说明

我想通过facility_id和created_at选择每个组的第一条记录和最后一条记录,需要水平输出。 我可以垂直做,但水平需要 在此处输入图片说明

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小提琴演示链接

我认为使用窗口函数并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()作为窗口函数支持。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM