Function MAX only 1 (one) record on Oracle

Asked

Viewed 4,216 times

0

Could someone give me a hand in using Oracle’s Function MAX()???

I need to do a query that returns only the last record of a history table, but I need to return 3 (three) columns of this record -> Id, Ticket_id and Queue_id, but if I use the query as follows the query is not executed due to an error in GROUP BY.

inserir a descrição da imagem aqui

To run the query I should add the QUEUE_ID column in GROUP BY as follows:

inserir a descrição da imagem aqui

But this way the result does not return the last record by MAX(ID) and yes returns 2 records, as below:

inserir a descrição da imagem aqui

And I just need the last entry, in case it would be 53474 with Queue_id 22.

Does anyone know how to create this type of query on Oracle?

  • Tried a subselect with max ?

2 answers

1


Assuming that there is only one entry with the maximum value of the desired column (for the conditions placed), the question can be solved in this way:

SELECT ID, TICKET_ID, QUEUE_ID
FROM TICKET_HISTORY
WHERE ID IN (
  SELECT MAX(ID) 
  FROM TICKET_HISTORY
  WHERE HISTORY_TYPE_ID = 27 AND STATE_ID = 2 AND 
  TICKET_ID = 1290
);
  • Perfect Andrei, that way it worked perfectly, had not tried that way yet, thanks for the tip.

0

Try it this way:

SELECT MAX(ID), TICKET_ID, QUEUE_ID
FROM TICKET_HISTORY
WHERE HISTORY_TYPE_ID = 27 AND STATE_ID = 2 AND TICKET_ID = 1290
ORDER BY TICKET_ID DESC LIMIT 1;
  • That doesn’t solve the problem, TICKET_ID is the same value on all lines, order by won’t do very well.

  • Oracle does not work this way with DESC LIMIT 1, already solved with the tip provided by Andrei.

Browser other questions tagged

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