I have table like this:
-----------
ID | Value
-----------
1 | AAAA
2 | ABCD
3 | AADC
4 | ABBD
I am trying to figure out how to return the number of times a string occurs in each of the Value.
So, if I want to count of time 'A' and 'B'appears, the sql statement will return like this:
-------------------
ID | Value | Count
-------------------
1 | AAAA | 0
2 | ABCD | 1
3 | AADC | 0
4 | ABBD | 2
5 | ABBB | 3
6 | AABB | 3
7 | AAAB | 3
Is there any way to do this? I do not want to use php, vb, etc. Just MySQL
答案 0 :(得分:1)
你可以尝试这个伴侣:
SELECT
ID,
Value,
LENGTH(REPLACE(Value, 'A', '')) 'count_a',
LENGTH(REPLACE(Value, 'B', '')) 'count_b'
FROM
your_table;
或者这个:
SELECT
ID,
Value,
LENGTH(REPLACE(Value, IF(LENGTH(REPLACE(Value, 'A','')) = 3, 'A', 'B'), '')) 'Count',
FROM
your_table;
这是基于给定的预期结果
答案 1 :(得分:0)
似乎您想要计算值,然后合并结果。我相信这样的事情对你有用。
SELECT
id,
value,
ROUND (
(
LENGTH(value)
- LENGTH(REPLACE(value, "A", ""))
) / LENGTH("A")
) AS count
FROM chars
UNION ALL
SELECT
id,
value,
ROUND (
(
LENGTH(value)
- LENGTH(REPLACE(value, "B", ""))
) / LENGTH("B")
) AS count
FROM chars