[英]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:我想用一个 SELECT 语句来改变它,所以它看起来像这样:
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 语句:
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).因为我想将表名设置为过去 5 年到过去 1 年的值(这里只有前一年的列名)。 Is it even possible to do this with one SELECT statement?甚至可以用一个 SELECT 语句来做到这一点吗?
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.