Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get a calculated output as mysql column?

I need to make a calculation by using a mysql query.

Here is my query.

SELECT  book_name, 
CASE WHEN  CURDATE()<book_return THEN 0 ELSE DATEDIFF(CURDATE(),book_return) END AS DateDifference,
CASE WHEN  DateDifference>0 THEN DateDifference*10 ELSE NULL) END AS TotalFines  FROM tblIssuedBooks order by lastupdated DESC

I need to mutiply DateDifference column by 10 if the DateDIfference value is greater than zero.but when I execute this I am getting Unknown column 'DateDifference' in 'field list' as an error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can someone show me how to improve this?

>Solution :

You can’t reuse an alias in a select which was defined in the same select. One workaround here uses a subquery:

SELECT book_name, DateDifference,
       CASE WHEN DateDifference > 0 THEN DateDifference*10 END AS TotalFines
FROM
(
    SELECT *, CASE WHEN CURDATE() < book_return
                   THEN 0
                   ELSE DATEDIFF(CURDATE(), book_return) END AS DateDifference
    FROM tblIssuedBooks
) t
ORDER BY lastupdated DESC;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading