获取每行具有最大值的组

时间:2017-10-04 13:31:02

标签: sql sql-server-2012

我得到了下表:

col1 | col2 | col3 | col4 | timestamp
-------------------------------------
  1  | ...  | ...  | ...  | 12:01
  1  | ...  | ...  | ...  | 12:40
  2  | ...  | ...  | ...  | 11:00
  2  | ...  | ...  | ...  | 13:00
  2  | ...  | ...  | ...  | 12:22
  3  | ...  | ...  | ...  | 16:00
  3  | ...  | ...  | ...  | 12:10

我希望每行都有按行1分组的最大时间戳值。这意味着结果必须如下:

col1 | col2 | col3 | col4 | timestamp
-------------------------------------
  1  | ...  | ...  | ...  | 12:40
  2  | ...  | ...  | ...  | 13:00
  3  | ...  | ...  | ...  | 16:00

我的以下查询有效:

SELECT col1, MAX(timestamp)
FROM table
GROUP BY col1

但不是这样:

SELECT col1, col2, col3, col4, MAX(timestamp)
FROM table
GROUP BY col1

2 个答案:

答案 0 :(得分:2)

根据 row number 列的分区以及 col1的降序提供 timestamp 专栏。然后选择 rn = 1 的行。

<强>查询

;with cte as(
    select [rn] = row_number() over(
        partition by [col1]
        order by [timestamp] desc
    ), *
    from your_table_name
)
select [col1], [col2], [col3], [col4], [timestamp]
from cte
where [rn] = 1;

答案 1 :(得分:1)

好吧,您可以按照它的工作方式获取最大时间戳,然后加入初始表以获取其他值,如下所示:

select t.col1, t.col2, t.col3, t.col4, tmax.max_ts
from table t join   (
                            select col1, max(timestamp) max_ts
                            from table
                            group by col1
                         ) tmax on tmax.col1 = t.col1 and tmax.max_ts = t.timestamp