计算SQL中已计数的列(db2)

时间:2015-03-23 13:54:45

标签: sql count db2

我对SQL很陌生并遇到这个问题:

我有一个填充表格,其中包含日期列和其他不感兴趣的列。

date | name | name2

2015-03-20 | peter | pan
2015-03-20 | john | wick
2015-03-18 | harry | potter

我现在正在做的是计算一切日期

select date, count(*)
from testtable
where date >= current date - 10 days
group by date

我现在要做的是计算结果线,只有在少于10条结果线的情况下才返回它们 我到目前为止所尝试的是围绕整个查询使用临时表并计算所有给出了结果行数的东西(是的)

with temp_count (date, counter) as 
(  
select date, count(*)
from testtable
where date >= current date - 10 days
group by date
    )
select count(*)
from temp_count

如果数字小于10,那么仍然缺少检查。
我在这个论坛上搜索并遇到了一些“有”结构使用,但这迫使我使用“group by”,我不能。 我在考虑这样的事情:

with temp_count (date, counter) as 
(  
select date, count(*)
from testtable
where date >= current date - 10 days
group by date
    )
select *
from temp_count
having count(*) < 10

也许我太累了想到一个简单的解决方案,但到目前为止我无法解决这个问题

编辑:一张图片,因为我的英语太可怕了 http://imgur.com/1O6zwoh

我想看到只有总行数少于10行的2个柱状结果

3 个答案:

答案 0 :(得分:0)

在temp_count表中,您可以使用WHERE子句过滤结果:

with temp_count (date, counter) as 
(  
select date, count(distinct date)
from testtable
where date >= current date - 10 days
group by date
    )
select *
from temp_count
where counter < 10

答案 1 :(得分:0)

我认为您只需将having子句移至内部查询,以便与GROUP BY配对:

with temp_count (date, counter) as 
(  
    select date, count(*)
    from testtable
    where date >= current date - 10 days
    group by date
    having count(*) < 10
)
select *
from temp_count

如果您想要知道是否返回了记录总数(分组后),那么可以执行此操作:

with temp_count (date, counter) as 
(  
    select date, counter=count(*)
    from testtable
    where date >= current date - 10 days
    group by date
)
select date, counter
from (
    select date, counter, rseq=row_number() over (order by date)
    from temp_count
) x
group by date, counter
having max(rseq) >= 10

如果总数少于10,则返回0行,如果有10个或更多,则返回所有结果(如果需要,也可以获得前10行)。

答案 2 :(得分:0)

类似的东西:

with t(dt, rn, cnt) as (
    select dt, row_number() over (order by dt) as rn
         , count(1) as cnt 
    from testtable 
    where dt >= current date - 10 days 
    group by dt
) 
select dt, cnt 
from t where 10 >= (select max(rn) from t);

会做你想要的(我认为)