具有分组的不同行

时间:2013-02-14 10:57:45

标签: sql group-by

我有一张桌子:

id_object | version | document
------------------------------
1         | 1       | 1 
1         | 2       | 2 
2         | 1       | 3 
2         | 2       | 1 
2         | 3       | 2 
1         | 1       | 3 

我想只显示带有版本(max)和文档的对象。我试过以下“

Select Distinct
  id_object ,
  Max(version),
  document
From
  prods
Group By
  id_object, document

我得到了这个结果

1         | 1       | 1
1         | 2       | 2
2         | 1       | 3
2         | 2       | 1
2         | 3       | 2
1         | 1       | 3

正如你所看到的,我正在拿整张桌子。我的问题是,为什么?

3 个答案:

答案 0 :(得分:2)

由于您按id_object document进行分组,因此无法获得所需的结果。这是因为document对于每个version都不同。

select x.id_object, 
       x.maxversion as version,
       p.document
from 
(
   Select id_object, Max(version) as maxversion
   From prods
   Group By id_object
) x
inner join prods p on p.id_object = x.id_object 
                   and p.version = x.maxversion

首先,您必须使用id_object选择max(version)。这可以与实际数据结合以获得正确的document

您必须这样做,因为您不能选择不在group by子句中的列,除非您对它们使用聚合函数(例如max())。

(MySQL可以选择非聚合列,但请避免使用,因为结果并不总是清晰甚至可预测)

答案 1 :(得分:0)

select prods.id_object, version, document
from prods inner join
(select id_object, max(version) as ver
from prods
group by id_object) tmp on prods.id_object = tmp.id_object and prods.version = tmp.ver

答案 2 :(得分:0)

查询:

<强> SQLFIDDLEExample

SELECT p.id_object, 
       p.version, 
       p.document
FROM prods p
WHERE p.version = (SELECT Max(version)
                   FROM prods
                   WHERE id_object = p.id_object)

结果:

| ID_OBJECT | VERSION | DOCUMENT |
----------------------------------
|         1 |       2 |        2 |
|         2 |       3 |        2 |