sql-server – 在OVER的窗口函数中使用DISTINCT

前端之家收集整理的这篇文章主要介绍了sql-server – 在OVER的窗口函数中使用DISTINCT前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将查询从Oracle迁移到sql Server 2014.

这是我在Oracle中运行良好的查询

select
count(distinct A) over (partition by B) / count(*) over() as A_B
from MyTable

这是我尝试在sql Server 2014中运行此查询后得到的错误.

Use of DISTINCT is not allowed with the OVER clause

谁知道问题是什么?在sql Server中可以进行哪种查询吗?
请指教.

解决方法

Anyone know what is the problem? Is such as kind of query possible in
sql Server?

不,目前尚未实施.请参阅以下连接项请求.

OVER clause enhancement request – DISTINCT clause for aggregate functions

另一种可能的变体是

SELECT M.A,M.B,T.A_B
FROM   MyTable M
       JOIN (SELECT CAST(COUNT(DISTINCT A) AS NUMERIC(18,8)) / SUM(COUNT(*)) OVER() AS A_B,B
             FROM   MyTable
             GROUP  BY B) T
         ON EXISTS (SELECT M.B INTERSECT SELECT T.B)

对NUMERIC的强制转换是为了避免整数除法. join子句的原因是explained here.

如果优选,它可以用ON M.B = T.B OR(M.B IS NULL和T.B IS NULL)代替(或者如果B列不可为空则简单地ON ON M.B = T.B).

原文链接:/mssql/79928.html

猜你在找的MsSQL相关文章