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

Counting an already counted column in SQL (db2)

我是 SQL 的新手,遇到了这个问题:

我有一个 table 填充的日期列和其他不感兴趣的列。

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 行时才返回它们。
到目前为止我尝试的是用一个临时 table 围绕整个查询并计算所有结果行数(是的)

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,还缺少什么检查。
我在这个论坛中搜索并遇到了一些要使用的 "having" 结构,但这迫使我使用 "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 列结果

在您的 temp_count table 中,您可以使用 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

我认为您只需要将 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

如果您想知道记录总数(分组后)是否 returned,那么您可以这样做:

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 行,这将 return 0 行,如果有 10 行或更多,将提供所有结果(如果需要,您也可以只获取前 10 行)。

类似于:

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);

会做你想做的(我认为)