Question

I have a table with 3 fields(id, jobsprocess,percent) and want to work out the cumulative percent on the fly, so it is a derived field.

in sql i would do this, which returns 13 records.

set @x := 0;
SELECT ID, jobsprocess, PERCENT, (@x := @x + PERCENT) AS cumaltive
FROM `hdb`.`lookupprocess`
inner join jobsprocess on jobprocess = process_id
where projid = 1302035
order by id

How can I do this in yii? So far I have the following but it is not giving me the results that i want

$lastrun = Yii::app()->db->createCommand("
                    SELECT ID, jobsprocess, PERCENT , (:criteria = :criteria + PERCENT) AS cumulative
                    FROM `hdb`.`lookupprocess`
                    inner join jobsprocess on jobprocess = process_id
                    where projid = $projid
                    order by id " )->queryAll(true, array(':criteria'=>0));

returns 13 records but the cumulative is always 0.

I have also tried th3e following but i get an error

$user = Yii::app()->db->createCommand()
    ->select('ID, jobsprocess, PERCENT , (:zero := (:zero + PERCENT)) AS cumulative')
    ->from('lookupprocess')
    ->join('jobsprocess','jobprocess = process_id')
    ->where('projid = :projid', array(':projid'=>$projid,':zero'=>0))

    ->queryAll();

it takes :zero as a string.

CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':= ('0' + PERCENT)) AS cumulative
FROM `lookupprocess`
JOIN `jobsprocess` ON job' at line 1. The SQL statement executed was: SELECT ID, jobsprocess, PERCENT , (:zero := (:zero + PERCENT)) AS cumulative
FROM `lookupprocess`
JOIN `jobsprocess` ON jobprocess = process_id
WHERE projid = :projid 
Was it helpful?

Solution

You can declare your SQL variable in the FROM part of your query:

SELECT ID, jobsprocess, PERCENT, (@x := @x + PERCENT) AS cumaltive
FROM `hdb`.`lookupprocess`, (SELECT @x=0) q
inner join jobsprocess on jobprocess = process_id
where projid = 1302035
order by id

So, something like this:

$lastrun = Yii::app()->db->createCommand("
    SELECT ID, jobsprocess, PERCENT , (@x := @x + PERCENT) AS cumulative
    FROM `hdb`.`lookupprocess`, (SELECT @x:=0) q
    inner join jobsprocess on jobprocess = process_id
    where projid = $projid
    order by id " )->queryAll();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top