过去5年的sql查询和分组?

时间:2013-08-14 22:24:15

标签: sql group-by db2 sum

我是SQL的新手,我正在研究DB2,我需要得到过去5年中id和x的总和。

以下是到目前为止我已经实现的查询,但是,我只需要获得最后5个yaers,这将获得我多年来的数据。我试图为sql语句添加前5,它似乎不起作用,它显示一些错误。如何修改此查询以仅获取最近5年的数据?

select (sum(X) + sum(Y)) as tot,some_date
from table where fkid = 1 
group by year order by year desc;

以下是我期待的数据格式。

总年份
552,074.78 2012-01-01 466,283.62 2011-01-01 640,813.37 2010-01-01 721,182.28 2009-01-01 719,676.05 2008-01-01

我得到的错误如下

  

错误:DB2 SQL错误:SQLCODE = -104,SQLSTATE = 42601,SQLERRMC = 5; VALUE(CONCAT || / - + FROM INTO *,\ AS。年,DRIVER = 3.58.81   SQLState:42601 ErrorCode:-104   错误:DB2 SQL错误:SQLCODE = -514,SQLSTATE = 26501,SQLERRMC = SQL_CURLH200C1,DRIVER = 3.58.81   SQLState:26501   ErrorCode:-514

编辑:列中包含日期类型,列名称不是年份,例如我将其修改为some_year。

1 个答案:

答案 0 :(得分:2)

您的查询问题很简单(假设这是唯一的问题)。 year是保留字,因此请用双引号括起来:

select (sum(X) + sum(Y)) as tot, "year"
from table
where fkid = 1 
group by "year"
order by "year" desc;

过去五年是另一回事。根据{{​​1}}列,您可以执行以下操作:

year

或者您实际上可能有另一列具有可以使用的日期时间,而不是select (sum(X) + sum(Y)) as tot, "year" from table where fkid = 1 and year >= year(current timestamp) - 5 group by "year" order by "year" desc;

编辑:

如果您有一个名为"year"的列是日期,您可以使用:

dt

如果您只希望一行包含总和,请忽略select (sum(X) + sum(Y)) as tot, year(dt) as "year" from table where fkid = 1 and dt >= CURRENT DATE - 5 years and dt <= CURRENT DATE group by year(dt) order by year(dt) desc; 子句。