SQL Server:从2个不同的数据列中选择最大值

时间:2016-07-08 11:44:42

标签: sql sql-server database

说,我有一个结构“table_name”如下:

+-----------+---------+--------------+-------+
| parent_id | file_id | created_date |Records|----- More Columns -----    
+-----------+---------+--------------+-------+
|    42     |   32    |  12/01/2016  |  254  |
|    45     |   33    |  23/04/2016  |  256  |
|    41     |   34    |  12/01/2016  |  213  |
|    42     |   35    |  18/11/2015  |  271  |
|    41     |   36    |  07/07/2016  |  198  |
|    42     |   37    |  23/04/2016  |  186  |
|    45     |   38    |  30/06/2016  |  211  |
|    42     |   39    |  29/05/2016  |  192  |
+-----------+---------+--------------+-------+

我希望查询返回具有最后日期和最后一个file_id的记录,即根据上述数据的结果应返回以下内容:

+-----------+---------+--------------+-------+
| parent_id | file_id | created_date |Records|----- More Columns -----    
+-----------+---------+--------------+-------+
|    42     |   34    |  12/01/2016  |  213  |
|    42     |   35    |  18/11/2015  |  271  |
|    41     |   36    |  07/07/2016  |  198  |
|    45     |   37    |  23/04/2016  |  186  |
|    45     |   38    |  30/06/2016  |  211  |
|    42     |   39    |  29/05/2016  |  192  |
+-----------+---------+--------------+-------+

注意 file_id:32 如何被视为 12/01/2016 的最新file_id条目 34 ,返回 34 ,而不是 32 。类似地,对于 file_ids:33& 37 37 被认为是 37> 34 即可。

现在我正在使用子查询,如下所示:

select max(file_ids) 
    from table_name
      where created_date in (
          select max(created_date) from table_name
);

但是这种方法花了很多时间,比如10k记录大约需要5-6分钟。

3 个答案:

答案 0 :(得分:2)

您可以使用ROW_NUMBER

SELECT file_id, created_date, Records
FROM (
  SELECT file_id, created_date, Records,
         ROW_NUMBER() OVER (PARTITION BY file_id
                            ORDER BY created_date DESC) AS rn
  FROM mytable ) AS t
WHERE t.rn = 1

以上查询选择每file_id

的最新记录

答案 1 :(得分:0)

您也可以将CTE与row_number一起使用。

Declare @Table Table(parent_id int,file_id int,created_date date,Records int)
insert into @Table values 
(42,32,' 2016/01/12 ',254)
,(45,33,'2016/04/23',256)
,(41,34,'2016/01/12',213)
,(42,35,'2015/11/18',271)
,(41,36,'2016/07/07',198)
,(42,37,'2016/04/23',186)
,(45,38,'2016/06/30',211)
,(42,39,'2016/05/29',192)

;WITH t
    AS (
        SELECT parent_id,file_id
            ,created_date
            ,records
            ,row_number() OVER (
                partition by created_date ORDER BY created_date DESC,file_id desc
                ) rn
                from @Table
        )
    SELECT parent_id,file_id
        ,created_date
        ,records
    FROM t
    WHERE rn = 1
    order by file_id

答案 2 :(得分:0)

为了进行比较,您可以尝试运行这样的查询:

select t.*
from t
where t.created_date = (select max(t2.created_date)
                        from t t2
                        where t2.file_id = t.file_id
                       );

对于此版本和row_number()版本,您需要t(file_id, created_date)上的索引。我很好奇你的情况是否会更快。

相关问题