Mysql 統計標簽出現次數(一行變多行)


需求背景

需求
  • 一張數據表
  • 其中有sid字段,代表tag,每行數據可能有多個tag字段
  • 統計全量數據中所有tag出現的次數(按tag分組,分別有多少數據)
source table demo
id sid
1 a3,a4,a1,a2,a5
2 a5,a3,a4,a2
3 a5,a3,a4
target table demo
sid_tag sid_occurrence
a1 1
a2 2
a3 3
a4 3
a5 3
SQL query in mysql
select substring_index( substring_index( sid , ',', id_table.help_topic_id + 1 ), ',',- 1 ) as sid_tag,count(sid) as sid_occurrence from src_t JOIN mysql.help_topic id_table on id_table.help_topic_id < (
  length(src_t.sid) - length(replace(src_t.sid, ',', '')) + 1
) GROUP BY sid_tag

hive

select tag,count(*) from(
select tag from table_name
lateral view explode(split(taglist,',')) r1 AS tag) a group by a.tag;

解析

  • 利用系統表mysql.help_topic進行了index的記錄(可以使用其他表),更暴力的解法是直接新建一張只有id列的表,可以預防系統表id不夠用(一般足夠了)
  • JOIN a.id < b.id,解決了復制行的操作;若b.id = 5,a.id 為(1,2,3,4,5),返回數據為 [(1,5),(2,5),(3,5),(4,5)]
  • substring_index( substring_index( sid , ',', id_table.help_topic_id + 1 ), ',',- 1 ) 利用index表中的index,作為子串索引進行數據拆分。索引構建基於上一步的join。
  • 隨后正常groupby統計

實驗

mysql
select * from (
  SELECT concat('a',topic.help_topic_id) as sid,topic.help_topic_id AS id
  FROM mysql.help_topic topic
  WHERE help_topic_id IN ('1', '2', '3', '4', '5')
) as id_table JOIN (
  SELECT concat('b',topic.help_topic_id) as sid,topic.help_topic_id AS id
  FROM mysql.help_topic topic
  WHERE help_topic_id IN ('1', '2', '3')
) as id_table2 on id_table2.id <= id_table.id
結果
sid id sid id
a1 1 b1 1
a2 2 b1 1
a2 2 b2 2
a3 3 b1 1
a3 3 b2 2
a3 3 b3 3
a4 4 b1 1
a4 4 b2 2
a4 4 b3 3
a5 5 b1 1
a5 5 b2 2
a5 5 b3 3


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM