Problems to count and group fields in the database

Asked

Viewed 40 times

0

I’m starting to study the SQL language and the interaction between the tables, and I came across an exercise in a list that I’m not able to solve.

inserir a descrição da imagem aqui

He asks the following:

For each existing product say what sales were made and how many items were ordered.

I tried this solution, but I did not reach the expected answer:

SELECT
    p.nome, COUNT(i.fk_venda)AS qtd_venda
FROM
    tb_produto AS p, tb_itens AS i
WHERE
    p.pk_produto=i.fk_produto
GROUP BY
    p.nome;
  • Your script prints which result ?

  • @Tuliocalil groups all registered items, with the exception of one of them. And the sum of the quantities sold does not match what I recorded earlier.

  • You can export the bank so I understand better here ?

  • @Tuliocalil the Caique has solved my doubt, but I still thank you for your attention!

  • You’re welcome! Good luck and success!

1 answer

0


From what I understand your question would be the following.

Display the quantity of items grouping by sale and by product, display the product description, display the sale identification.

See if the select below suits you, if you do not show us what it returns.

SELECT
     p.nome           [Produto]
   , fk_venda         [idVenda]
   , COUNT(i.pk_item) [QuantidadeItens]
FROM
    tb_produto 
INNER JOIN tb_itens AS i
   ON p.pk_produto = i.fk_produto
GROUP BY
    p.nome, fk_venda;
  • That’s what I was trying to do! Before by the way I did he grouped all the sales of a product, IE, he did not display the sales separately as the request for the exercise. With this solution, the sales identifications were separated, and the items accounted for according to the product. Thank you very much!

  • Exactly, Gina. I’m happy to help

Browser other questions tagged

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