简体   繁体   English

具有最小值和最大值的 SQL 组

[英]SQL Group with Min and Max

I have a super simple query using group by and I just can't figure out how to get the desired result.我有一个使用 group by 的超级简单查询,但我不知道如何获得所需的结果。 It's literally a simple query with min() and max().这实际上是一个带有 min() 和 max() 的简单查询。 I have a table where assets belong to a certain location with a date in/out (it also has multiple in/out dates without changing location), but if an asset moves back to location where its previously already been, the grouping doesn't work.我有一个表,其中资产属于某个位置,有一个日期进/出(它也有多个进/出日期而不改变位置),但是如果资产移回之前已经存在的位置,则分组不会工作。 I tried using a combination of over(partition by...), just can't solve it.我尝试使用over(partition by...)的组合,就是无法解决。

Table:桌子:

Asset   Location    Date In     Date Out
------------------------------------------
00001   A           01/01/2020  13/01/2020
00001   A           14/01/2020  26/01/2020
00001   A           27/01/2020  08/02/2020
00001   B           09/02/2020  21/02/2020
00001   B           22/02/2020  05/03/2020
00001   B           06/03/2020  18/03/2020
00001   A           19/03/2020  31/03/2020
00001   A           01/04/2020  13/04/2020
00001   A           14/04/2020  26/04/2020
00001   A           27/04/2020  09/05/2020
00001   A           10/05/2020  16/09/2020

Desired result:想要的结果:

Asset   Location    Date In     Date Out
------------------------------------------
00001   A           01/01/2020  08/02/2020
00001   B           09/02/2020  18/03/2020
00001   A           19/03/2020  16/09/2020

Actual result:实际结果:

Asset   Location    Date In     Date Out
------------------------------------------
00001   A           01/01/2020  16/09/2020
00001   B           09/02/2020  18/03/2020

This is a groups-and-islands problem.这是一个群体和岛屿问题。 A simple solution is the difference of row numbers:一个简单的解决方案是行号的差异:

select asset, location, min(date_in), max(date_out)
from (select t.*,
             row_number() over (partition by asset order by date_in) as seqnum             
             row_number() over (partition by asset, location order by date_in) as seqnum_2
      from t
     ) t
group by asset, location, (seqnum - seqnum_2);

Why this works is a little tricky to explain.为什么这行得通有点难以解释。 If you look at the subquery you'll see how the difference in row numbers defines the consecutive rows you want.如果您查看子查询,您将看到行号的差异如何定义您想要的连续行。

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

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