serhio
serhio

Reputation: 28586

aggregate values in SQL columns

I am SQL beginner and I have the following question:

I have the following data (article sales by week)

COUNT   WEEK    ART
4           1   A
9           1   B

5           2   A
4           2   B

6           3   A
5           3   B

7           4   A
2           4   B

I would like to have the following output

ODD_WEEK    EVEN_WEEK   ART
10          12          A
14          6           B

in other words, I would like to group the elements by a criteria in a column (ODD_WEEK) and by an other criteria in another column (EVEN_WEEK)

Is it possible in T-SQL?

Upvotes: 0

Views: 69

Answers (1)

Meherzad
Meherzad

Reputation: 8563

Try this query

select
   art,
   sum(case when week%2=0 then count else 0 end) even,
   sum(case when week%2<>0 then count else 0 end) odd
from 
   tbl
group by 
   art

FIDDLE

| ART | EVEN | ODD |
|-----|------|-----|
|   A |   12 |  10 |
|   B |    6 |  14 |

Upvotes: 5

Related Questions