当count大于postgres sql中的特定数字时,选择count

时间:2017-08-15 10:39:41

标签: sql postgresql

我想从表中获取上个月的记录。我试过了:

SELECT count(*) as numberOfRows from Table where created_at >  CURRENT_DATE - INTERVAL '1 months'

没关系,但我想添加一些条件:

  

如果numberOfRows> = 10,则不执行任何操作(numberOfRows可以是20,30,...)

     

否则,如果numberOfRows< 10,从这个表中选择,直到numberOfRows       = 10(最近2个月,3个月等)。

我该怎么做? 谢谢你的进步!

2 个答案:

答案 0 :(得分:2)

WITH curr_month_cnt AS (
    SELECT COUNT(*) AS cnt
    FROM your_table
    WHERE created_at > CURRENT_DATE - INTERVAL '1 months'
)

SELECT *
FROM your_table
WHERE created_at > CURRENT_DATE - INTERVAL '1 months'
UNION ALL
SELECT t.*
FROM
(
    SELECT *
    FROM your_table
    WHERE
        created_at <= CURRENT_DATE - INTERVAL '1 months' AND
        (SELECT cnt FROM curr_month_cnt) < 10
    ORDER BY created_at desc
    LIMIT
        GREATEST(0, 10 - (SELECT cnt FROM curr_month_cnt))
) t

这将从最近一个月开始向后返回最多10条记录。如果最近一个月没有10条记录,那么将按顺序返回两个月和三个月的数据。

答案 1 :(得分:0)

根据您的描述,您似乎想要:

select greatest(10, count(*)) as numberOfRows
from Table
where created_at >  CURRENT_DATE - INTERVAL '1 months';

这似乎相当令人惊讶。也许你想要:

select (case when sum( (CURRENT_DATE - INTERVAL '1 months' ) :: int) >= 10 
             then sum( (CURRENT_DATE - INTERVAL '1 months' ) :: int)
             else least(10, count(*))
        end) as numberOfRows
from Table
where created_at > CURRENT_DATE - INTERVAL '1 months';