首页 > 解决方案 > 比较可以为 NULL 的多个列

问题描述

我想比较一组列并决定:

  1. 如果所有非 NULL 的列都相等
  2. 如果任何非 NULL 列不相等
  3. 如果所有列都为 NULL

示例输入和输出:

Inn: 'NO', NULL, 'GB', 'NO', 'NO'
Out: 1) FALSE; 2) TRUE; 3) FALSE
----
Inn: 'NO', NULL, 'NO', 'NO', 'NO'
Out: 1) TRUE; 2) FALSE; 3) FALSE
----
Inn: NULL, NULL, NULL, NULL, NULL
Out: 1) FALSE; 2) FALSE; 3) TRUE

我需要测试的列数很多,所以比较每一个的逻辑语句有点麻烦。

系统:Teradata SQL 数据库

标签: sqllogicteradata

解决方案


您将使用case表达式。也许:

select (case when a is null and b is null and c is null and d is null
             then 'all null'
             when coalesce(a, b, c, d) = coalesce(b, c, d, a) and
                  coalesce(a, b, c, d) = coalesce(c, d, b, a) and
                  coalesce(a, b, c, d) = coalesce(d, a, b, c)
             then 'all non-nulls are equal'
             else 'unequal'
         end);

推荐阅读