简体   繁体   中英

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) ?

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 ?

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 )

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 . 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. 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:

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) . 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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