在MySql中同时计数3个值为yes和no的列

66bbxpm5  于 2022-12-17  发布在  Mysql
关注(0)|答案(3)|浏览(136)

该表有列英语,西班牙语和法语。每一个有是或否的值,我想计数的数量是和否的每一列到一个表。
我尝试使用非重复计数,但它不能将所有列放在一个表下。
它应该如下所示:

Key| French   | Spanish |English|
--—| -------- | ------- |——————-|  
Yes|    45    |    35   |  72   |
No |    27    |    37   |  0    |
uxhixvfz

uxhixvfz1#

你可以试试GROUP BY子句。

SELECT `key`, 
  sum(`french`) as french,
  sum(`spanish`) as spanish,
  sum(`english`) as english
FROM `answers` 
GROUP BY `key`;
key     french  spanish  english    
no      3       2        1
yes     1       2        3

使用以下模式

CREATE TABLE `answers` (
  `key` varchar(3) NOT NULL DEFAULT '',
  `french` int(11) NOT NULL,
  `spanish` int(11) NOT NULL,
  `english` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `answers` (`key`, `french`, `spanish`, `english`) VALUES
('yes', 1, 2, 3),
('no', 3, 2, 1);
oxalkeyp

oxalkeyp2#

假设包含英语、Spanish和French三列的表名为Source_Table,下面是一个可以完成您所需任务的查询:

select
  'YES' Key,
  (select count(1) from Source_Table where French='YES') French, 
  (select count(1) from Source_Table where Spanish='YES') Spanish,
  (select count(1) from Source_Table where English='YES') English
from Source_Table
Limit 1 
union 
  'NO' Key, 
  (select count(1) from Source_Table where French='NO') French,
  (select count(1) from Source_Table where Spanish='NO') Spanish,
  (select count(1) from Source_Table where English='NO') English
from Source_Table
Limit 1

希望这对你有帮助。最好的问候。

hc2pp10m

hc2pp10m3#

在MySQL中,使用字符串列表示“yes”和“no”而不是布尔列是很少见的,但是这里的查询几乎是一样的。
您希望一个结果行表示“Yes”,一个结果行表示“No”,但是每行都有yes和no值。因此,您需要为两个结果行使用UNION ALL。您要联合的两个查询遍历所有行,并有条件地计算语言。在标准SQL中,我们将使用COUNT(*) FILTER (WHERE french = 'yes')来完成此操作,而在某些不支持FILTER子句的DBMS中,我们会使用COUNT(CASE WHEN french = 'yes' THEN 1 END)SUM(CASE WHEN french = 'yes' THEN 1 ELSE 0 END),但在MySQL中,这变得更简单,因为在MySQL中true = 1和false = 0,我们可以只使用SUM(french = 'yes')
完整查询:

select
  'Yes' as yes_or_no,
  sum(french = 'yes') as french,
  sum(spanish = 'yes') as spanish,
  sum(english = 'yes') as english
from mytable
union all
select
  'No' as yes_or_no,
  sum(french = 'no') as french,
  sum(spanish = 'no') as spanish,
  sum(english = 'no') as english
from mytable;

相关问题