MAX () returning multiple rows

1

When I run the script it does not return only the maximum value, ie the longest time, but the 3 times.

SELECT  P.CD_PACIENTE CD_PACIENTE
            ,P.NM_PACIENTE NM_PACIENTE
            ,L.CD_UNID_INT CD_UNID_INT
            ,L.DS_ENFERMARIA DS_ENFERMARIA
            ,L.DS_LEITO DS_LEITO
            ,MAX(MI.HR_MOV_INT) HR_MOV_INT


            FROM ATENDIME A
            JOIN PACIENTE P ON P.CD_PACIENTE = A.CD_PACIENTE
            JOIN MOV_INT MI ON MI.CD_ATENDIMENTO = A.CD_ATENDIMENTO
            JOIN LEITO L ON L.CD_LEITO = MI.CD_LEITO

            WHERE A.DT_ALTA_MEDICA IS NULL
            AND P.CD_PACIENTE = 0

            GROUP BY P.CD_PACIENTE 
            ,P.NM_PACIENTE 
            ,L.CD_UNID_INT
            ,L.DS_ENFERMARIA 
            ,L.DS_LEITO

            ORDER BY P.CD_PACIENTE

Result returned:

0   TESTE   35  0319    VIRTUAL     11/06/2018 10:51:18
0   TESTE   23  0414    LEITO03     11/06/2018 10:49:48
0   TESTE   35  0319    LEITO008    01/04/2018 16:00:00

Expected result:

0   TESTE   35  0319    VIRTUAL     11/06/2018 10:51:18
    
asked by anonymous 21.09.2018 / 21:49

3 answers

3

It will bring the MAX into your collation, that's correct. If you want to look at the MAX of the entire table, leave only the MAX in the select. Again, if you leave the grouping it will always show the maximum result within each grouping. I do not know if I could be clear.

    
21.09.2018 / 22:57
1

When you use group by , it does the grouping on each value of the column that you specify, that is, group equal values, see that example .

When you use max() , it returns the highest value field in the column, that is, returns the largest field, see that example .

If you use group by together with max() , the result will return the maximum value of each collation you ask for, not a single value. If you want to get the highest value, remove the grouping of values to return a single line.

    
21.09.2018 / 23:25
1

Hello,

As the colleagues quoted above, it is correct to return the three values. The easiest way to get around this, assuming you already have the select ready, is to put it in from in the form of a subselect and out of it call the MAX function.

So:

    SELECT MAX(TAB.HR_MOV_INT) -- demais colunas desejadas
     FROM
    (SELECT  P.CD_PACIENTE CD_PACIENTE
        ,P.NM_PACIENTE NM_PACIENTE
        ,L.CD_UNID_INT CD_UNID_INT
        ,L.DS_ENFERMARIA DS_ENFERMARIA
        ,L.DS_LEITO DS_LEITO
        ,MAX(MI.HR_MOV_INT) HR_MOV_INT

        FROM ATENDIME A
        JOIN PACIENTE P ON P.CD_PACIENTE = A.CD_PACIENTE
        JOIN MOV_INT MI ON MI.CD_ATENDIMENTO = A.CD_ATENDIMENTO
        JOIN LEITO L ON L.CD_LEITO = MI.CD_LEITO

        WHERE A.DT_ALTA_MEDICA IS NULL
        AND P.CD_PACIENTE = 0

        GROUP BY P.CD_PACIENTE 
        ,P.NM_PACIENTE 
        ,L.CD_UNID_INT
        ,L.DS_ENFERMARIA 
        ,L.DS_LEITO) tab
    
28.09.2018 / 17:10