Select Distinct

Asked

Viewed 327 times

1

tbl_protocolos

id_protocolo | protocolo | assunto

1;ra001;vazamentos

2;ra002;incendios

3;ra003;inundacoes


tbl_prot_tramitacoes

id_tram | id_protocolo | pdf | id_setor_origem

1;1;001.pdf;70

2;1;001.pdf;100 - **rejeitar por causa do id_setor_origem**

3;2;002.pdf;70

4;3;003.pdf;70

5;1;001.pdf;70 - rejeitar pois já peguei **id_protocolo = 1** na linha 1

I need the tbl_prot_tramitacoes pdf field ( where there is repetition of id_protocolo ) and id_setor_origem = 70 e preciso tb do campo protocolo e assunto da tbl_protocolos ( onde NÃO há repetiçao do id_protocolo )

Now, how do I carry these records ?

id_tram | protocolo | assunto | pdf

1          ra001    vazamentos  001.pdf

3          ra002    incendios   002.pdf

4          ra003    inundacoes  003.pdf

1 answer

1


You can use a subquery to select the lines that meet the conditions, as shown below.

SELECT a.id_tram,protocolo, assunto, pdf 
FROM tbl_prot_tramitacoes AS a
INNER JOIN tbl_protocolos AS b
ON a.id_protocolo = b.id_protocolo
WHERE a.id_tram IN 
(SELECT MIN(id_tram)
FROM tbl_prot_tramitacoes
WHERE id_setor_origem = 70
GROUP BY id_protocolo)

select within parentheses is used to obtain the id of lines with each first occurrence id_protocolo. Then, in the top select, these ids are used to obtain additional information.

  • Ball show. Lesson learned. Thank you very much. Besides solving the issue commented how it works and this for me was sensational.

  • SELECT b.id_protocol, b.protocol, b.subject, b.subject, a.numero_doc, a.pdf, a.data_processing FROM tbl_prot_processing AS a INNER TBL_PROTOCOLS AS b ON a. id_protocol = b.id_protocol WHERE a.id_processing IN (SELECT MIN(id_processing) FROM tbl_prot_processing WHERE id_setor_origin = 70 GROUP BY id_protocol) One question, is there any way INSIDE THIS ADD A DIFFERENCE column that shows the DAYS difference between.data_processing and TODAY ?

  • Yes, you can use the function DATEDIFF to get the difference between two dates, and use NOW() to get today’s day. DATEDIFF(now(),a.data_tramitacao)

  • Thank you, ball show

  • @theteo In this case (previous comment) the difference is generated at the time you make the select, I don’t think it makes sense add a column with this content in the table, since it will depend on the moment you read it.

  • understood, but I will use this query to generate a VIEW, so in my case it will make perfect sense. Thank you.

  • @theteo Yes, in case a view makes sense. Nothing!

Show 2 more comments

Browser other questions tagged

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