Question

I have a mysql query that subtracts amounts from several rows to show a new amount in a new column called "Balance". I would like it to only show those records where Balance > '0'. See below:

    SELECT 
visits.visit_id,
visits.payment_increments,
((visits.total - visits.paid) - SUM(payments.amount)) AS Balance,
schedule.schedule_date
FROM
visits
    LEFT OUTER JOIN
schedule ON visits.schedule_id = schedule.id
    LEFT OUTER JOIN
payments ON visits.visit_id = payments.visit_id
WHERE
Balance>'0'
GROUP BY visits.visit_id

Is there a way to use my new column in the WHERE statement? Right now, all it shows is an error -> Error Code:1054 Unknown column 'Balance' in 'where clause'.

Any help is much appreciated!

Was it helpful?

Solution

use HAVING instead of WHERE

GROUP BY ... HAVING Balance >0

Note : HAVING works works with non-table columns ..Since Balance is not a column of main table, so this is an imaginary column, so it will work with HAVING just like WHERE works with table columns

Read more...

OTHER TIPS

  SELECT 
visits.visit_id,
visits.payment_increments,
((visits.total - visits.paid) - SUM(payments.amount)) AS Balance,
schedule.schedule_date
FROM
visits
    LEFT OUTER JOIN
schedule ON visits.schedule_id = schedule.id
    LEFT OUTER JOIN
payments ON visits.visit_id = payments.visit_id

GROUP BY visits.visit_id HAVING  Balance>'0'

You can use the same SQL query just you have to mention full column name

   SELECT 
   visits.visit_id,
   visits.payment_increments,
   ((visits.total - visits.paid) - SUM(payments.amount)) AS Balance,
   schedule.schedule_date
  FROM
     visits
    LEFT OUTER JOIN
   schedule ON visits.schedule_id = schedule.id
   LEFT OUTER JOIN
  payments ON visits.visit_id = payments.visit_id
WHERE
  ((visits.total - visits.paid) - SUM(payments.amount))>'0'
 GROUP BY visits.visit_id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top