0

我有一个包含三个字段的表,一个 ID、一个日期(字符串)和一个 INT。像这样。

+---------------------------
+BH|2012-09-01|56789
+BH|2011-09-01|56765
+BH|2010-08-01|67866
+CH|2012-09-01|58789
+CH|2011-09-01|56795
+CH|2010-08-01|67866
+DH|2012-09-01|52789
+DH|2011-09-01|56665
+DH|2010-08-01|67866

我基本上需要为每个 ID,我只需要返回具有最高日期字符串的行。从这个例子中,我的结果需要是。

+---------------------------
+BH|2012-09-01|56789
+CH|2012-09-01|58789
+DH|2012-09-01|52789
4

3 回答 3

1
SELECT t.id, t.date_column, t.int_column
    FROM YourTable t
        INNER JOIN (SELECT id, MAX(date_column) AS MaxDate
                        FROM YourTable
                        GROUP BY id) q
            ON t.id = q.id
                AND t.date_column = q.MaxDate
于 2012-04-27T21:10:01.683 回答
0

假设以下结构:

CREATE TABLE  `stackoverflow`.`table_10357817` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Date` datetime NOT NULL,
  `Number` int(11) NOT NULL,
  `Code` char(2) NOT NULL,
  PRIMARY KEY (`Id`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=latin1

以下查询将使用预期的结果:

SELECT Code, Date, Number
FROM table_10357817
GROUP BY Code
HAVING Date = MAX(Date)

GROUP BY 强制每个代码(您称之为 id)生成一个结果,而 HAVING 子句仅返回与每个代码/id 的最大日期匹配的数据。

更新

使用了以下数据脚本:

INSERT INTO table_10357817 
    (Code, Date, Number)
VALUES 
    ('BH', '2012-09-01', 56789),
    ('BH', '2011-09-01', 56765),
    ('BH', '2010-08-01', 67866),
    ('CH', '2012-09-01', 58789),
    ('CH', '2011-09-01', 56795),
    ('CH', '2010-08-01', 67866),
    ('DH', '2012-09-01', 52789),
    ('DH', '2011-09-01', 56665),
    ('DH', '2010-08-01', 67866)
于 2012-04-27T21:30:08.927 回答
0
SELECT id, date, int
FROM (  SELECT id, date, int
        FROM table_name
        ORDER BY date DESC) AS h
GROUP BY id

将 table_name 和列替换为正确的。

于 2012-04-27T21:07:33.260 回答