SQL Server 2012:与聚合函数中的 over 子句不同

SQL Server 2012: distinct with over clause in an aggregate function

使用 over (partition by) 编写聚合函数的正确语法是什么?

或者如何重写?我没有一些示例 table,因为我这样做是为了自己练习。我想知道这是否可能。请在下面找到我正在考虑的场景。​​

我们以一个简单的例子为例:

select 
    *,
    sum (column1 * column2) over (partition by column10, colum12)/100 as sumProduct
into #myTemp
from myTable

上面的查询适用于具有这些列的 table。 现在,我怎么能为 column1column2 的不同值写同样的东西?

下面的查询不起作用,但它是我要实现的伪查询。

预期结果非常简单(参见 distinct column1 * distinct column2

select 
    *,
    sum (distinct column1 * distinct column2) over (partition by column10, colum12)/100 as sumProduct
into #myTemp
from myTable

编辑: 我想避免 group by。我正在尝试尽可能多地使用分区,这样我会在 window 函数

方面做得更好

distinctcount() 以外的聚合一起使用通常是不正确的。 window 函数和聚合函数都是如此。

您可以使用 row_number() 和条件聚合来完成 count(distinct) 的等效操作:

select t.*,
       sum(case when seqnum = 1 then 1 else 0 end) as CountDistinct
into #myTemp
from (select t.*,
             row_number() over (partition by column10, colum12 order by (select NULL)) as seqnum
      from myTable t
     ) t;

编辑:

上面将把 NULL 值计为 "valid" 值,这与 COUNT(DISTINCT) 不同。这很容易补救:

select t.*,
       count(case when seqnum = 1 then colum12 end) as CountDistinct
into #myTemp
from (select t.*,
             row_number() over (partition by column10, colum12 order by (select NULL)) as seqnum
      from myTable t
     ) t;