Sql 第一行选择不同的

Sql 第一行选择不同的,sql,postgresql,Sql,Postgresql,我在SQL查询方面遇到了一些问题。我有一个表来存储日期的结果。我想选择所有具有最长(最近)日期的不同结果。我可以通过以下方式实现这一点: select distinct(r.data), max(c.committed_at) as timestamp from results r inner join commits c on (r.commit_id=c.id) where r.repository_id=65 AND data_type='data_model' group b

我在SQL查询方面遇到了一些问题。我有一个表来存储日期的结果。我想选择所有具有最长(最近)日期的不同结果。我可以通过以下方式实现这一点:

select distinct(r.data), max(c.committed_at) as timestamp
from results r
     inner join commits c on (r.commit_id=c.id) 
where r.repository_id=65 AND data_type='data_model'
group by data
order by timestamp DESC
这是好的,所有的工作

但是,我希望能够选择第三列,即散列。此哈希对于每个结果行都是唯一的

但是当我将它添加到SELECT子句中时,我当然也必须将它添加到我的组中

select distinct(r.data), max(c.committed_at) as timestamp, c.hash
from results r
     inner join commits c on (r.commit_id=c.id) 
where r.repository_id=65 AND data_type='data_model'
group by data, c.hash
order by timestamp DESC
这就抛出了这个问题。当然,我不再得到明显的结果

我在
散列
上尝试了聚合函数:

select distinct(r.data), max(c.long_hash), max(c.committed_at) as timestamp
from results r
    inner join commits c on (r.commit_id=c.id) 
where r.repository_id=65 AND data_type='data_model'
group by data
order by timestamp DESC
但是我没有得到最大时间,我得到了最大散列

我觉得我只是想说“找到具有最大时间戳的不同结果,然后在结果中包含哈希”,但我不知道如何

干杯, 本

编辑:我尝试使用
DISTINCT ON
进行此操作:

select distinct on (data) data, c.committed_at as committed_at, c.long_hash
from results r 
    inner join commits c on (r.commit_id=c.id) 
where r.repository_id=65 AND data_type='complexity'
order by data, c.committed_at DESC
但这需要在
data
上进行排序,这同样会抛出我的结果的排序

编辑2:

执行此查询将得到以下结果:

“{”status:“supported”,“per_method:“10.2”,“total:“815.2”,“data…”,'2017-01-04 13:25:51','4a44bccca804c28c6a5e61b36b5ebcb716d4c11f'
“{”状态“:”支持“,”per_方法“:”8.8“,”总计“:”649.3“,”数据“:”,”2017-01-02 23:35:11“,”d747e657a81c5c6da4262a5298c3071082b2af41“
“{”状态“:”支持“,”per_方法“:”10.7“,”总计“:”944.3“,”数据“:”,”2017-01-08 17:28:57“,”ff4be5fa6dc88237e7855ed1b534baee69aa8800“
如您所见,
数据
列是有序的(根据JSONB列规则),而
时间戳
列则不是有序的(从1月4日到1月2日,再到1月8日)。

尝试以下方法:

with cte as
(
select r.data,c.committed_at, c.hash,timestamp, 
ROW_NUMBER() over (Partition by r.data order by c.committed_at DESC) as ranking
from results r
     inner join commits c on (r.commit_id=c.id) 
where r.repository_id=65 AND data_type='data_model' 
)
Select data,committed_at, hash 
from cte where ranking=1 order by timestamp DESC

您不需要使用
上选择distinct on
分组。您只需按
调整
顺序即可。因此:

select distinct on (r.data) r.*, c.*
from results r inner join
     commits c
     on r.commit_id = c.id 
where r.repository_id = 65 and
      data_type = 'data_model'
order by r.data, c.committed_at desc;
distinct on
完成您想做的所有工作。它为
列表中的每个值组合返回一行。该行是order by指定的第一行


我想这就是你想要的
distinct(r.data)
,因为
distinct
本身不是一个函数,你不会用括号括起来。

正在使用哪些数据库管理系统,比如Oracle、MySQL、Postgres、SQL Server……哎呀!博士后。我也尝试过使用DISTINCT,但这需要按数据列排序,这也不是我想要的…
DISTINCT
不是一个函数
distinct(a),b
distinct a,(b)
distinct a,b
完全相同。它始终应用于选择列表中的所有列。我只是想避免按那个专栏排序。。。有没有办法做到这一点?如果你加一些提琴,可能会更好well@ArijitMukherjee未提供示例数据,因此无法添加。这看起来很有希望,而且实际有效!谢谢,将此标记为正确答案。