【问题标题】:How to sum two rows of sql query如何对两行sql查询求和
【发布时间】:2017-03-02 17:25:55
【问题描述】:

在一个数据库中,我有学生注册的事件。它看起来像这样:

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

例如

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

我有以下查询:

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

query_to_html 将查询转换为 html 表。 这给了我以下信息:

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

我想根据学习关联(数组)总结一些研究,例如第 1 组)数学、天文学、物理和计算机科学以及第 2 组)生物学和生物医学科学。像这样:

study_association, amount
Fundamentals, 166
Bio, 50

其中 166 和 55 是对应于 study_association 数组的几行的总和。

我该怎么做?

谢谢!

【问题讨论】:

  • 添加一些示例表数据和预期的结果 - 以及所有格式化文本。

标签: php html sql


【解决方案1】:

您可以使用 SUM(IF()) 仅计算特定行。我假设您的专栏是“组”:

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

这将计算给定数组中某一组中的注册人。

【讨论】:

    猜你喜欢
    • 2013-01-30
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2018-05-06
    相关资源
    最近更新 更多