How to select by taking the record that has the maximum value of a field?

Asked

Viewed 3,034 times

1

I am doing a select that is seeking records that meet some conditions and then should take from them only the record that has the maximum value of a given field.

It’s like this:

SELECT 
    VP.VAL_PREVISTO
FROM 
    TB_META M 
INNER JOIN 
    TB_SUPER_FUNCAO_META SFM ON 
    M.COD_META = SFM.COD_META 
    AND SFM.COD_FUNCAO = (SELECT F.COD_SUPER_FUNCAO U FROM TB_USUARIO U INNER JOIN TB_FUNCAO F ON U.COD_FUNCAO = F.COD_FUNCAO WHERE U.COD_USUARIO = 5)
INNER JOIN
    TB_VALOR_PREVISTO VP ON
    M.COD_META = VP.COD_META
INNER JOIN
    TB_CG_META_PERIODO CGMP ON
    VP.COD_VALOR_PREVISTO = CGMP.COD_VALOR_PREVISTO       
WHERE
    SFM.IND_EXIBIR_MC_CG = 1 AND M.COD_META = 44 AND CGMP.NUM_PERIODO_LANCAMENTO = 4

In this query I am searching the period: CGMP.NUM_PERIODO_LANCAMENTO = 4 but I don’t want to specify the period, because the maximum period may be longer than that. I wanted the query to get the record with maximum period, but only after the other "Where".

1 answer

2

One of the solutions is to make a subquery to fetch the MAX of that element:

SELECT 
    VP.VAL_PREVISTO
FROM 
    TB_META M 
INNER JOIN 
    TB_SUPER_FUNCAO_META SFM ON 
    M.COD_META = SFM.COD_META 
    AND SFM.COD_FUNCAO = (SELECT F.COD_SUPER_FUNCAO U FROM TB_USUARIO U INNER JOIN TB_FUNCAO F ON U.COD_FUNCAO = F.COD_FUNCAO WHERE U.COD_USUARIO = 5)
INNER JOIN
    TB_VALOR_PREVISTO VP ON
    M.COD_META = VP.COD_META
INNER JOIN
    TB_CG_META_PERIODO CGMP ON
    VP.COD_VALOR_PREVISTO = CGMP.COD_VALOR_PREVISTO       
WHERE
    SFM.IND_EXIBIR_MC_CG = 1 AND M.COD_META = 44 
    AND CGMP.NUM_PERIODO_LANCAMENTO = (
        SELECT MAX(C.NUM_PERIODO_LANCAMENTO)
        FROM TB_CG_META_PERIODO C
    )
  • But what if "SELECT MAX(C.NUM_PERIODO_LANCAMENTO) FROM TB_CG_META_PERIODO C" is different from the results obtained in my first Where conditions? I’ll be left with no results, right?

  • What conditions are you talking about @Joaopaulo? The SFM.IND_EXIBIR_MC_CG = 1 AND M.COD_META = 44 or those of JOIN?

  • I searched where SFM.IND_EXIBIR_MC_CG = 1 AND M.COD_META = 44. With these conditions I get results where the maximum period is 3, but the maximum period of the table is 6 for example. If I add the condition you said I’ll find the 6 and not the 3 I want.

  • Will I have to use a condition virtually equal to my original select? I was seeing if I had a simpler alternative.

  • @Joaopaulo, I get it. To do this in the subquery you will have to put the conditions to get your maximum. If you say it’s gonna be based on SFM.IND_EXIBIR_MC_CG and M.COD_META, then they need to be there. However, I couldn’t figure out where this data will influence an assumed maximum of the CGMP.NUM_PERIODO_LANCAMENTO. There needs to be a relationship between both tables

Browser other questions tagged

You are not signed in. Login or sign up in order to post.