简体   繁体   English

如何对两行SQL查询求和

[英]How to sum two rows of sql query

In a database I have registrations vof students for an event. 在数据库中,我为某项活动的学生提供了注册信息。 It looks like this: 看起来像这样:

id, firstname, surname, gender, email, studydegree, study, workshop1, workshop2, participate_speeddating, ss_companies, date of birth, date of registration

for example 例如

6574, John, Doe, Male, johndoe@gmail.com, Phd, ComputerScience, None, None, no, None, 01-01-1990, 01-01-2017

I have the following the query: 我有以下查询:

    <?php query_to_html('Studies', 'SELECT study, COUNT(*) FROM registrants GROUP BY study'); ?> 

where query_to_html transforms the query into an html table. 其中query_to_html将查询转换为html表。 This gives me the following: 这给了我以下内容:

study , COUNT(*)
Mathematics, 90
Physics, 71
Astronomy, 5
Biology, 25
Biomedical Sciences, 25
... etc

I'd like to sum some of the studies, based on study association (array), for example group 1) Mathematics, Astronomy, Physics and Computer Science and group 2) Biology and Biomedical sciences. 我想总结一些基于研究关联(数组)的研究,例如第1组:数学,天文学,物理和计算机科学,第2组:生物学和生物医学。 Like this: 像这样:

study_association, amount
Fundamentals, 166
Bio, 50

where 166 and 55 is a sum of a few rows corresponding to the study_association array. 其中166和55是对应于study_association数组的几行之和。

How do I do this? 我该怎么做呢?

Thanks! 谢谢!

You can use SUM(IF()) to count only specific rows. 您可以使用SUM(IF())仅计算特定的行。 I assume your column is "group": 我认为您的专栏是“组”:

SELECT
    study,
    COUNT(*) AS sum,
    SUM(IF(`group` IN ('Mathematics', 'Astronomy', 'Physics', 'Computer Science'), 1, 0) AS group1,
    SUM(IF(`group` IN ('Biology', 'Biomedical'), 1, 0) AS group2
FROM registrants
GROUP BY study

This will count registrants which are in one of group in given array. 这将计算给定数组中属于一组的注册人。

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

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