简体   繁体   中英

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?

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 |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM