简体   繁体   English

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

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

What is the correct syntax of writing an aggregate function using over (partition by) ? 使用over (partition by)编写聚合函数的正确语法是什么?

Or how could be this re-written? 还是怎么改写? I don't have some sample table since I'm doing this as an exercise for myself. 我没有样本表,因为这是我自己做的练习。 I wonder if this would be possible. 我想知道这是否可能。 Please find below, the scenario I was thinking of. 请在下面找到我所想到的方案。

Let's take a simple example as a sample: 让我们以一个简单的示例作为示例:

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

The query above works on a table which has those columns. 上面的查询在具有这些列的表上工作。 Now, how could I write the same thing for distinct values of column1 and column2 ? 现在,如何为column1column2不同值编写相同的内容?

Query below is not working but it's the pseudo for what i'm trying to achieve. 下面的查询不起作用,但这是我想要实现的伪。

The expected result is quite straightforward (see distinct column1 * distinct column2 ) 预期的结果非常简单(请参见distinct column1 * distinct column2

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

EDIT: I want to avoid group by . 编辑:我想避免group by I'm trying to use partition by as much as I can so I would get better at window functions 我正在尝试尽可能多地使用分区,以便我会更好地使用窗口功能

Use of distinct with an aggregation other than count() is generally not correct. 使用不包含count()以外的聚合的distinct通常是不正确的。 This is as true for window functions as it is for aggregation functions. 对于窗口函数和聚合函数都是如此。

You can do the equivalent of count(distinct) using row_number() and conditional aggregation: 您可以使用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;

EDIT: 编辑:

The above will count a NULL value as a "valid" value, unlike COUNT(DISTINCT) . COUNT(DISTINCT)不同,以上内容会将NULL值视为“有效”值。 This is easily remedied: 这很容易补救:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM