Sql, sum of several

Asked

Viewed 66 times

-1

Hello, I have a bank with 3 important tables, state,city and orders need to rank the states than have more requests to q have less but the orders are related only to city table. so I need to make a Count for each city and add the Counts of the cities that belong to the same state. but I have no idea how to do that. someone can help me?

state table structure: inserir a descrição da imagem aqui

structure of the city table: inserir a descrição da imagem aqui

order table structure: inserir a descrição da imagem aqui

  • 2

    Post the structure of the 3 tables, it makes it easier to help you.

1 answer

4


Considering generic names of tables and fields:

SELECT es.nome as estado, ci.nome as cidade, COUNT(pe.id)
FROM pedidos pe
LEFT JOIN cidade ci ON ci.id = pe.cidade
LEFT JOIN estado es ON es.id = ci.estado
WHERE pe.datapedido BETWEEN '01/01/2018' AND '31/01/2018'
GROUP BY es.nome, ci.nome

In its structure:

SELECT es.estado, COUNT(pe.id)
FROM pedidos pe
LEFT JOIN cidades ci ON ci.id = pe.cidade_id
LEFT JOIN estado es ON es.id = ci.estado_id
GROUP BY es.estado
  • Hello thanks for the help, the output I need would be order status-number & #Xa;your query returns quite different

  • @Matheuslima Alterei. Look now.

  • now it worked, thank you so much for your help

Browser other questions tagged

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