SQL Server 2012:聚合函数中的distinct with over子句
使用SQL Server 2012:聚合函数中的distinct with over子句,sql,sql-server,tsql,sql-server-2012,window-functions,Sql,Sql Server,Tsql,Sql Server 2012,Window Functions,使用over(partition by)编写聚合函数的正确语法是什么 或者这是怎么写的?我没有一些样本表,因为我做这个是为了锻炼自己。我想知道这是否可能。请在下面找到我想到的情景 让我们举一个简单的例子作为示例: select *, sum (column1 * column2) over (partition by column10, colum12)/100 as sumProduct into #myTemp from myTable 上面的查询在具有这些列的表上工作。
over(partition by)
编写聚合函数的正确语法是什么
或者这是怎么写的?我没有一些样本表,因为我做这个是为了锻炼自己。我想知道这是否可能。请在下面找到我想到的情景
让我们举一个简单的例子作为示例:
select
*,
sum (column1 * column2) over (partition by column10, colum12)/100 as sumProduct
into #myTemp
from myTable
上面的查询在具有这些列的表上工作。
现在,如何为column1
和column2
的不同值编写相同的代码
下面的查询不起作用,但它是我试图实现的伪查询
预期的结果非常简单(请参见distinct column1*distinct column2
)
编辑:我想避免
按分组。我正在尽可能多地使用分区,以便更好地使用窗口函数使用distinct
和非count()的聚合通常是不正确的。窗口函数和聚合函数都是如此
使用row\u 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;
编辑:
与count(DISTINCT)
不同,上面将NULL
值计算为“有效”值。这很容易纠正:
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;
您无法在windows功能中进行区分。首先在cte中执行distinct,然后应用您的函数。聚合或窗口函数(除了COUNT()
)不应使用distinct
。如果列或列2
中的值是/将是NULL
,这是否也有效?伟大的answer@CM2K . . . 这对NULL
的处理略有不同,因为它将其计为有效值。我添加了一个一致的版本,即使对于NULL
值也是如此。我是CTE
和row\u number()
的初学者(老实说,只是简单地阅读一下,从未使用过它们)。我理解这里的逻辑(或者,至少我希望如此),但如何计算/合并问题中所示的sumProduct
。我不建议这样做。在distinct
中使用除count()
之外的聚合函数通常表明数据结构存在问题,我发现这很危险(当然,在min()
或max()
中不需要这样做)。规范化数据或在子查询中使用选择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;