Compare products for years in different columns of the same table

Asked

Viewed 27 times

0

Good afternoon!

I would like to perform a select in sql that solves the following question: I have a sales table related to one of products, however, I want to compare the results of the same product in 2018 and 2019.

The table has more or less this structure:

estrutura

I’d like a result like that:

result

Can anyone help? Thank you in advance! :)

  • Try making a Count using the between, and then compare the years Count

  • Luiz, can you help me with an example? It would help a lot. Thank you for answering! :)

  • https://tapoueh.org/blog/2013/07/simple-case-for-pivoting-in-sql/ pivot with CASE a possible solution. The question is pertinent , I do not understand the criticism.

  • Thanks for the help Motta. I also did not understand the criticism the question, I thought valid... Ball forward!

1 answer

0


Try:

SELECT coalesce(a.produto, b.produto) AS "Produto", coalesce(a.quantidade, 0) AS "Qtd 2018", coalesce(b.quantidade, 0) AS "Qtd 2019" FROM
 (SELECT * FROM sua_tabela WHERE ano = 2018) a
 FULL OUTER JOIN
 (SELECT * FROM sua_tabela WHERE ano = 2019) b
 ON (a.produto = b.produto)
 ORDER BY 1;

Another possibility is to use the Crosstab function of the tablefunc module (https://www.postgresql.org/docs/current/tablefunc.html).

  • Gave straight! Thank you so much for your help. :)

Browser other questions tagged

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