例如,有一个帐户表具有:
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';
答案 0 :(得分:1)
您将使用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;
:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingStart="5dp"
android:textColor="@color/blank"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/tv_title"
android:background="@color/white"
android:paddingLeft="5dp"
android:paddingStart="5dp"
android:singleLine="false"
android:textColor="@color/black"
android:textStyle="italic" />
</RelativeLayout>
答案 1 :(得分:1)
您可以将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
答案 2 :(得分:0)
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的差异