MySQL:以逗号分隔列[重复]获取数据计数

问题描述 投票:0回答:1

我有一个存储数据的表,如:

userid    books
ym0001    dictionary,textbooks,notebooks
ym0002    textbooks,dictionary

我想计算每本书发生的次数。我希望我的结果是这种格式。

books       Counts
dictionary  2
notebooks   1
textbooks   2

这是mysql。请帮忙

mysql
1个回答
0
投票

以下方法构建1000个整数的结果,然后使用这些整数(n)来定位逗号分隔字符串中的段,并为每个段创建一个新行,以便派生表如下所示:

userid | book      
:----- | :---------
ym0001 | dictionary
ym0002 | textbooks 
ym0001 | textbooks 
ym0002 | dictionary
ym0001 | notebooks 

一旦存在,这是一个简单的问题,按书分组以达到计数。

select
    book, count(*) Counts
from (
    select
           t.userid
         , SUBSTRING_INDEX(SUBSTRING_INDEX(t.books, ',', numbers.n), ',', -1) book
    from (
        select @rownum:=@rownum+1 AS n
        from
        (
           select 0 union all select 1 union all select 2 union all select 3 
           union all select 4 union all select 5 union all select 6 
           union all select 7 union all select 8 union all select 9
        ) a
        cross join (
           select 0 union all select 1 union all select 2 union all select 3 
           union all select 4 union all select 5 union all select 6 
           union all select 7 union all select 8 union all select 9
        ) b
        cross join  (
           select 0 union all select 1 union all select 2 union all select 3 
           union all select 4 union all select 5 union all select 6 
           union all select 7 union all select 8 union all select 9
        ) c
        cross join (select @rownum:=0) r
        ) numbers
    inner join mytable t
      on CHAR_LENGTH(t.books)
        -CHAR_LENGTH(REPLACE(t.books, ',', '')) >= numbers.n-1
    ) d
group by
    book
order by
    book
book       | Counts
:--------- | -----:
dictionary |      2
notebooks  |      1
textbooks  |      2
  1. 如果您已有数字表,请改用它。
  2. b和c的交叉连接动态地产生1000行,如果你需要更多添加类似于c的交叉连接。即,数字的数量应超过逗号分隔数据的最大长度

db <>小提琴here

© www.soinside.com 2019 - 2024. All rights reserved.