我有一个数据库,其中包含多行数据集合,如下所示:
Username: BillyBob
TotalPrice: 19.99
CreationDate: 2012-02-20 14:30:58
我需要在PHP中执行一个类似这样的SQL语句。
$sql = mysql_query(" Add up Total Price Where Username='BillyBob' Where CreationDate is within this month ");
我该怎么做呢?我也想做最近30天,上周,特定日期范围等事情。
这可能吗?
答案 0 :(得分:2)
只需添加错误和输入的处理(给定月份的总回报),您只需要在您感兴趣的任何时间段内更改monthStart和monthEnd逻辑/值。
//Parameters for query
$month = '2012-02';
$username = 'BillyBob';
//Make date start and end
$monthStart = $month.'-01 00:00:00';
$monthEnd = $month.'-'.date('t', strtotime($monthStart)).' 23:59:59';
//Make the query
$query = sprintf("
SELECT SUM(TotalPrice)
WHERE Username = '%s'
AND CreationDate >= '%s'
AND CreationDate <= '%s'",
mysql_real_escape_string($username),
mysql_real_escape_string($monthStart),
mysql_real_escape_string($monthEnd)
);
$result = mysql_query($query);
if ($result) {
if (mysql_num_rows($result) == 1) {
//Output / process number e.g.:
list($total) = mysql_fetch_num($result);
echo 'Total for '.$username.' from '.date('l, jS F Y', strtotime($monthStart)).' to '.date('l, jS F Y', strtotime($monthEnd)).' = £'.number_format($total, 2);
} else {
//error handling
}
} else {
//error handling
}
答案 1 :(得分:0)
http://www.tizag.com/mysqlTutorial/mysqlsum.php
你可以使用mysql sum。请参阅此处并应用于您的数据库结构
可能类似于Select *,sum(totalPrice)来自tbl,其中Username ='BillyBob'和CreationDate&lt;'2012-02-20 14:30:58'
答案 2 :(得分:0)
我会尝试这样的事情(未经测试):
$sql = mysql_query("SELECT SUM(TotalPrice) FROM myTable WHERE Username = 'BillyBob' AND CreationDate BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()");