【问题标题】:Mysql getting rows by each month in each yearMysql每年按月获取行数
【发布时间】:2017-04-19 12:27:50
【问题描述】:

我试图找出每年每个月的总成本。

我有下表“日志”

date               |    cost
---------------------------------
Wed, 01 Aug 2016   |    45
Tue, 15 Aug 2016   |    52
Mon, 31 Aug 2016   |    23
Thu, 05 Sep 2016   |    9
Sat, 10 Sep 2016   |    33
Mon, 12 Feb 2017   |    8
Tue, 31 Feb 2017   |    0
Wed, 31 Mar 2017   |    100
Fri, 31 Mar 2017   |    35
Thu, 31 Mar 2017   |    45

这就是我想要达到的目标,

2017

二月 8+0

三月 100+35+45


2016

8 月 45+52+23

九月 9+33


目前我正在这样做,

$sqly = "SELECT DISTINCT RIGHT(date,4) as year FROM logs ORDER BY id DESC;";
$resy = mysql_query($sqly);
while($rowy = mysql_fetch_array($resy))
{
   echo $rowy['year'];
}

结果:

2017

2016

我不知道如何进一步获取每年的月份并将每个月的总数相加。

【问题讨论】:

标签: php mysql


【解决方案1】:

这个查询应该可以工作:

SELECT YEAR(STR_TO_DATE(date, '%W, %d %M %Y')) AS year,
       MONTH(STR_TO_DATE(date, '%W, %d %M %Y')) AS month, 
       SUM(cost) 
FROM logs 
GROUP BY year, month;

【讨论】:

    【解决方案2】:

    试试这个查询。

    SELECT YEAR(date) AS year, MONTH(date) AS month, COUNT(DISTINCT id) FROM logs GROUP BY year, month
    

    【讨论】:

    • 我将年份和月份设为 NULL 以及条目数。
    【解决方案3】:
    You can use below code to find your answer, Hope this will help you
    
    <?php
    
    $sqly = "SELECT DISTINCT RIGHT(date,4) as year FROM logs ORDER BY id DESC;";
    $resy = mysql_query($sqly);
    while($rowy = mysql_fetch_array($resy))
    {
       echo $rowy['year'];
    
       $sqly2 = "select SUBSTRING(date, 9, 3) as month_name, Group_concat(cost,' + ') as total_cost from logs where RIGHT(date,4) = '".$rowy['year']."' GROUP BY SUBSTRING(date, 9, 3)";
        $resy2 = mysql_query($sqly2);
    
        while($rowy2 = mysql_fetch_array($resy2))
    {
       echo $rowy2['month_name'] ." ".$rowy2['total_cost'] ;
    
    }
    }
    

    【讨论】:

    • 感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 2018-06-17
    • 2014-12-12
    • 1970-01-01
    相关资源
    最近更新 更多