SQL data count filtered by multiple tables

Asked

Viewed 61 times

1

I have a PHP page where I have to generate a chart of "Registered sellers" filtered by region.

The problem is that the Sellers table has City Id, the City table has State Id and the State Id has Region Id. And I need to filter the salesmen for region.

Follow the structures:

Seller’s Table
Tabela de Vendedores
City Table
Tabela de Cidade
Status table
Tabela de Estado
Region Table
Tabela de Região

1 answer

1


Basically a great JOIN fix everything:

select v.PrimeiroNome as "Nome do Vendedor", r.Nome as "Região"
from Vendedores v
inner join Cidades c on c.Id = v.IdCidade
inner join Estados e on e.Id = c.IdEstado
inner join Regionais r on r.Id = e.IdRegional;

To count:

select tabela.Nome as "Região", count(*) from
    (select v.PrimeiroNome as "Nome do Vendedor", r.Nome -- as "Região"
    from Vendedores v
    inner join Cidades c on c.Id = v.IdCidade
    inner join Estados e on e.Id = c.IdEstado
    inner join Regionais r on r.Id = e.IdRegional) tabela
-- group by "Região"; -- Isto aqui deu erro no Browser.
group by tabela.Nome
  • I did, but it didn’t work out. My problem is in making the related Seller count (Table 1) filtered by Region (Table 4) and then grouping everything (group by).

  • I updated the answer.

  • It worked perfectly in the query program. I already marked as correct, but in the Browser it was error. Each GROUP BY expression must contain at least one column that is not an outer reference Would you know what it means? Anyway thank you so much.

  • Strange to have given it. I updated again.

Browser other questions tagged

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