简体   繁体   English

如何在DB2 SQL中获取数据,限制返回的行数,并对一列的这些行求和?

[英]How to get data in DB2 SQL, limit the number of rows returned and also SUM those rows for one column?

I have a simple query that returns some records: 我有一个简单的查询,返回一些记录:

select reference as ref, amount as amt
from my.table
where foo_ref like 'B%'
and foo_amount != 0.000
fetch first 12 rows only

What I would also like to do is to SUM the amt column for these 12 returned rows. 我还想做的是对这12条返回的行的amt列求和。 I am a newbie to SQL so I am not sure how this is done. 我是SQL的新手,所以不确定如何完成此操作。 Any help is appreciated. 任何帮助表示赞赏。

 select reference as ref, SUM(amount) as amt
 from my.table
 where foo_ref like 'B%'
 and foo_amount != 0.000
 group by reference
 fetch first 12 rows only

The SUM() adds the values in amount. SUM()将值相加。 I added a group by for the reference. 我添加了一个分组供参考。 The result will be a table that is a group of references with a sum of the amount. 结果将是一个表,该表是一组引用的总和。

Any time you use a SUM(), COUNT(), MAX(), MIN() - et cetera you also have to add a group by to fields that are not using these functions. 每当您使用SUM(),COUNT(),MAX(),MIN()等时,您还必须向不使用这些功能的字段中添加分组依据。

What version and release of DB2? 什么版本和发行版的DB2? There's some powerful OLAP functionality in current versions.. 当前版本中有一些强大的OLAP功能。

with tbl as (
   select reference as ref, amount as amt
   from my.table
   where foo_ref like 'B%'
     and foo_amount != 0.000
   order by ref
   fetch first 12 rows only )
select tbl.*, sum(amt) as tot_amt 
from tbl  
group by rollup ((ref,amt))

This will return 13 rows, with the 13th containing NULL for ref and amt while having the total for the 12 rows in tot_amt. 这将返回13行,第13行包含ref和amt的NULL,而tot_amt中包含12行的总数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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