请帮助我解决困惑。
为什么 min() 的行为与 max() 不同?
Select
max(My_Date) over (order by My_Date) as Max_Datum
, min(My_Date) over (order by My_Date) as Min_Datum
From
(
Select dateadd(m,-1,getdate()) as My_Date
Union all
Select getdate() as My_Date
Union all
Select dateadd(m,1,getdate()) as My_Date
Union all
Select dateadd(m,2,getdate()) as My_Date
) t1
结果:
Max_Datum Min_Datum
2024-08-02 16:20:39.733 2024-08-02 16:20:39.733
2024-09-02 16:20:39.733 2024-08-02 16:20:39.733
2024-10-02 16:20:39.733 2024-08-02 16:20:39.733
2024-11-02 16:20:39.733 2024-08-02 16:20:39.733
问题不是函数,而是你的
OVER
子句。您已添加了 OVER
子句和子句 ORDER BY My_Date
,根据 documentation,默认窗口为 RANGE UNBOUNDED PRECEDING AND CURRENT ROW
。因此,MAX
值始终是当前行值,因为这是数据的顺序。
以以下简化数据为例:
身份证 | 一些数字 |
---|---|
1 | 2 |
2 | 3 |
3 | 1 |
4 | 5 |
5 | 4 |
现在假设您有类似的查询:
SELECT MIN(SomeNumber) OVER (ORDER BY SomeNumber RANGE UNBOUNDED PRECEDING AND CURRENT ROW) AS MinSomeNumber,
MAX(SomeNumber) OVER (ORDER BY SomeNumber RANGE UNBOUNDED PRECEDING AND CURRENT ROW) AS MaxSomeNumber
FROM dbo.SomeTable
ORDER BY ID;
这将导致以下结果:
最小一些数字 | 最大一些数 |
---|---|
1 | 1 |
2 | 2 |
3 | 3 |
4 | 4 |
5 | 5 |
实际上,您在每一行都询问以下问题:
因此,您可以看到,
MAX
会有所不同,但 MIN
不会。
您可能希望在这里更改
ORDER
,或包含整个结果集:
SELECT MIN(SomeNumber) OVER (ORDER BY SomeNumber RANGE UNBOUNDED PRECEDING AND CURRENT ROW) AS MinSomeNumber,
MAX(SomeNumber) OVER (ORDER BY SomeNumber DESC RANGE UNBOUNDED PRECEDING AND CURRENT ROW) AS MaxSomeNumber,
MIN(SomeNumber) OVER (ORDER BY SomeNumber ROWS UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS MinSomeNumber,
MAX(SomeNumber) OVER (ORDER BY SomeNumber ROWS UNBOUNDED PRECEDING AND CURRENT FOLLOWING) AS MaxSomeNumber
FROM dbo.SomeTable
ORDER BY ID;