1

我想计算上个月的总金额。

$people_sql = "SELECT SUM(amount) AS people"
    . " FROM room WHERE userid = '$userid'"
    . " AND date BETWEEN DATE_FORMAT(NOW() - INTERVAL 1 MONTH, '%Y-%m-01')"
    .          " AND DATE_FORMAT(NOW() ,'%Y-%m-01')";

例如 2013 年 6 月 1 日 - 30 日

通过运行上述查询,我​​得到 0。

如何让它工作。

4

2 回答 2

0

您想将字符串转换回日期:

SELECT SUM(amount) AS people
FROM room
WHERE userid = '$userid' AND
      date >= date(DATE_FORMAT(NOW() - INTERVAL 1 MONTH, '%Y-%m-01')) AND
      date < date(DATE_FORMAT(NOW() ,'%Y-%m-01'))

这使用了date()函数,您也可以使用它str_to_date()来提供特定的格式。

我更改了,between因为它将包括当月的第一天。

另一种表述方式是:

SELECT SUM(amount) AS people
FROM room
WHERE userid = '$userid' AND
      date_format(date, '%Y-%m') = date_format(now() - interval 1 month, '%Y-%m')

这更简洁。您的方法的优点是它可以利用date.

于 2013-07-14T17:51:27.847 回答
0

当我运行查询

SELECT 
  SUM(amount) AS people, 
  DATE_FORMAT(NOW() - INTERVAL 1 MONTH, '%Y-%m-01') as from_date, 
  DATE_FORMAT(NOW() ,'%Y-%m-01') as to_date
FROM room 
WHERE userid = 1
  AND date >= DATE_FORMAT(NOW() - INTERVAL 1 MONTH, '%Y-%m-01') 
  AND date < DATE_FORMAT(NOW() ,'%Y-%m-01')

我得到了很好的价值观。

架构:

CREATE TABLE room 
    (
     id int auto_increment primary key, 
     userid int,
     date datetime,
     amount integer
    );

INSERT INTO room
(userid, date, amount)
VALUES
(1, now(), 1), (1, now(), 2), (1, '2010-01-01', 4), (1, '2013-06-20', 8)
于 2013-07-14T17:54:05.977 回答