如何按唯一数据范围对mysql数据进行分组

时间:2017-12-06 16:11:33

标签: php mysql

我想从左侧数据为这个右侧输出创建一个sql查询,如下图所示:

enter image description here

这是我到目前为止的查询,但没有得到正确的结果:

SELECT CONCAT(MONTH(Date),?Last day of month,YEAR(date)) AS Date,
       SUM(Amount1) AS rslt1,
       SUM(Amount2) AS rslt2 
FROM table 
GROUP BY MONTH(date), YEAR(date)

1 个答案:

答案 0 :(得分:3)

例如......

SELECT ym
     , @a1 := @a1 + a1 amount1
     , @a2 := @a2 + a2 amount2
  FROM 
     ( SELECT DATE_FORMAT(date,'%Y-%m') ym 
            , SUM(amount1) a1
            , SUM(amount2) a2 
         FROM my_table 
        GROUP 
           BY ym 
     ) x
     , (SELECT @a1:=0,@a2:=0) vars
 ORDER
    BY ym;