我试图找出每个数字出现在一列中的次数。我有一个数据库,用于存储父母签到自己的孩子的密码,以便他们将孩子签入和送出学前班。
引脚号存储在CHAR(4)
列中;但它们都是数字。
我努力了:
SELECT COUNT(pin) AS Count
FROM adult
WHERE pin LIKE '%2%';
返回以下结果:
+-------+
| Count |
+-------+
| 182 |
+-------+
但是,这只能告诉我有多少记录具有“ 2”,而不是发生了多少次(因为一条记录可以具有超过1个“ 2”。这也是一个非常手动的过程,需要处理每个数字0-9。
我想要看起来更像的东西:
+-----+-----+
|Value|Count|
+-----+-----+
| 0| 204|
| 1| 200|
| 2| 182|
. .
. .
. .
| 9| 203|
+-----+-----+
这超出了我对SQL的了解。非常感谢您的帮助!
您可以使用substr()
:
select substr(t.pin, n.pos, 1) as chr, count(*)
from adult t cross join
(select 1 as pos union all select 2 union all select 3 union all select 4
) n
group by substr(t.pin, n.pos, 1)
order by chr;
这会提取中的每个字符,pin
然后按该字符进行汇总。该from
子句等效于:
from ((select substr(col, 1, 1) from adult union all
(select substr(col, 2, 1) from adult union all
(select substr(col, 3, 1) from adult union all
(select substr(col, 4, 1) from adult
) t
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句