何时在 postresql 查询中使用 COALESCE 函数?

发布于 2024-12-10 13:39:30 字数 77 浏览 0 评论 0原文

我用谷歌搜索了很多,但没有找到我的问题的可以理解的答案。有趣的是 4 我什么时候必须在查询中使用 COALESCE 函数。预先感谢您的答复。

I googled a lot but did not find understandable answer for my question. It is interesting 4 me when do I have to use COALESCE function in query. Thank you in advance for your answer.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾城°AllureLove 2024-12-17 13:39:30

当您想要“列”的第一个非 NULL 值时(这种意义上的列意味着在您的查询输出中,而不是在您的表中)。

一个例子可能是公司的联系人。假设您有三列:

CompanyRep
CompanySecretary
CompanyOwner

并且您想要存储所有三列。但是,在让您知道应该联系谁的查询中,您希望按照给定的顺序传递其中一个。但其中任何一个或全部都可能为 NULL。

查询:

select coalesce (CompanyRep, CompanySecretary, CompanyOwner, '???') as contact
from blah blah blah

会给你你想要的值。它会给你它找到的第一个不为 NULL 的值。如果所有可能的表列均为 NULL,您将得到 '???',因为这显然不是 NULL。


另一个例子,假设您有一个会计数据库,其中有单独的借方和贷方价值列 - 不要介意这通常是 一个糟糕设计,你应该有一个带有标志的列 - 让我们假设它是由会计知识比我少的人:-)

因此,如果您想汇总所有交易以确保贷方和借方相等,您可以使用类似以下内容的内容:

select sum (coalesce (credit, -debit, 0)) from txns ...

这样,如果贷方值不为 NULL,它将选择贷方值,否则将选择贷方值它将选择借方值的负值(所有值均为正值)。如果它们都是 NULL,它会给你零。

我听到你问,当它们都是非 NULL 时会发生什么。嗯,这就是为什么它是一个糟糕的设计:-)

When you want the first non-NULL value for a "column" (column in this sense means in your query output, not your table).

One example might be a company's contact person. Say you have three columns:

CompanyRep
CompanySecretary
CompanyOwner

and you want to store all three. But, in a query that lets you know who you should contact, you want to deliver one of those in the order given. But any or all of them may be NULL.

The query:

select coalesce (CompanyRep, CompanySecretary, CompanyOwner, '???') as contact
from blah blah blah

would give you the value you want. It will give you the first value it finds that isn't NULL. If all the possible table columns are NULL, you'll get '???' since that's obviously not NULL.


Another example, let's say you have an accounting database that has separate columns for debit and credit value - never mind that this is usually a bad design and you should have one column with a sign - let's assume it was set up by someone with less accounting knowledge than me :-)

So, if you then wanted to sum up all transactions to ensure credits and debits are equal, you could use something like:

select sum (coalesce (credit, -debit, 0)) from txns ...

That way, it will select the credit value if it's not NULL, otherwise it will select the negation of the debit value (all values are positive). If they're both NULL, it will give you zero.

What happens when they're both non-NULL I hear you ask. Well, that's why it's a bad design :-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文