如何递归运行sql查询?

wlzqhblo  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(380)

例如,有一个accounts表具有:

account_id | ......    
000        | ......    
001        | ......    
004        | ......    
010        | ......   
.....   
198        | ......

我想得到帐户id的分布,而不是一次又一次地运行下面的查询,有没有更聪明的方法来获得000-010,010-020,…,190-200的id计数?谢谢

SELECT count(account_id)
FROM accounts
WHERE account_id >= '000' AND  account_id <= '010';
x7yiwoj4

x7yiwoj41#

你可以划分 account_id 按10创建一个范围,然后按除以的结果分组以获得所需的结果:

SELECT CONCAT(LPAD(FLOOR(account_id/10)*10,3, '0'), '-', LPAD(FLOOR(account_id/10)*10+9, 3, '0')) AS `range`,
       COUNT(*) AS number
FROM accounts
GROUP BY `range`

输出(对于演示中的一些示例数据):

range       number
000-009     3
010-019     2
020-029     1
030-039     1
040-049     1
050-059     2

在dbfiddle上演示

dohp0rv5

dohp0rv52#

你会用 group by :

select (case when account_id >= '000' and account_id <= '010' then '000-010'
             when account_id >= '011' and account_id <= '020' then '011-020'
             when account_id >= '021' and account_id <= '030' then '021-030'
             . . .
        end) as account_id_grp,
       count(*)
from accounts
group by account_id_grp
order by account_id_grp;
tyky79it

tyky79it3#

select t1.account_id ||'-'||t2.
     account_id,count(*) from 
     table t1 where account_id IN (Select account_id from 
      table t2 where t2.account_id-t1.account_id=10)`

我试着通过相关子查询获取表中帐户ID的差异

相关问题