How to do an INNER JOIN by bringing specific fields from two tables and removing the repeated records and with a max condition?

Asked

Viewed 512 times

0

Well, I have the following tables:

Table 01:

inserir a descrição da imagem aqui

And table 02:

inserir a descrição da imagem aqui

There I would like to bring only all fields with higher points and do not repeat the waiter in the case, how to do?

  • The names that appear in table 01 are the names of the waiters?

1 answer

2


Adding up the Points of the same waiter (ex.: Juliana Oliveira => 100 + 123)

SELECT g.nome Garcom,sum(p.pontos) TotalPontos
FROM tabela01 g
JOIN tabela02 p ON p.garcom_id = g.id
GROUP BY g.nome 
ORDER BY sum(p.pontos) DESC,g.nome

Without adding, catching the biggest point of every waiter

SELECT g.nome Garcom,max(p.pontos) maior
FROM tabela01 g
JOIN tabela02 p ON p.garcom_id = g.id
GROUP BY g.nome 
ORDER BY max(p.pontos) DESC,g.nome 

P.S.: Change the tabela01 and tabela02 for the names of the respective tables

If you want the first records Filtre by the first N records Voce wants and you did not inform what type of database is.

Sqlserver would add a TOP N right after the select (SELECT TOP 10 ....);

Postgresql would add a LIMIT N at the end (ORDER BY ..... LIMIT 10);

Oracle is beemmm more complicated, nor will post here, I will inform a link (I found on google) Oracle

Mysql equals Postgresql, uses LIMIT at the end

  • 1

    Mysql is the bank, I want the highest score... Ex.: pedro, 110pts, Joao, 98pts, pedro, 115pts... Soon the query brings: pedro 110pst... Joao 115pts. Got it?

  • Do you want to add the points of the same waiter or not? ex.: Juliana Oliveira -> 100 and 123

  • I added DESC to SQL for descending order (this was missing)

  • I do not want sum, I just want to bring the record with the highest score, in case there is another waiter with the same features bring the with the highest score, this for all records!

  • I think I solved... thanks!

Browser other questions tagged

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