如何使用MAX命令选择一组记录

时间:2019-05-28 06:37:04

标签: sql oracle greatest-n-per-group top-n

我有一张桌子上的许多记录,它们的一个字段在一个字段中是不同的,因此我希望在此字段中选择一些最大价值的记录。

1 个答案:

答案 0 :(得分:0)

您要的是以下内容吗?

数据创建:

INSERT INTO MYTABLE_TEST VALUES (
    'USER1',
    '11'
);

INSERT INTO MYTABLE_TEST VALUES (
    'USER2',
    '21'
);

INSERT INTO MYTABLE_TEST VALUES (
    'USER2',
    '22'
);

INSERT INTO MYTABLE_TEST VALUES (
    'USER3',
    '31'
);

INSERT INTO MYTABLE_TEST VALUES (
    'USER3',
    '32'
);

INSERT INTO MYTABLE_TEST VALUES (
    'USER3',
    '33'
);

SELECT * FROM MYTABLE_TEST;

Table data

现在,我们将在“ val”列中获取具有最大值的用户记录,如下所示:

SELECT * FROM MYTABLE_TEST;

SELECT
    NAME,
    VAL
FROM
    (
        SELECT
            NAME,
            VAL,
            MAX(VAL) OVER(
                PARTITION BY NAME
                ORDER BY
                    VAL DESC NULLS LAST
            ) MAX_VAL
        FROM
            MYTABLE_TEST T
    )
WHERE
    VAL = MAX_VAL;

---------------- OR ----------------

SELECT
    NAME,
    VAL
FROM
    (
        SELECT
            NAME,
            VAL,
            ROW_NUMBER() OVER(
                PARTITION BY NAME
                ORDER BY
                    VAL DESC NULLS LAST
            ) RN
        FROM
            MYTABLE_TEST T
    )
WHERE
    RN = 1;

Result