从一个数据库表中计算日期范围的数据

时间:2016-03-31 20:54:10

标签: php sql joomla3.0

我有sql函数:

        $sql = "SELECT date(datum_ura) as datetime, 
                   COUNT(CASE rezultat_status_fk WHEN 5 THEN rezultat_status_fk END) AS half_lost, AVG(kvota) as average, SUM(vlozek) as vlozek,
                   SUM(CASE rezultat_status_fk WHEN 1 THEN vlozek * kvota WHEN 2 THEN vlozek WHEN 3 THEN 0 END) AS case_profit,
                   SUM(CASE rezultat_status_fk WHEN 1 THEN vlozek * kvota-vlozek WHEN 2 THEN 0 WHEN 3 THEN -vlozek END) AS profit
            FROM bs_analiza 
            WHERE users_fk=$user_id"." group by date(datum_ura)";

该函数从一个表中获取数据并计算它并按日期显示结果。我正在尝试执行一个函数,它可以将当前日期结果与结果前一天相加....等等。

我想的是:

foreach ($items as $key => $value) {    
$date = $value->datetime;           
    $prev_date = date('Y-m-d', strtotime($date .' -1 day'));
    $prev_date = strtotime($prev_date);
    $i = $key-1;
$profit_before = $items[$i]->$prev_date;

但我仍然得到相同的结果。

1 个答案:

答案 0 :(得分:0)

您可以使用中间结果中的选择来实现此目的,建议您创建视图或使用WITH

SELECT
   datetime,
   (SELECT SUM(vlozek) FROM ... WHERE datetime >= t.datetime) vlozek_cumsum,
   (SELECT SUM(case_profit) FROM ... WHERE datetime >= t.datetime) case_profit_cumsum,
   (SELECT SUM(profit) FROM ... WHERE datetime >= t.datetime) profit_cumsum
FROM
   ... t
ORDER BY
   datetime DESC

...是您的中间结果。

编辑(澄清):您通过select语句获得中间结果。所以你可以

  1. 创建视图并将...替换为视图名称或

    CREATE OR REPLACE VIEW <view_name> AS <select_stmt>
    
  2. 使用WITH并使用别名替换上述查询中的所有...

    WITH <alias_name> AS ( <select_stmt> )
    SELECT
       ...