Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why an aggregation function doesn't work as expected in an apply block

WITH
    a (v)
    AS
        (    SELECT LEVEL
               FROM DUAL
         CONNECT BY LEVEL < 5),
    b (v)
    AS
        (    SELECT LEVEL
               FROM DUAL
         CONNECT BY LEVEL < 5)
SELECT a.v
  FROM a
       CROSS APPLY (SELECT MIN (b.v)
                      FROM b
                     WHERE a.v = b.v) bb

result 1,2,3,4
but expected result would be 1,1,1,1.

code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

1,2,3,4 is the correct output.

In the outer query you SELECT a.v which will select the v value from table a CROSS JOIN with the single row aggregation generated by the CROSS APPLY.

For your code, it doesn’t really matter what the output is from the bb sub-query in the CROSS APPLY as you are not outputting the value from bb and the aggregation forces the output to be a single row.


If you want to get the value from the bb sub-query then use:

WITH a (v) AS (
  SELECT LEVEL FROM DUAL CONNECT BY LEVEL < 5
),
b (v) AS (
  SELECT LEVEL FROM DUAL CONNECT BY LEVEL < 5
)
SELECT a.v, bb.min_v
  FROM a
       CROSS APPLY (
         SELECT MIN (b.v) As min_v
         FROM   b
         WHERE  a.v = b.v
       ) bb

Then the output is:

V MIN_V
1 1
2 2
3 3
4 4

If you want all 1s then SELECT the value from bb and use b.v <= a.v as the filter:

WITH a (v) AS (
  SELECT LEVEL FROM DUAL CONNECT BY LEVEL < 5
),
b (v) AS (
  SELECT LEVEL FROM DUAL CONNECT BY LEVEL < 5
)
SELECT a.v, bb.min_v
  FROM a
       CROSS APPLY (
         SELECT MIN (b.v) As min_v
         FROM   b
         WHERE  b.v <= a.v
       ) bb

which outputs:

V MIN_V
1 1
2 1
3 1
4 1

db<>fiddle here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading