I have one series as '12345234123123543'. How to write a function in SQL to find out which digit has most occurrence in a given series?
If you are using SQL Server then You may do like this
DECLARE @Str VARCHAR(MAX)='12345234123123543'
;WITH CTE AS(
SELECT CAST('' AS NVARCHAR(1)) AS CH, 1 AS CNT
UNION ALL
SELECT CAST(SUBSTRING(@Str,CNT,1)AS NVARCHAR(1)) AS CH , CNT+1
FROM CTE
WHERE CNT<=LEN(@Str)
)
SELECT TOP 1 CH,COUNT(CH)
FROM CTE
WHERE CH <> ''
GROUP BY CH
ORDER BY COUNT(CH) DESC
If you are using Postgres you can use the following:
select c, count(*) as cnt
from unnest(string_to_array('12345234123123543',null)) as t(c)
group by c
order by cnt desc
limit 1;
Output:
c | cnt
--+----
3 | 5
Edit: inspired by Jaydip's answer, this can indeed be expressed with standard SQL only:
with recursive cte (ch, cnt) as (
values ('', 1)
union all
select substring('12345234123123543' from cnt for 1) as ch, cnt+1
from cte
where cnt <= character_length('12345234123123543')
)
select ch, count(ch)
from cte
where ch <> ''
group by ch
order by count(ch) desc
fetch first 1 rows only
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.