根据不同的列返回查询的最大值

时间:2013-08-28 10:06:15

标签: sql oracle

我的表存储了少量文档的各种版本。

-------------------------------
| id   | doc_type |  download | 
-------------------------------
|  1   |   type1  |  file     |
-------------------------------
|  2   |   type2  |  file     |
-------------------------------
|  3   |   type3  |  file     |
-------------------------------
|  4   |   type1  |  file     |
-------------------------------

该表存储相同类型文档的不同版本。我需要构建一个查询,它将返回不同类型的doc_type,其中包含max(id) - 这是该文件的最新版本。 doc_types的数量不受限制且是动态的。我的询问到目前为止:

select max(id) from template_table 
where doc_type in (select distinct doct_type from template_table);

这只返回一个最大的结果。如果我可以通过id ASC对结果进行排序,并将限制结果排序为4,但不能保证它将返回不同的doc_types。此外,DB中的文档类型数量可能会从4个变化,需要计算数量。

select * from template_table 
order by id limit 4;

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用GROUP BY获得所需的结果

select 
   doc_type
,  max(id)                                                AS last_id
,  max(download) KEEP (DENSE_RANK FIRST order by id desc) AS last_download
from template_table
group by doc_type
;

答案 1 :(得分:1)

查询:

SELECT t1.id,
       t1.doc_type,
       t1.download
FROM   template_table t1
 JOIN (SELECT MAX(id) AS id,
              doc_typ
       FROM template_table
       GROUP BY doc_type) t2
  ON t2.doc_type = t1.doc_type
  AND t2.id = t1.id

OR:

SELECT t1.id,
       t1.doc_type,
       t1.download
FROM   template_table t1
WHERE t1.id = (SELECT MAX(t2.id)
               FROM template_table t2
               WHERE t2.doc_type = t1.doc_type)
相关问题