我在使用 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 子句中时,我当然也必须将它添加到我的 GROUP BY 中。
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
这会抛出查询。我不再得到明显的结果(当然)。
我在 hash
上尝试了聚合函数:
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
进行 ORDER BY,这又会打乱我的结果顺序...
编辑 2:
执行此查询会得到以下结果:
'{"status":"supported","per_method":"10.2","total":"815.2","data"<snip>...}','2017-01-04 13:25:51','4a44bccca804c28c6a5e61b36b5ebcb716d4c11f'
'{"status":"supported","per_method":"8.8","total":"649.3","data":<snip>...}','2017-01-02 23:35:11','d747e657a81c5c6da4262a5298c3071082b2af41'
'{"status":"supported","per_method":"10.7","total":"944.3","data":<snip>...}','2017-01-08 17:28:57','ff4be5fa6dc88237e7855ed1b534baee69aa8800'
如您所见,data
列是有序的(根据 JSONB 列规则),而 timestamp
列不是(从 1 月 4 日到1 月 2 日至 1 月 8 日)。
最佳答案
你不需要group by
与 select distinct on
.您只需调整 order by
.所以:
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
做你想做的所有工作。它为 distinct on
中的每个值组合返回一行列表。该行是 order by 指定的第一行。
我认为这就是您对 distinct(r.data)
的意图,因为 distinct
它本身不是一个函数,您不会在它上面使用括号。
关于sql - SELECT DISTINCT 的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51054982/