Search code examples
mysqlsqlsqlyog

Would like to get running total of comission SQL table


i'm trying to acheive the following result from one table, "policies"

+-------------+------------------+
|Commission   |Total Commission  |
+-------------+------------------+
|108          |108               |
+-------------+------------------+
|50           |158               |
+-------------+------------------+
|12           |170               |
+-------------+------------------+

and so on...

so far, my query looks like this:

SELECT
  P.commission
  SUM(P.commission) OVER (PARTITION BY P.id ORDER BY P.id) AS "Total Commission"
FROM
  policies P

except use of OVER doesn't seem to be working (words such as SELECT, SUM() and FROM all change text colour to blue because they're keywords)

Please could someone suggest a way to get this working how I want it

EDIT:: p.policy_id didn't exist. Was just p.id, corrected.
EDIT2:: incorrect spelling of "commission", corrected

Further edit:

I am now using the following query, which is fetching the following result:

SELECT p.commission,
   (SELECT SUM(p2.commission)
    FROM policies p2
    WHERE p2.id = p.id AND p2.id <= p.id
   ) AS total_commission
FROM policies p;


+-------------+------------------+
|Commission   |Total Commission  |
+-------------+------------------+
|108          |108               |
+-------------+------------------+
|50           |50                |
+-------------+------------------+
|12           |12                |
+-------------+------------------+

Solution

  • You are probably using MySQL, which doesn't support window functions.

    You can use a correlated subquery instead:

    SELECT p.comission,
           (SELECT SUM(p2.comission)
            FROM policies p2
            WHERE p2.id = p.id and p2.policy_id <= p.policy_id
           ) as total_comission
    FROM policies p;