我的SQL请求加入2个表,结果是支付金额,按付款方式分组。付款方式存在于payment_history
表中:BlueMedia,Transferuj,BankPayment和ChangeSum。另外payment_history.payment_method
列可以包含空字符串或NULL
- 在这种情况下,我想将其作为“其他”值进行检索。postgresql:额外的WHERE子句隐藏行
SQL查询是:
SELECT
CASE
WHEN COALESCE(payment_history.payment_method, '') = '' THEN 'other'
ELSE payment_history.payment_method
END as payment_method,
CASE
WHEN SUM(paid_balance) IS NULL THEN 0.00
ELSE SUM(paid_balance)
END as paid_balance,
CASE
WHEN SUM(sum_without_commission) IS NULL THEN 0.00
ELSE SUM(sum_without_commission)
END as sum_without_commission
FROM
payment_history
LEFT JOIN
participants_list ON payment_history.registration_id = participants_list.registration_id
WHERE
payment_history.client_id = 258 AND
participants_list.deleted = 0 AND
participants_list.is_reserved = 0
GROUP BY payment_history.payment_method
结果(以付款方式Transferuj没有记录,这是好的,因为它是缺席了当前客户端id
= 258):
other
表示该记录存在于payment_history
中,其中payment_method
是NULL
或空字符串。
我不想检索记录,其中付款方式为ChangeSum
。在查询所以,我已经添加了相应的条件:
...
WHERE payment_history.client_id = 258
AND payment_history.payment_method != 'ChangeSum'
...
但在结果集也other
是空的:
为什么会出现这种问题,我能做些什么来获得所需要的数据方法(包括other
,当payment_method
列包含NULL
||空字符串;但没有ChangeStatus
)?
谢谢你,它的工作原理!我会后我的答案(我需要使用'NULLIF'太多,因为它可以为空字符串也,不仅'NULL'),但究竟你的回答将被接受。 –
@Boolean_Type你说得对,我忽略了'nullif()'的需要。虽然乐意帮忙! – SqlZim
不幸的是,我不是SQL中的profi。可以ü,请解释一下,为什么'COALESCE(payment_history.payment_method, '')!='ChangeSum''让我看到'other'?我明白,这个问题是万一'payment_method'包含'NULL',但不明白,它是如何阻止检索行'other' ...也就是说,当payment_method包含NULL时结果如何呢?和'空!=“ChangeSum''返回'null'?.. –