我正在尝试使用所有费用的总和构建一个数组。年,正如您在下面的查询/代码中看到的那样。这不是一个很好的解决方案,因为我将不得不做大约40个查询。如何为此构建更优的查询?不能为我的生活搞清楚这一点。我应该使用PHP代替while ($date< 2011-04-01) { sql; $date +1year; }
等等吗?
$a = "SELECT sum(field_fee_value) FROM content_type_transfer WHERE field_inorout_value = 'In' AND field_date_value BETWEEN '1996-04-01T23:00:00' AND '1997-04-01T23:00:00'";
$b = "SELECT sum(field_fee_value) FROM content_type_transfer WHERE field_inorout_value = 'In' AND field_date_value BETWEEN '1997-04-01T23:00:00' AND '1998-04-01T23:00:00'";
$c = "SELECT sum(field_fee_value) FROM content_type_transfer WHERE field_inorout_value = 'In' AND field_date_value BETWEEN '1998-04-01T23:00:00' AND '1999-04-01T23:00:00'";
$a = db_result(db_query($a));
$b = db_result(db_query($b));
$c = db_result(db_query($c));
$array = array($a, $b, $c, $d, $e);
非常感谢你。我会试着详细说明是否要弄清楚我要去哪里。或者至少试着去。
答案 0 :(得分:0)
您可以在查询中使用GROUP BY
子句,以提高效率。试试这个:
$results = "SELECT sum(field_fee_value), YEAR(field_date_value) as 'year' FROM content_type_transfer WHERE field_inorout_value = 'In' GROUP BY YEAR(field_date_value)";
此查询将为您提供每年field_free_value
的总和。
答案 1 :(得分:0)
以下是您的解决方案:
SELECT sum(field_fee_value)
FROM content_type_transfer
WHERE field_inorout_value = 'In'
GROUP BY YEAR(field_date_value)
此外,您可以按最小/最大时间值限制查询
答案 2 :(得分:0)
您可以将40个查询合并为一个
// replace @date to field_date_value
SELECT
IF ( month(@date)=4 and day(@date)=1 and time(@date)>='23:00:00',
year(@date)+1, year(@date)) as year_distribution,
SUM(field_fee_value)
FROM content_type_transfer
WHERE
field_inorout_value = 'In' AND
field_date_value BETWEEN '{minimum_date}' AND '{maximum_date}'
GROUP BY year_distribution;
预期结果
1996 SUM(field_fee_value)
1997 SUM(field_fee_value)
...
2011 SUM(field_fee_value)