SQL 根据一个字段的值在两个字段之间进行选择
我正在使用 PostgreSQL 数据库,在表示一些测量值的表中,我有两列:测量值和插值值。在第一个中,我有观察(测量),在第二个中,我有取决于附近值的插值。每个具有原始值的记录也有一个插值。但是,有很多记录没有“原始”观察值(NULL),因此值被插值并存储在第二列中。所以基本上数据库中只有两种情况:
Value Value
NULL Value
当然,最好使用第一列中的值(如果可用),因此我需要构建一个查询来从第一列中选择数据,如果不可用(NULL ),然后数据库返回相关记录的第二列的值。我不知道如何构建 SQL 查询。
请帮忙。谢谢。
I am using a PostgreSQL database, and in a table representing some measurements I've two columns: measurement, and interpolated. In the first I've the observation (measurement), and in the second the interpolated value depending on nearby values. Every record with an original value has also an interpolated value. However, there are a lot of records without "original" observations (NULL), hence the values are interpolated and stored in the second column. So basically there are just two cases in the database:
Value Value
NULL Value
Of course, it is preferable to use the value from the first column if available, hence I need to build a query to select the data from the first column, and if not available (NULL), then the database returns the value from the second column for the record in question. I have no idea how to build the SQL query.
Please help. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
合并
:
如果它不为
NULL
,则返回first_value
,否则返回second_value
。You can use
Coalesce
:This would return
first_value
if it is notNULL
,second_value
otherwise.彼得成功了。但为了完整起见(您的问题的标题比您的特定问题更笼统),这里是几个 条件表达式 可用于 Postgresql(以及其他几个数据库):
CASE、COALESCE、NULLIF ,最大,最小
。第一个是最一般的。Peter nailed it. But for the sake of completeness (the title of your question is more general than your particular issue), here goes the docs for the several conditional expressions available in Postgresql (and in several other databases) :
CASE, COALESCE, NULLIF, GREATEST, LEAST
. The first one is the most general.