简体   繁体   English

如何计算所有列中的数字或出现次数并使用MySQL列出它们?

[英]How to count numbers or occurrences in all columns and list them using MySQL?

I have a table looking like: 我有一张桌子,看起来像:

| A | B | C | ... | Z |  <- names of columns
-----------------------
| 1 | 0 | 1 | ... | 1 | 
| 0 | 1 | 1 | ... | 1 | 
| 1 | 1 | 1 | ... | 1 | 
| 0 | 1 | 1 | ... | 0 | 
| 1 | 0 | 1 | ... | 1 | 

And I would like to sum up all 1s in all the columns and list them out. 我想总结所有列中的所有1,并将其列出。 How can I do that using MySQL? 如何使用MySQL做到这一点? Number of columns is about 80, if possible I would like not to list them in the SQL call. 列数大约为80,如果可能的话,我不想在SQL调用中列出它们。

I would like to get a response similar to this one: 我想得到与此响应类似的响应:

A: 3
B: 3
C: 5
...
Z: 4

This table has been designed in a way that makes the query you describe more difficult. 该表的设计方式使您描述的查询更加困难。

Using many columns for data values that should be compared or counted together because they're the same type of value is called repeating groups . 使用许多列作为数据类型应当比较或计数的数据值,因为它们是相同的值类型 ,称为重复组 It's a violation of database normalization rules. 这违反了数据库规范化规则。

The more traditional way to store this data would be over 80 rows, not 80 columns. 存储数据的更传统的方法是超过80行,而不是80列。

CREATE TABLE mytable (
  id INT PRIMARY KEY,
  label CHAR(1) NOT NULL,
  value TINYINT NOT NULL
);

INSERT INTO mytable VALUES
('A', 1), ('B', 0), ('C', 1), ...

Then you could use a simple query with an aggregate function like this: 然后,您可以使用带有聚合函数的简单查询,如下所示:

SELECT label, SUM(value)
FROM mytable
GROUP BY label;

There are times when it's worth using a denormalized table design (like your current table), but that time is when you want to optimize for a particular query. 有时候值得使用非规范化表设计(例如当前表),但是那时候是您要针对特定​​查询进行优化的时候。 Be careful about using denormalized designs, because they optimize for one query at the expense of all other queries you might run against the same data. 使用非规范化设计时要格外小心,因为它们会针对一个查询进行优化,而您可能会针对相同数据运行所有其他查询。 The query you want to make is one of those that is made more difficult by using the denormalized design you currently have. 您要进行的查询是使用当前具有的非规范化设计而变得更加困难的查询之一。

There is no easy way, you will need to explicitly list the columns. 没有简单的方法,您将需要显式列出这些列。 A UNION query should be what you need, like: UNION查询应该是您所需要的,例如:

SELECT 'A' column_name, SUM(A) cnt FROM mytable
UNION ALL SELECT 'B', SUM(B) FROM mytable
UNION ALL SELECT 'C', SUM(C) FROM mytable
...

NB: it should be possible to generate the query programmatically using any text manipulation tool (Excel, perl, ...), or dynamically using a prepared statement. 注意:应该可以使用任何文本处理工具(Excel,perl等)以编程方式生成查询,也可以使用准备好的语句动态生成查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM