如何获取最大值并使用group by子句

时间:2017-07-22 12:47:09

标签: sql

我有这样的查询:

select transactions_id,
    time_stamp,
    clock
from times
group by transactions_id
having sum(distinct type) = 1

现在,我希望获得max值,具体取决于id

我使用了以下查询但未使用过:

select max(id),
    transactions_id,
    time_stamp,
    clock
from times
group by transactions_id
having sum(distinct type) = 1

select transactions_id,
    time_stamp,
    clock
from times
group by transactions_id
having sum(distinct type) = 1
    and max(id)

例如:

我有三个条件:

  1. type必须为1
  2. group by transactions_id
  3. max id
  4. enter image description here

2 个答案:

答案 0 :(得分:1)

您可以在一个查询中找到聚合,并将其结果与表结合以获取相关行。

select *
from times t1
join (
    select transactions_id,
        max(id) as id
    from times
    where type = 1
    group by transactions_id
    ) t2 using (transactions_id, id);

答案 1 :(得分:0)

如果我理解正确,您可以使用ANSI标准row_number()函数:

select t.*
from (select t.*,
             row_number() over (partition by transactions_id order by id desc) as seqnum
      from times t
     ) t
where seqnum = 1;

我不确定having sum(distinct type) = 1是什么。这个问题没有在问题中解释。