【问题标题】:MySQL how to get count of instances across columns as well as rows?MySQL如何跨列和行获取实例数?
【发布时间】:2021-09-08 19:27:37
【问题描述】:

我有一张像这样有 10 列的表格,显示在虚拟商店购买的物品,以及用于购买它的货币:

+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+------------+
| soldfor_1 | soldfor_2 | soldfor_3 | soldfor_4 | soldfor_5 | soldfor_6 | soldfor_7 | soldfor_8 | soldfor_9 | soldfor_10 |
+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+------------+
| Gold      | Gold      | Gold      | Silver    | Silver    |           | Bronze    | Gold      |           | Gold       |
| Gold      | Gold      | Gold      | Gold      | Gold      | Gold      |           |           |           |            |
| Bronze    | Silver    | Silver    | Silver    | Gold      | Gold      | Silver    | Bronze    | Gold      |            |
+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+------------+

我想查询此选择,以便创建使用的三种不同货币(黄金、白银和青铜)的列表,按货币在任何列和任何行中出现的次数排序。

例如,我想要的查询输出如下所示:

Gold 14
Silver 6
Bronze 3

它计算了三种不同类型货币在列和行中出现的次数,然后将它们放入按此数量排序的列表中。然后它在每种货币旁边附加了次数。

但是我没有运气。到目前为止,我能够做的是计算项目在任何行上出现的次数,有点 - 查询看起来像这样:

SELECT 
    soldfor_1, 
    soldfor_2, 
    soldfor_3, 
    soldfor_4, 
    soldfor_5, 
    soldfor_6, 
    soldfor_7, 
    soldfor_8, 
    soldfor_9, 
    soldfor_10, 
    COUNT(*) 
FROM phpbb_topics 
WHERE 
   forum_id=16 
   AND sold=1 
GROUP BY topic_title 
ORDER BY COUNT(*) DESC

但这只会给我一个有序的货币列表,因为它们只出现在 ROWS 中。我希望它也考虑 COLUMNS。

有人知道我能做什么吗?

【问题讨论】:

    标签: mysql


    【解决方案1】:

    你可以unpivot,在MySQL中使用union all

    select soldfor, count(*)
    from ((select soldfor_1 as soldfor from phpbb_topics) union all
          (select soldfor_2 as soldfor from phpbb_topics) union all
          . . .
          (select soldfor_10 as soldfor from phpbb_topics)
         ) s
    group by soldfor;
    

    通常,当您有多个仅按数字区分的列时,这表明数据模型不好。更合理的数据模型应该有一个每列值有一行的表。

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 2016-03-08
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      相关资源
      最近更新 更多