我需要帮助来编写此SQLFiddle的视图。现在数据看起来像:
SERIALNUMBER | INSERTDATE | PARAM1 | PARAM2 | PARAM3 | PARAM4 | PARAM5
3456 | 2017-11-15T12:00:54Z | (null) | (null) | (null) | (null) | 17
3456 | 2017-11-15T12:01:03Z | (null) | (null) | 2 | (null) | (null)
3456 | 2017-11-15T12:07:16Z | (null) | (null) | (null) | 7 | (null)
3456 | 2017-11-15T12:08:08Z | (null) | (null) | (null) | (null) | 19
3456 | 2017-11-15T12:11:32Z | abc | (null) | (null) | (null) | (null)
12 | 2017-11-15T12:00:50Z | (null) | 4 | (null) | (null) | (null)
12 | 2017-11-15T12:01:03Z | (null) | 7 | (null) | (null) | (null)
12 | 2017-11-15T12:07:03Z | (null) | (null) | (null) | te | (null)
我想要接收的结果是由serialnumber分组的数据,如果有更多列没有空数据,那么应选择最新的:
SERIALNUMBER | INSERTDATE | PARAM1 | PARAM2 | PARAM3 | PARAM4 | PARAM5
3456 | 2017-11-15T12:00:54Z | abc | (null) | 2 | 7 | 19
12 | 2017-11-15T12:00:50Z | (null) | 7 | (null) | te | (null)
非常感谢您的帮助
答案 0 :(得分:1)
你没有为此指定确切的规则,所以我猜你想要最大值。如果是这样,这是一个简单的聚合:
select serialnumber, min(InsertDate) as InsertDate,
max(Param1) as Param1,
max(Param2) as Param2,
max(Param3) as Param3,
max(Param4) as Param4,
max(Param5) as Param5
from sample
group by serialnumber
order by InsertDate desc;
Here是SQL小提琴。
我知道,OP确实指定要选择最新的非NULL值。
在那种情况下:
select serialnumber, min(InsertDate) as InsertDate,
max(Param1) keep (dense_rank first order by nvl2(Param1, 1, 2), InsertDate desc) as Param1,
max(Param2) keep (dense_rank first order by nvl2(Param2, 1, 2), InsertDate desc) as Param2,
max(Param3) keep (dense_rank first order by nvl2(Param3, 1, 2), InsertDate desc) as Param3,
max(Param4) keep (dense_rank first order by nvl2(Param4, 1, 2), InsertDate desc) as Param4,
max(Param5) keep (dense_rank first order by nvl2(Param5, 1, 2), InsertDate desc) as Param5
from sample
group by serialnumber
order by InsertDate desc;
以及相应的SQL Fiddle。