具有MAX日期的GROUP BY

时间:2013-05-03 16:27:52

标签: sql group-by having-clause

源表是:

+----------------------------+
| Col A | Col B |    Col C   |
+-------+--------------------+
|  100  |    1  |  1/2/2012  |
|  100  |    2  |  1/2/2012  |
|  100  |    3  |  1/2/2012  |
|  100  |    1  |  5/2/2012  |
|  100  |    2  |  5/2/2012  |
|  100  |    3  |  5/2/2012  |
+-------+-------+------------+

期望的结果:

+-----------------------------+
| Col A | Col B  |    Col C   |
+-------+--------+------------+
|  100  |    1   |   5/2/2012 |
|  100  |    2   |   5/2/2012 |
|  100  |    3   |   5/2/2012 |
+-------+--------+------------+

我们如何使用SQL获取它?

我试过

SELECT * FROM Table A
GROUP BY Col C
HAVING Col C = max(Col C) AND Col A = '100'

但它似乎没有起作用。

3 个答案:

答案 0 :(得分:1)

不是这样的吗?

SELECT ColA, ColB, MAX(ColC) ColC
FROM   TableName
GROUP  BY ColA, ColB

答案 1 :(得分:0)

http://sqlfiddle.com/#!2/7d6f5/6/0

您可以使用 MAX()。请看上面的小提琴

SELECT a, b, MAX(c) FROM a GROUP BY a, b
如果这是你的架构,请加入考虑因素 CREATE TABLE a( a INT, b INT, c DATE );

答案 2 :(得分:0)

我在ms访问中快速完成了这项工作,

SELECT 
 cola, colb, max(colc)
FROM MyTbl
where cola=100
group by cola,colb

enter image description here