我对这些php mysql语句感到困惑。
我需要从表中的同一列(金额)中获得四个不同的结果。
这些函数为以下项找到(金额)的总和:
今年迄今为止
去年给时间
去年捐款总额
最近30天内捐赠
它们似乎都是相同的变化。我不知道如何获取LastYearNow以显示正确的结果。如何显示从2016年初到今天的日期2016的结果?
public function getSum() {
$query = $this->db->query("SELECT SUM(amount) as amount_sum FROM " . DB_PREFIX . "donate Where date_added >= (CURDATE() - INTERVAL 12 MONTH) ");
return $query->row;
}
public function lastThirty() {
$query = $this->db->query("SELECT SUM(amount) as amount_sum FROM " . DB_PREFIX . "donate Where date_added >= (CURDATE() - INTERVAL 1 MONTH)" );
return $query->row;
}
public function lastYearNow() {
$query = $this->db->query("SELECT SUM(amount) as amount_sum FROM " . DB_PREFIX . "donate Where date_added >= (CURDATE() - INTERVAL 12 MONTH) ");
return $query->row;
}
public function lastYearTotal() {
$query = $this->db->query("SELECT SUM(amount) as amount_sum FROM " . DB_PREFIX . "donate Where YEAR(date_added) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))" );
return $query->row;
}
最佳答案
查询lastYearNow
当前正在计算总数的最后12个月。相反,如果要计算从一年的第一天到当前日期的去年总计,则需要使用BETWEEN子句:
SELECT SUM(amount) as amount_sum
FROM donate
WHERE date_added BETWEEN
MAKEDATE(YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR)), 1, 1)
AND
(CURDATE() - INTERVAL 12 MONTH)
警告:我前面没有安装MySQL,因此语法可能不太正确。