我有两列(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();
答案 0 :(得分:1)
您只需将逻辑添加到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
就是它所使用的。如果添加表别名则更清楚:
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);