我有两列(credit和debited_amount),我想计算它们之间的差,只需要检索大于零的记录或debited_amount字段为Null。没关系,如果值是零。这是我尝试过的sqlquery。请帮助
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();
您只需要在where子句中添加逻辑即可:
where
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);
您的查询credit在中重新定义select。但是,这无关紧要,因为您不能在where子句中引用列别名。因此,该列credit就是它所使用的。如果添加表别名,则更加清楚:
credit
select
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);