Oracle SQL - 如果它是唯一的值,则保留null值,否则避免使用null值

时间:2017-06-01 09:35:17

标签: sql oracle

我有这张桌子:

Table1
-----------------
ID         VAL       
-----------------
1          A
1          B
1          null
2          null
3          B
3          null
4          B
4          C
5          null   

我想得到这个结果:

如果唯一值为null则返回null,否则返回非null    值

Table1
-----------------
ID         VAL       
-----------------
1          A
1          B
2          null
3          B
4          B
4          C  
5          null

我尝试使用Over Partition By with Case但是我的语句变得过于复杂,有几个子查询,如果认为应该有一个简单的方法来执行此操作。

2 个答案:

答案 0 :(得分:3)

COUNT( value ) OVER ( PARTITION BY id )分析函数会计算value不是NULL的行idSELECT id, value FROM ( SELECT t.*, COUNT( value ) OVER ( PARTITION BY id ) AS num_values FROM yourtable t ) WHERE value IS NOT NULL OR num_values = 0; 。您可以使用它来过滤这样的行:

NULL
  

如果唯一值为null则返回null,否则返回非空值

如果您想确保仅在id只有一行时才会返回SELECT id, value FROM ( SELECT t.*, COUNT( * ) OVER ( PARTITION BY id ) AS num_rows FROM yourtable t ) WHERE value IS NOT NULL OR num_rows = 1;

#include <iostream>

#include <boost/interprocess/managed_shared_memory.hpp>


int main(int argc, char const* argv[])
{
    boost::interprocess::shared_memory_object::remove("High");
    try {
        boost::interprocess::managed_shared_memory managed_shm(
                boost::interprocess::create_only,
               "High",
                256);
        std::cout << "success" << std::endl;
    }
    catch (boost::interprocess::interprocess_exception &ex) {
        std::cout << ex.what() << std::endl;
    }
    return 0;
}

答案 1 :(得分:0)

试试这个:

SELECT *
FROM yourtable t1
WHERE val IS NOT NULL OR
NOT EXISTS (SELECT 'VALUED'
    FROM yourtable t2
    WHERE t2.id = t1.id
    AND t2.val IS NOT NULL)