SQL:返回其val = min(exp)的ID

时间:2016-07-15 15:17:47

标签: sql-server

给出像

这样的表格

pkg#,时间

0,20

1,23

2,34

3,35

4,59

我想知道pkg#与其后续pkg有最大/最小时差(连续2个pkgs之间的差距)

在这种情况下,pkg-2有最小时差(1),pkg-3有最大时差(14) 什么是可以将pkg#的最小/最大时差返回到下一个pkg的sql?

3 个答案:

答案 0 :(得分:0)

如果您使用的是SQL SERVER 2012或更高版本,则可以在此处尝试使用LEAD函数来获取要在当前行中对齐的下一行值:

SELECT *, LEAD([time]) OVER(ORDER BY [pkg#]) as nexttime
FROM [your_table]

会产生这样的结果:

pkg time    nexttime
0   20  23
1   23  34
2   34  35
3   35  59
4   59  NULL

现在比较这两列值应该能给你你想要的东西。 (注意最后一行将具有nexttime = NULL,因为没有更多行可以从中获取值,因此只需在查询时将其过滤掉)。

假设新表名为new_table,以获得最大差异:

select top 1 *, nexttime-time as diff
from new_table
where nexttime is not null
order by (nexttime-time) desc

并获得min diff order by nexttime-time

答案 1 :(得分:0)

对@xbb的回答略有不同:

CREATE TABLE #t ( Pkg INT, Time INT );
INSERT  #t ( Pkg, Time )
VALUES  ( 0, 20 ),
       ( 1, 23 ),
       ( 2, 34 ),
       ( 3, 35 ),
       ( 4, 59 );

SELECT  Pkg
,      Time
,      Time - LAG(Time) OVER ( ORDER BY Pkg ) AS TimeSincePrevious
,      ABS(time - LEAD(Time) OVER ( ORDER BY Pkg )) AS TimeUntilNext
FROM       #t;

DROP TABLE #t;

将产生结果:

Pkg  Time  TimeSincePrevious  TimeUntilNext
0    20    NULL               3
1    23    3                  11
2    34    11                 1
3    35    1                  24
4    59    24                 NULL

答案 2 :(得分:0)

看看下面的解决方案 - 我将查询分解为三个步骤:

WITH Ordered AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY pkg) rowNum, pkg, [time] FROM Test
),
Diffs AS
(
    SELECT T1.pkg,
           T2.[time]-T1.[time] diff,
           MIN(T2.[time]-T1.[time]) OVER () minimum,
           MAX(T2.[time]-T1.[time]) OVER () maximum
    FROM Ordered T1
    JOIN Ordered T2 ON T1.rowNum = T2.rowNum-1
)
SELECT pkg, diff FROM Diffs
WHERE diff=minimum OR diff=maximum
ORDER by diff
  1. 行数
  2. 加入偏移1,计算diff,MIN和MAX
  3. 过滤行不等于min或max
  4. 如果出现tie,查询可能会返回更多行。可以通过将最终SELECT替换为:

    来简单地删除关系
    ...
    SELECT MIN(pkg) pkg, diff FROM Diffs
    WHERE diff=minimum OR diff=maximum
    GROUP BY diff
    ORDER by diff