sql – 选择具有少量唯一列的记录,同时选择非空值优先于另一列

我想通过获取field1和field2特有的记录来查询表,同时选择具有field4的行,使其具有某些值而不是优先级为null.

例如在原始表中

field1  field2  field3  field4
  1       B       A     (null) 
  1       B       A       2   
  2       C       A       3   
  2       D       A     (null)
  3       D       F       3   
  2       C       A       3   

我希望从输出查询得到的是:

field1  field2  field3  field4
  1       B       A       2   
  2       C       A       3   
  2       D       A     (null)
  3       D       F       3   

是否有任何有效的SQL表加入技术/过滤方法来实现这一目标?谢谢

P / S – 为了避免混淆,仅具有field1和field2的区别的目的是因为field3可以具有不同的值,所选择的行将基于field4在优先级中不为null的那些行

例如

field1  field2  field3  field4
  1       B       A     (null)   
  1       B       C       2       <- this will be the chosen one
最佳答案
试试这个:

你需要按前3个字段进行分组并获取filed4的MAX()

select "field1","field2","field3",max("field4")
from Table1
group by "field1","field2","field3"
order by "field1"

SQL fiddle demo

编辑:

如果你只想将field1和field2作为分组的一部分,那么试试这个:

select "field1","field2","field3","field4"
from(
select "field1","field2","field3","field4",
        row_number() 
        over(partition by "field1","field2" order by "field4" desc) as rn
from Table1)A
where A.rn=1

SQL Fiddle Demo 2

转载注明原文:sql – 选择具有少量唯一列的记录,同时选择非空值优先于另一列 - 代码日志