SQL Group same ID with another condition

Asked

Viewed 1,162 times

1

I believe it’s a little specific question, because I haven’t found anything related yet.

I have a table called contas_produtos, which is a relationship Nxn between the tables contas and the table produtos.

The table has the following columns:

ID (PK)
conta_id (FK)
produto_id (FK)
precoFinal (float)

Well, this one precoFinal indicates the final value of a given product, which can be changed by the application, ie two products can have the same id, but with different values of precoFinal.

What I wish to do is to be able to group the same products id, but with equal final prices, and separate these products from those that have even id but different final prices.

I know I can’t just group by precoFinal, because it would take products with different prices.

What I’ve done so far is group by id, but it does not serve me, therefore it does not compensate nor I put my SQL here.

A lot of text, I know, but I think it would be easier to explain like this.
Thank you

2 answers

1

See if it solves

SELECT conta_id, 
       produto_id, 
       precofinal 
FROM   ((produtos 
         INNER JOIN contas_produtos 
                 ON id = conta_id) 
        INNER JOIN produtos 
                ON produto_id = produto_id ) 
GROUP  BY id, 
          precofinal 
  • Thank you for your answer and your friendly effort, but I think the easiest solution would really be group by with two fields. Anyway, thanks for your time.

  • Not for that, the problem, but I put Grup by with two fields, the rest of sql is only there to represent what you did not post, and as you said yourself that there is a relation of Nxn in the mentioned tables, the correct is to use the Inner Join in these cases, the only difference between our answers is syntax. but anyway good luck !

-2

Well, I’m sorry, I managed to settle just by using group by with more than one column, as follows:

SELECT Count(*) AS quantidade, 
       conta_id, 
       produto_id, 
       precofinal 
FROM   conta_produtos 
GROUP  BY produto_id, 
          precofinal
  • Good luck !

  • Sorry, but why -2 ? Shouldn’t I have answered my own question? How to proceed in this case?

Browser other questions tagged

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