COUNT + JOIN WITH DIFFICULTY IN RESULT

Asked

Viewed 81 times

-1

I need to get two results... I have a table with a total of 102 drivers and another table with the date he left to make deliveries and another with the arrival date...

I need to know which drivers are on the street and which are off duty.

The problem is that when I make a Join for the tables the result does not come as expected...

Example:

SELECT COUNT ('MOTORISTAS.CODIGO') 
FROM
MOTORISTAS 
WHERE 
MOTORISTAS.SITUACAO = 'A' AND
MOTORISTAS.OBS LIKE '%BAÚ%' AND
MOTORISTAS.CODIGO IN (SELECT VIAGENS.ID_MOTORISTA
            FROM VIAGENS 
            WHERE VIAGENS.ID_MOTORISTA <> 0)

ou este ...
SELECT COUNT (DISTINCT MOTORISTAS.CODIGO) 
FROM
MOTORISTAS INNER JOIN VIAGENS ON MOTORISTAS.CODIGO = VIAGENS.ID_MOTORISTA
WHERE 
MOTORISTAS.SITUACAO = 'A' AND
MOTORISTAS.OBS LIKE '%BAÚ%' AND
VIAGENS.ID_MOTORISTA <> 0

Both present a result of 42

  • What is your BDS? What does it say if it is traveling?

  • the tables are in Firebird

  • Goal is two answers ,one qtos drivers are on the go and how many drivers are at home

  • Okay, but you didn’t answer what I asked: How do you know if he’s traveling? Does the trip have a status or do you just delete it when it finishes one? And what is the link between the tables? The driver table has a id_motorista?

  • Oops, yes, the Trips table has two columns for this purpose, one of the exits *when he leaves to travel and the other with his arrival... when he finishes this trip

1 answer

0


Try using this SQL, make the necessary modifications according to your fields:

SELECT DISTINCT 
       COUNT(IIF(((V.DATA_SAIDA IS NOT NULL)AND(V.DATA_CHEGADA IS NULL)AND(V.ID_MOTORISTA IS NOT NULL))
                ,1
                ,NULL)) AS EM_VIAGEM
      ,COUNT(IIF(((V.DATA_SAIDA IS NULL)OR(V.DATA_CHEGADA IS NOT NULL))
                ,1
                ,NULL)) AS PARADOS
  FROM      MOTORISTAS M
  LEFT JOIN VIAGENS    V ON V.ID_MOTORISTA = M.CODIGO
 WHERE M.SITUACAO = 'A' 
   AND M.OBS      LIKE '%BAÚ%'
  • Thank you @Matheus Ribeiro

  • You’re welcome, it solved your problem?

  • @Victorandrade If my answer solved your problem, please mark it as accepted or give me feedback to help you!

Browser other questions tagged

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