1

我有一个看起来像这样的 SQL 查询:

SELECT 
COALESCE(field1, 0) AS field1, 
COALESCE(field2, 0) AS field2,
COALESCE(field3 - field1 - field2, 0) AS field
FROM ...

However the problem with it is that given say:

field1 = 1
field2 = 0
field3 = 2

显示输出时,字段 3 显示 0,尽管 2 - 1 - 0 = 1。

COALESCE 用于我离开外部加入一些可能导致 Null 值的表。

如果 field3 为空,我也会有任何问题吗?

谢谢

4

2 回答 2

5

独立进行合并:

SELECT COALESCE(field1, 0) AS field1, COALESCE(field2, 0) AS field2,
       COALESCE(field3, 0) - coalesce(field1, 0) - coalesce(field2, 0) AS field
FROM ...

至于你的例子,我怀疑这field2实际上是NULL而不是 0。

于 2013-04-01T13:13:43.750 回答
1

您不能使用在同一级别上给出的别名进行计算。您需要再次重复该函数或仅将主要计算包装在子查询中,

SELECT  field1, field2,
        field3 - (field1 + field2)
FROM
        (
            SELECT  COALESCE(field1, 0) AS field1, 
                    COALESCE(field2, 0) AS field2, 
                    COALESCE(field3, 0) field3
            FROM    TableName
        ) x

原因是因为 SQL 操作的顺序如下:

  • FROM 子句
  • WHERE 子句
  • GROUP BY 子句
  • HAVING 子句
  • 选择子句
  • ORDER BY 子句

ALIASSELECT声明中给出,并且在它们创建的级别上无法访问。

于 2013-04-01T13:15:27.317 回答