2012-11-06 34 views
0

我想从一个类似于表得到“最上面的”数据:如何获得“最上面的”数据

 
A B C | Id 
1 2 3 | 1 
    4 5 | 1 
    6 | 1

AC =列
1-6值(场未设置为空)
数据是根据它降序排列的ID序列

当我查询我想获得最新的写入的数据,在这个例子中,查询应该给我1,4和6单排:

 
a b c | Id 
1 4 6 | 1 

这是我做过尝试,但后来我得到正确的结果,但在不同的行:

select * from 
(select id, a from dataTable where id=(select max(dt.dataRow) from dataTable dt where dt.id = 1)) a_query 
full outer join 
(select id, b from dataTable where id=(select max(dt.dataRow) from dataTable dt where dt.id = 1)) b_query 
on a_query.id=b_query.id 
full outer join 
(select id, c from dataTable where id=(select max(dt.dataRow) from dataTable dt where dt.id = 1)) c_query 
on nvl(a_query.id, b_query.id)=c_query.id 

优选的Oracle SQL

回答

3

这似乎过于复杂,只得到每个最大列(并且在列为空值的情况下使用COALESCE):

SELECT [id], MAX(COALESCE(a, 0)) AS a, 
    MAX(COALESCE(b, 0)) AS b, 
    MAX(COALESCE(c, 0)) AS c 
FROM dataTable 
GROUP BY [id] 
+0

感谢您的回答,但我仍然得到这个解决方案,我想散布这两行之间的数据过多行。 –

+1

我不确定你的意思是“过多的行”或数据在两行之间传播?用更具体的例子来展示你的模式会很有帮助。 – LittleBobbyTables

+1

如果你有多个“ID”,那么你将有超过1行,但它是有道理的......结果按ID – jazzytomato

0

我可能简化了我的例子, A,B,C中的数据可能是非数字的,不能排序等等。

我发现LAST_VALUE()http://www.oracle.com/technetwork/issue-archive/2006/06-nov/o66asktom-099001.html适应得很好,这里面将返回:

 
A B C | Id 
1 2 3 | 1 
1 4 5 | 1 
1 4 6 | 1 

为我furhter上运行。

然后查询看起来是这样的:

select distinct 
last_value(a ignore nulls) over (order by id) a, 
last_value(b ignore nulls) over (order by id) b, 
last_value(c ignore nulls) over (order by id) c 
from datatable 
where datatable.id IN (select id from datatable where datatable.id = 1)