简体   繁体   English

根据来自另一列的不同值对sql值求和,并将结果放入数组

[英]Sum sql values based on distinct values from another column and put the result in array

I am trying to to create an array based on the results from sum values based on the distinct values from another column 我正在尝试基于总和值的结果创建一个数组,该总和值基于另一列的不同值

I have these two columns Month and Lessons. 我有这两列“月份”和“课程”。 In the column month is the month name when the lessons were given (January, February...). 月份中的列是上课的月份名称(一月,二月...)。 In the column lessons I have values like (12,7,6,9,11, etc.) 在专栏中的课程中,我的值是(12,7,6,9,11等)

Example Values 值示例

Month    |lessons
------------------
January  |12 
January  |7
February |6
March    |9
March    |11

What I want to achieve is to sum all lessons for every month and then put the values in an array for example ($month_values = January Sum, February Sum, etc). 我要实现的是汇总每个月的所有课程,然后将值放入数组中(例如,$ month_values =一月总和,二月总和等)。

Example Result 结果示例

$month_values = 19,6,20;

I have managed to get the months with this query 我已经设法得到几个月的查询

$sth = $db->prepare("SELECT DISTINCT month FROM acc where month!=''");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
$months = json_encode($result);

But I am struggling to get the values for each month 但是我在努力获取每个月的价值

I have searched here to see if anyone faced the same challenge, but couldn't find anything that can help me 我在这里搜索过,看看是否有人遇到过同样的挑战,但是找不到任何可以帮助我的东西

Any suggestion how to alter the query above and to put the lessons values in a array? 有什么建议如何更改上面的查询并将课程值放在数组中?

Thanks 谢谢

select group_concat(month), group_concat(l) from (

    SELECT month, SUM(lessons) as l FROM lessons_by_month GROUP BY month

) foo

Will give you 会给你

|   GROUP_CONCAT(MONTH) | GROUP_CONCAT(L) |
|-----------------------|-----------------|
| February,January,June |          2,6,10 |

Simply, what you need in this case is to GROUP the rows by the month column. 简单地说,你在这种情况下,需要的是GROUP在本月列的行。

SELECT month, SUM(lessons) AS lessons FROM lessons_by_month GROUP BY month

I also made an SQL Fiddle with which you can tweak around if you need to. 我还制作了一个SQL Fiddle ,您可以根据需要进行调整。

Here is an example output, based on the input from your question: 这是一个示例输出,基于您的问题的输入:

month    | lessons
------------------
February | 6
January  | 19
March    | 20
SELECT month, SUM(lessons) 
FROM lessons_by_month 
GROUP BY month 
ORDER BY MONTH(STR_TO_DATE(month,'%M')) ASC

The above query will output you sum of lessons in the calendar month order. 上面的查询将按日历月顺序输出课程总和。

SQLFIDDLE DEMO SQLFIDDLE演示

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

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