0
id category
1 eat,drink
2 drink,cup
3 eat,take
4 tea,eat

i need to order records which have max number of category repeated by category column, ex- eat are repeated 3 times then it is comes first order and then drink comes then tea or cup comes.. thanks in advance..

Ranveer
  • 11
  • 4
  • 4
    You should fix your data model. Storing multiple values in a delimited string is not the SQL way to store data. – Gordon Linoff Feb 16 '21 at 16:22
  • You will find that [many queries become hard to solve](https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad/3653574#3653574) when you store comma-separated lists like this. They will be easier if you store categories as a separate table, one row per category. – Bill Karwin Feb 16 '21 at 16:34
  • thanks @GordonLinoff but we can not change the flow on mid of project , do you have solution for above flow. – Ranveer Feb 16 '21 at 17:03

1 Answers1

0

As Gordon suggested data model should be changed to get most out of RDBMS. But what you are looking for can be achieved through below query:

select category,count(*) category_count from(
select t.id, j.category 
from tablename t
join json_table(
  replace(json_array(t.category ), ',', '","'),
  '$[*]' columns (category  varchar(50) path '$')
) j
)t
group by category
order by count(*) desc;

Output:

enter image description here