When to use the OVER clause?

1
The Documentation says:

  

Determines the partitioning and sorting of the rowset before   of the associated window function.

An example I created just to demonstrate this:

select ROW_NUMBER() OVER(PARTITION BY cor order by carro  ) from carro

This example would return a ROW_NUMBER counting until the column condition changes and resumes. In a table of 7 records with 2 records with the color yellow and 5 with the color blue the Row_Number would go from 1 to 2 and would restart and would go from 1 to 5 again.

However for some aggregation functions, no partitioning is required to use this condition, for example this select found here :

SELECT  MAX(date) OVER (ORDER BY id)
FROM    mytable

But for clauses with value-partitioning the order by is mandatory, but the partition is not, otherwise it depends on the function it is calling, then:

  • When should I use the OVER clause?
  • Does Group By at the end of a select work in the same way (in case there is a partition)?
  • When I can use functions with over without an order by, is there specific function that allows this?

There is a question in SOEN but I found the answer very generic so I continue with some questions.

Other references:

OVER Clause

    
asked by anonymous 10.11.2017 / 20:11

1 answer

2

The OVER function from what I understand it determines the partitioning and ordering of a set of N lines before the application of the associated window function. Defining a window or set of user-specified rows in query results. In a way, compute a value for each row in the window.

You can use the OVER clause with functions to compute aggregate values such as moving averages, cumulative aggregates, cumulative sums, or the first N results per group.

Syntax example:

- For Aggregation Functions (SUM - COUNT - AVG - etc)

    OVER(Partition by Campo)

- For RANK - NTILE - DENSE_RANK - ROW_NUMBER

    OVER(Partition by Campo Order by Campo)

Now let's use it inside a SELECT , there is no way to show solution without OVER x with OVER

Solution COM OVER, notice that the Partition By clause works as if it were a GROUP BY . Creating groups, which we call windows. Making the query simpler.

SELECT Nome, Data,count(*) over(partition by Nome) TotalAcessos FROM Acesso

Solution if you do not want to use OVER

SELECT  A.Nome, A.Data, TabGroup.TotalAcessos
FROM  Acesso A
INNER JOIN
(
    SELECT  Nome, COUNT(*) TotalAcessos
    FROM  Acesso
    GROUP BY  Nome
) TabGroup ON  A.Nome=TabGroup.Nome
    
10.11.2017 / 20:28