How to select CNPJ higher billing? - SQL -

Asked

Viewed 63 times

0

Hello, everybody!

I have a table of customers with Grupo Economico code and CNPJ, each economic group has more than one record, and I cross-checked with my Billing and Address table, so far so good.

I wanted to take the CNPJ address of higher billing and have as final result only Code Economic Group and Address, without showing the CNPJ and Billing, but I can’t.

After crossing tried the code below, but the result is wrong, the address is not CNPJ higher billing:

Select CodGrupo, NomeGrupo, First(CNPJ), Max(Fat), Cidade, UF
From tbl_EndFat 
Group By CodGrupo, NomeGrupo, Cidade, UF 
OrderBy max(fat)

Edit: My goal is for the query to return the highest billing CNPJ address for each economic group.

Any suggestions?

  • Why the "First(CNPJ)"? The goal is just to return the record of higher billing?

  • No, I expressed myself badly, the goal is to return the CNPJ address of higher turnover for each Economic Group.

2 answers

0

According to your question I made a solution, you said you want the economic code and address of the company with the highest turnover, however two companies may have the highest turnover, this may be a problem, but according to your question this is not a problem. Follow the code that can help you, basically is to recover only the company(s) that has the highest turnover.

If you only want the company with the highest turnover group by is unnecessary, in my view.

Select CodGrupo, NomeGrupo, Cidade, UF
From tbl_EndFat 
where Fat = (select max(fat) from tbl_EndFat)
  • Assuming Group Name is functionally dependent on Codgroup you need to correlate the subselect Codgroup with the outermost SELECT.

  • Hey, buddy, I like the suggestion, but it doesn’t apply. I didn’t express myself well, actually I need you to output show me the highest billing CNPJ address for each Economic Group. Thanks

0

My goal is for the query to return the CNPJ address of higher revenue for each economic group.

Evaluate if the following sql code returns what you need.

-- código #1
SELECT top (1) with ties 
       CodGrupo, NomeGrupo, CNPJ, Faturamento, Cidade, UF
  from ...
  order by rank() over (partition by CodGrupo
                        order by Faturamento desc);

Browser other questions tagged

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