SQL last value aggregation is giving first value with ordered inner query

63 Views Asked by At

Hi I have below query

SELECT
    CLUSTER_ID AS CLUSTER_ID,
    "date"
FROM
    HISTORY
GROUP BY
    CLUSTER_ID,
    "date"
ORDER BY
    CLUSTER_ID,
    "date"

with below output

1   2023-02-27
1   2023-03-01
1   2023-03-06
1   2023-03-13
1   2023-03-20
1   2023-03-27
1   2023-04-01
1   2023-04-03

when used above query as inner query as below, my expectation is to get last date which is 2023-04-03 but to my surprise it is giving first value which is 2023-02-27

SELECT
    LAST_VALUE(CLUSTER_ID),
    LAST_VALUE("date")
FROM
    (

        SELECT
            CLUSTER_ID AS CLUSTER_ID,
            "date"
        FROM
            HISTORY
        GROUP BY
            CLUSTER_ID,
            "date"
        ORDER BY
            CLUSTER_ID,
            "date")
    GROUP BY
        CLUSTER_ID

It is giving expected value 2023-04-03 when DESC order is used in inner query like below

SELECT
    LAST_VALUE(CLUSTER_ID),
    LAST_VALUE("date")
FROM
    (
    SELECT
        CLUSTER_ID AS CLUSTER_ID,
        "date"
    FROM
        HISTORY
    GROUP BY
        CLUSTER_ID,
        "date"
    ORDER BY
        CLUSTER_ID,
        "date" DESC)
GROUP BY
    CLUSTER_ID

can someone please explain the execution flow of the query

0

There are 0 best solutions below