0

I have the following question, when I make a query, how can I return the sums in different columns in various periods of time, for example I have this table:

  ---------------------------
  | PRODUCT | VALUE | MONTH |
  ---------------------------
  | P1      | 10    |  2    |
  | P1      |  5    |  3    |
  | P1      |  22   |  4    |
  | P1      |  4    |  2    |
  | P2      |  4    |  2    |
  | P2      |  7    |  4    |
  | P2      |  10   |  4    |

And I wish I had this result

  --------------------------------------
  | PRODUCT | MONTH2 | MONTH3 | MONTH4 |
  --------------------------------------
  | P1      | 14       |  5    | 22    |
  | P2      | 4        |  0    | 17    |
MT0
  • 143,790
  • 11
  • 59
  • 117

1 Answers1

0

You can use conditional aggregation:

select product,
       sum(case when month = 2 then value end) as month2,
       sum(case when month = 3 then value end) as month3,
       sum(case when month = 4 then value end) as month4
from t
group by product;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786