php - 按添加年份对所有每月收入组进行排序

标签 php mysql

想要显示我每月和每年的所有支出,如下图 [][2] 所示,代码如下所示

SELECT 
    monthname(date_added) as monthname,
    year(date_added) as year,
    SUM(amount) as amounts 
    FROM incomes GROUP BY year ORDER BY monthname

2017年
一月 100 美元
二月 $200
7 月 90 美元
六月 $300

<小时/> 2018年
一月 100 美元
二月 $200
7 月 90 美元
六月 300 美元

最佳答案

似乎您需要按日期和月份订购

    select t.year, t.monthname, t.amounts
    from(
         SELECT monthname(date_added) as monthname, 
                month(date_added) month, 
                year(date_added) as year,
                SUM(amount) as amounts 
                FROM incomes 
                GROUP BY year, month, monthname
    )
    ORDER BY t.year, t.month

或者如果您需要今年和上一年的两个单独的结果

对于实际年份,您可以

select t.year, t.monthname, t.amounts
from(
     SELECT monthname(date_added) as monthname, 
            month(date_added) month, 
            year(date_added) as year,
            SUM(amount) as amounts 
            FROM incomes 
            where year(date_added) = year(curdate())
            GROUP BY year, month, monthname
)
ORDER BY t.year, t.month

上一年你可以

select t.year, t.monthname, t.amounts
from(
     SELECT monthname(date_added) as monthname, 
            month(date_added) month, 
            year(date_added) as year,
            SUM(amount) as amounts 
            FROM incomes 
            where year(date_added) = year(curdate()) -1 
            GROUP BY year, month, monthname
)
ORDER BY t.year, t.month

关于php - 按添加年份对所有每月收入组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52374077/

相关文章:

PHP 未定义偏移量

javascript - PHP json_decode 不适用于对象 GET 变量

c# - 将行从一个表移动到另一个表

html文件里面的php不会执行

php - 使用 PHP 和 MySQL 创建成员(member)个人资料页面

php - 尝试在 echo 中间使用 if 函数

mysql - 需要连接 2 个表,但 MySQL 中另一个表中的某些行除外

mysql - 出现 1045 错误时,如何在 SQL 中导出运行查询的结果?

php - Laravel 队列错误 'Illuminate\Http\UploadedFile' 的序列化是不允许的

php - 在 PHP 中从 MySQL 存储过程获取输出值和记录集