Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
964 views
in Technique[技术] by (71.8m points)

sql - Difference between two columns in mysql

I have two columns (credit and debited_amount) and I want to calculate the difference between them.Only need to retrieve records greater than zero or if the debited_amount field is Null. Never mind if the value is zero.Here is the sqlquery which I have tried.Please help

SELECT `p_Id`,`user_id`,`doc_id`,`credit` ,`app_date`,`expires_on`,(credit -debited_amount) AS credit
FROM `wp_loyalty_credits` WHERE `expires_on`>now();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You just need to add the logic into the where clause:

SELECT `p_Id`,`user_id`,`doc_id`,`credit` ,`app_date`,`expires_on`,
       (credit -debited_amount) AS credit
FROM `wp_loyalty_credits`
WHERE `expires_on`>now() and (credit > debited_amount or debited_amount is null);

Your query redefines credit in the select. However, that is irrelevant, because you can't refer to a column alias in the where clause. So, the column credit is what it used. It is clearer if you add table aliases:

SELECT lc.p_Id, lc.user_id, lc.doc_id, lc.credit, lc.app_date, lc.expires_on,
       (lc.credit - lc.debited_amount) AS credit
FROM `wp_loyalty_credits` lc
WHERE lc.expires_on > now() and
      (lc.credit > lc.debited_amount or lc.debited_amount is null);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...