gpt4 book ai didi

sql - mysql - 按多列频率排序

转载 作者:行者123 更新时间:2023-11-29 04:59:10 24 4
gpt4 key购买 nike

我有一个包含 5 列的表格:

  • 标记 1
  • 标签 2
  • 标签 3
  • 标记 4
  • 标签 5

如果我想显示按这些标签的流行度(频率)排序的结果,我会使用哪种查询?

最佳答案

因为表格没有规范化,所以你必须先把它展平:

SELECT a.column, a.tag1 AS tag
FROM TABLE a
UNION ALL
SELECT b.column, b.tag2
FROM TABLE b
UNION ALL
SELECT c.column, c.tag3
FROM TABLE c
UNION ALL
SELECT d.column, d.tag4
FROM TABLE d
UNION ALL
SELECT e.column, e.tag5
FROM TABLE e

...在你数数之前:

SELECT t.tag, COUNT(*) tag_popularity
FROM (SELECT a.column, a.tag1 AS tag
FROM TABLE a
UNION ALL
SELECT b.column, b.tag2
FROM TABLE b
UNION ALL
SELECT c.column, c.tag3
FROM TABLE c
UNION ALL
SELECT d.column, d.tag4
FROM TABLE d
UNION ALL
SELECT e.column, e.tag5
FROM TABLE e) x
GROUP BY x.tag
ORDER BY tag_popularity DESC

关于sql - mysql - 按多列频率排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3463876/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com