sql - 为什么 where 子句中没有窗口函数?

标签 sql sql-server tsql window-functions

标题说明了一切,为什么我不能在 SQL Server 的 where 子句中使用窗口函数?

这个查询非常有意义:

select id, sales_person_id, product_type, product_id, sale_amount
from Sales_Log
where 1 = row_number() over(partition by sales_person_id, product_type, product_id order by sale_amount desc)

但是这不起作用。有没有比 CTE/子查询更好的方法?

编辑

就其值(value)而言,这是带有 CTE 的查询:

with Best_Sales as (
    select id, sales_person_id, product_type, product_id, sale_amount, row_number() over (partition by sales_person_id, product_type, product_id order by sales_amount desc) rank
    from Sales_log
)
select id, sales_person_id, product_type, product_id, sale_amount
from Best_Sales
where rank = 1

编辑

+1 对于使用子查询显示的答案,但实际上我正在寻找无法在 where 子句中使用窗口函数的原因。

最佳答案

why can't I use a windowed function in a where clause in SQL Server?

一个答案虽然不是特别有用,但因为规范说你不能。

请参阅 Itzik Ben Gan 的文章 - Logical Query Processing: What It Is And What It Means to You特别是the image here 。窗口函数在 SELECT 时评估在 WHERE 之后剩余的结果集上/JOIN/GROUP BY/HAVING条款已处理(步骤 5.1)。

really I'm looking for the reasoning behind not being able to use windowing functions in where clauses.

WHERE 中不允许使用它们的原因的条款是它会造成歧义。窃取 Itzik Ben Gan 的例子 High-Performance T-SQL Using Window Functions (第25页)

假设你的 table 是

CREATE TABLE T1
(
col1 CHAR(1) PRIMARY KEY
)

INSERT INTO T1 VALUES('A'),('B'),('C'),('D'),('E'),('F')

以及您的查询

SELECT col1
FROM T1
WHERE ROW_NUMBER() OVER (ORDER BY col1) <= 3
AND col1 > 'B'

正确的结果是什么?您是否期望 col1 > 'B'谓词在行编号之前还是之后运行?

关于sql - 为什么 where 子句中没有窗口函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13997177/

相关文章:

MySQL选择列包含值的行

sql - 检查行是否存在的最快方法

sql - 带有未定义类型的 Case 语句?或为什么约会?

sql查询动态返回行数

sql - 为查询字符串声明变量

sql - 履行客户订单号的采购订单号 - SQL

sql - 如何手动插入身份?

sql - 从 SQL Server 中的字符串中提取子字符串

sql-server - 与多个 ON 的连接是什么意思?

sql - IF EXISTS 在 INSERT、UPDATE、DELETE 之前进行优化