Inner Join display last status

Asked

Viewed 261 times

2

I need to get data from 3 tables through a filter in 2 of them using the Date and Status criteria, and the Date is done in one table and the Status in another.

It turns out that when more than one status with the same name it lists all, it would like to get the last status.

query used:

SELECT
numero.id,
numero.numero,
status.status,
status.data
FROM numero
INNER JOIN dados ON numero.id = dados.id_numero
INNER JOIN status ON numero.numero = status.numero AND status.status = 'Confirmado'
WHERE dados.data BETWEEN '2015-04-10' AND '2015-04-10 23:59:59.997' ORDER BY dados.data

Demonstrativo Online: SQL Fiddle

  • You can give an example of the output you want?

2 answers

1


I understand that when you say, "last status" you intend to return only the one with the latest date. If so you can just do:

SELECT   numero.id,
         numero.numero,
         status.status,
         MAX(status.data) DATA
FROM numero
INNER JOIN dados 
   ON numero.id = dados.id_numero
INNER JOIN status 
   ON numero.numero = status.numero 
  AND status.status = 'Confirmado'
WHERE dados.data BETWEEN '2015-04-10' AND '2015-04-10 23:59:59.997' 
GROUP BY numero.id, numero.numero, status.status 
ORDER BY dados.data
  • Thank you very much @ ;)

  • No problem. It is a pleasure to be able to help! It is always possible to distract from work :)

  • has Skype @Bruno?

  • Not here, but you can chat, I guess.

0

Just make a GROUP BY numero.id

SELECT
  numero.id,
  numero.numero,
  status.status,
  status.data
FROM numero
INNER JOIN dados ON numero.id = dados.id_numero
INNER JOIN status ON numero.numero = status.numero AND status.status = 'Confirmado'
WHERE dados.data BETWEEN '2015-04-10' AND '2015-04-10 23:59:59.997'
GROUP BY numero.id
ORDER BY dados.data
  • grateful for the help, then... with the GROUP BY it brings me the first status that in the above example is 2015-04-11 and I need it to be the last, which in this case is 2015-04-15

  • It is not enough just to group by by the number.id. This way loses some of the results.

Browser other questions tagged

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