Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle Analytic functions - How to reuse a PARTITION BY clause?

I have written a complex SQL query with Oracle in which I want to use two analytic function over the same partition.

Let's be quite simple but not too much:

SELECT col1,
       MAX(col2) OVER(PARTITION BY col3, col4, col5, col6,
                                   CASE WHEN col7 LIKE 'foo'
                                        THEN SUBSTR(col7,1,5)
                                        ELSE col7
                                   END
                                   ORDER BY col5 ASC, col6 DESC),
       MIN(col2) OVER(PARTITION BY col3, col4, col5, col6,
                                   CASE WHEN col7 LIKE 'foo'
                                        THEN SUBSTR(col7,1,5)
                                        ELSE col7
                                   END
                                   ORDER BY col5 ASC, col6 DESC)
  FROM my_table;

Is there a more elegant syntax for factoring the PARTITION BY clause?

Thank you.

like image 293
Benoit Avatar asked Mar 29 '11 13:03

Benoit


People also ask

Can we use where clause in partition by Oracle?

Thanks much. bhushan - we cannot use a where clause after the partition by is over.

What is the difference between aggregate and analytic functions in Oracle?

Aggregate functions perform a calculation on a set of values and return a single value. Analytic functions compute an aggregate value based on a set of values, and, unlike aggregate functions, can return multiple rows for each set of values.

What is Query_partition_clause?

The query_partition_clause clause divides rows into partitions to which the LAG() function is applied. By default, the function treats the whole result set as a single partition.

WHAT IS OVER clause in Oracle SQL?

The OVER clause specifies the partitioning, ordering and window "over which" the analytic function operates. It operates over a moving window (3 rows wide) over the rows, ordered by date. It operates over a window that includes the current row and all prior rows.


1 Answers

If you are referring to the standard WINDOW clause like this:

SELECT col1,
       MAX(col2) OVER(w),
       MIN(col2) OVER(w)
FROM my_table
WINDOW w AS (PARTITION BY col3, col4, col5, col6,
                               CASE WHEN col7 LIKE 'foo'
                                    THEN SUBSTR(col7,1,5)
                                    ELSE col7
                               END
                               ORDER BY col5 ASC, col6 DESC);

then I believe the answer is no, Oracle does not support this (checked with 11gR2).

like image 156
a_horse_with_no_name Avatar answered Oct 29 '22 18:10

a_horse_with_no_name