Nihilius
Nihilius

Reputation: 23

SELECT statement with a new column based on a value

I have a table like this:

month year  id  amount
1     2001  1   345.5
2     2001  1   123.5
3     2001  1   654.5
4     2001  1   542.5
5     2001  1   123.5
6     2001  1   123.5
7     2001  1   654.5
8     2001  1   654.5
9     2001  1   789.3
10    2001  1   654.5
11    2001  1   123.5
12    2001  1   654.5
1     2002  1   123.5
2     2002  1   123.5
3     2002  1   654.5
...

and I want to change it with a SELECT statement so it looks like this:

month  id  2001   2002   2003 ...
1      1   345.5  123.5
2      1   123.5  123.5
3      1   654.5  654.5
4      1   542.5  ...
5      1   123.5
6      1   123.5
7      1   654.5
8      1   654.5
9      1   789.3
10     1   654.5
11     1   123.5
12     1   654.5

I tried a SELECT statement like this:

SELECT
  month, year, id, amount, sum(amount_order) AS YEAR(getdate())-1
FROM
  receipts
WHERE
  id = '1'
  AND year BETWEEN YEAR(getdate())-5 AND YEAR(getdate())-1
GROUP BY
  month, year, id

because I wanted to set the table name as the value of the years of past 5 years to past 1 year (here with only the column name of the year before). Is it even possible to do this with one SELECT statement?

Upvotes: 1

Views: 53

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269483

Use conditional aggregation:

select month, id,
       sum(case when year = 2001 then amount else 0 end) as amount_2001,
       sum(case when year = 2002 then amount else 0 end) as amount_2002,
       . . . 
from t
group by month, id;

Upvotes: 1

Related Questions