对日期内的多列求和

时间:2018-10-05 14:51:46

标签: sql date sum intervals

祝大家有美好的一天,我要做一个查询,将一些列加在一起。

$sqlannoprima = "SELECT fascia_prezzo,data,giorno,
   SUM (a1,a2,a3,a4,a5,a6,a7,a8) as atot, 
   SUM (g1,g2,g3,g4,g5,g6,gtesi,gg) as gtot,
   SUM (f1,f2,f,3,f4) as ftot, SUM (lt1,lt2,lt3,lt4,ltg) as lttot,
   FROM giorni 
   WHERE STR_TO_DATE(giorno, '%d/%m/%Y')- INTERVAL 1 YEAR BETWEEN STR_TO_DATE('" . $d1 . "', '%d/%m/%Y')- INTERVAL 1 YEAR 
     AND STR_TO_DATE('" . $d2 . "', '%d/%m/%Y')- INTERVAL 1 YEAR 
   GROUP BY giorno 
   ORDER BY STR_TO_DATE(giorno, '%d/%m/%Y')- INTERVAL 1 YEAR";

但是当我尝试打印结果时,SQL返回错误。

注意:尝试在第377行的E:\ EasyPHP \ data \ localweb \ cdm \ stats.php中获取非对象的属性

这是在377行:$ risultatoannoprima = $ queryannoprima-> num_rows;

我想念什么? 非常感谢

3 个答案:

答案 0 :(得分:3)

您需要删除sql中,之后的最后一个lttot 另外,您最好直接使用(INTERVAL 1 YEAR)而不是INTERVAL 1 YEAR

  $sqlannoprima = "SELECT fascia_prezzo,data,giorno,
   SUM (a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8) as atot, 
   SUM (g1 + g2 + g3 + g4 + g5 + g6 + gtesi + gg) as gtot,
   SUM (f1 + f2 +f3 + f4) as ftot, 
   SUM (lt1 + lt2 + lt3 + lt4 + ltg) as lttot
   FROM giorni 
   WHERE STR_TO_DATE(giorno, '%d/%m/%Y')- (INTERVAL 1 YEAR) BETWEEN STR_TO_DATE('" . $d1 . "', '%d/%m/%Y')- (INTERVAL 1 YEAR) AND STR_TO_DATE('" . $d2 . "', '%d/%m/%Y')- (INTERVAL 1 YEAR) GROUP BY giorno 
   ORDER BY (STR_TO_DATE(giorno, '%d/%m/%Y')- (INTERVAL 1 YEAR))";

答案 1 :(得分:3)

SUM()是一个聚合函数,它使用行+求和,对求和,例如:

(f1 + f2 + f3 + f4)  as ftot

SUM(f1 + f2 + f3 + f4) as ftot

如果要对行和列求和

答案 2 :(得分:0)

选择fascia_prezzo,data,giorno,将SUM(a1)作为a1,将SUM(a2)作为a2,将SUM(a3)作为a3,将SUM(a4)作为a4,将SUM(a4)作为a4,将SUM(a5)作为a5,SUM(a6)为a6,SUM(a7)为a7,SUM(a8)为a8,(SUM(a1)+ SUM(a2)+ SUM(a3)+ SUM(a4)+ SUM(a5)+ SUM (a6)+ SUM(a7)+ SUM(a8))作为来自giorni的atot STR_TO_DATE(giorno,'%d /%m /%Y')在STR_TO_DATE('“。$ d1。”','%d /%m /%Y')和STR_TO_DATE('“。$ d2。”'之间,'%d /%m /%Y') GROUP BY fascia_prezzo,data,giorno ORDER BY STR_TO_DATE(giorno,'%d /%m /%Y')