Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Case in windowing function ( OVER (Partition))

I am trying to accomplish the following:

SELECT 
   *,
   CASE WHEN 1 THEN SUM(b.myField) ELSE AVG(b.myField) END OVER (PARTITION BY ID)
FROM tbl a
LEFT JOIN tbl2 b ON a.ID = b.aID

Is this possible with the window functions in SQL Server?

I am able to accomplish the following without the case statement:

SELECT 
   *,
   SUM(b.myField) OVER (PARTITION BY ID)
FROM tbl a
LEFT JOIN tbl2 b ON a.ID = b.aID
like image 775
ryan Avatar asked May 29 '14 15:05

ryan


People also ask

Can we use CASE statement in partition by?

We can use the CASE Expression in any statement or clause that allows a valid expression. For example, you can use CASE Expression in statements such as SELECT , UPDATE , DELETE , SET and in clauses such as PARTITION BY , ORDER BY , WHERE and HAVING .

Is partition by a window function?

A window function computes a value for each row in the window. PARTITION BY expr_list PARTITION BY is an optional clause that subdivides the data into partitions. Including the partition clause divides the query result set into partitions, and the window function is applied to each partition separately.

What is the correct syntax for a windowing function?

Basic windowing syntax The first part of the above aggregation, SUM(duration_seconds) , looks a lot like any other aggregation. Adding OVER designates it as a window function. You could read the above aggregation as "take the sum of duration_seconds over the entire result set, in order by start_time ."


1 Answers

You can try this:

SELECT 
   *,
   CASE WHEN (SUM(b.myField) 
OVER (PARTITION BY ID))=1 THEN SUM(b.myField)
 ELSE AVG(b.myField) END 
FROM tbl a
LEFT JOIN tbl2 b ON a.ID = b.aID
like image 66
Juan Bernardo Gómez Avatar answered Oct 11 '22 11:10

Juan Bernardo Gómez