Return rows with the highest value in a column

Asked

Viewed 737 times

0

I have a problem with a query in an Oracle database in a table with 3 columns:

ID_Loja | Canal | Valor_Venda

There is the possibility of having more than one sale per store and I want to know which channel assigned to the store based on the amount of sales that each store had as an example below. In that case, I want the query just return the line containing channel "A" since in that case there were 5 sales vs 4 sales to the same store with different rating.

           ID_Loja: 1
             Canal: A
Count(Valor_Venda): 5

           ID_Loja: 1
             Canal: B
Count(Valor_Venda): 4

So far, I’ve only done query that brings the amount of sales per store/channel, but I could not bring only the combination that has more sales per store/channel only.

SELECT ID_Loja, Canal, COUNT(Valor_Venda)
FROM Vendas
GROUP BY ID_loja, Canal

1 answer

0

I do not have Oracle here, but try to use a temporary table, in the syntax of postgresql was like this:

with temp as (select 
    f.ID_Loja,
    f.Canal,
    count(*) as qtd
    from Vendas f
    group by f.Canal,f.ID_Loja )

select  distinct
f.ID_Loja,
t.Canal,
t.qtd
from Vendas f 
inner join temp t on t.ID_Loja = f.ID_Loja and t.qtd = (select max(qtd) from temp x where x.ID_Loja = t.ID_Loja)
order by t.qtd desc
  • In this case, as there are 2 different channels for the same store, your query will return the 2 lines. In case I need to return only the line that has the highest number of sales per store and its respective channel, thus excluding the line of the store that has the channel "B"

  • I edited the answer, but since I don’t have Oracle, maybe it’s not the same syntax as postgresql, anything, try using http://sqlfiddle.com/ to show us the schema and query

  • Note. I chose this way, because if there are two stores with the same amount in two channels, these will appear in the result too

Browser other questions tagged

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