我的表格如下所示
CREATE TABLE IF NOT EXISTS `testtab` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`auto_num` varchar(100) NOT NULL,
`seal_num` varchar(100) NOT NULL,
`arr_date` date NOT NULL,
`unload_date` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
INSERT INTO `testtab` (`id`, `name`, `auto_num`, `seal_num`, `arr_date`, `unload_date`) VALUES
(1, 'contain1', 'AT0000004815', 'CN44178', '2014-11-28', '2014-11-28'),
(2, 'contain1', 'AT0000004815', 'CN44178', '2014-12-28', '2014-12-28'),
(3, 'contain1', 'AT0000004815', 'CN44178', '2014-12-28', '2014-11-28'),
(4, 'contain1', 'AT0000004815', 'CN44178', '2014-11-28', '2014-12-28'),
(5, 'contain2', 'AT0000000227', 'CG11818', '2015-09-12', '2015-08-30'),
(6, 'contain2', 'AT0000000227', 'CG11818', '2015-08-30', '2015-08-30'),
(7, 'contain2', 'AT0000000227', 'CG11818', '2015-09-12', '2015-09-14'),
(8, 'contain2', 'AT0000000227', 'CG11818', '2015-08-30', '2015-09-14'),
(9, 'contain3', 'AT0000005297', 'FG1005G', '2015-01-25', '2015-01-27'),
(10, 'contain3', 'AT0000005297', 'FG1005G', '2015-01-25', '2014-12-27');
我需要输出结果,如下所示 Mysql查询结果必须包含arr_date,unload_date中的最大日期值 按字段分组:name,auto_num,seal_num
id name auto_num seal_num arr_date unload_date
2 contain1 AT0000004815 CN44178 2014-12-28 2014-12-28
7 contain2 AT0000000227 CG11818 2015-09-12 2015-09-14
9 contain3 AT0000005297 FG1005G 2015-01-25 2015-01-27
我想在这里使用什么查询,请帮助我,
答案 0 :(得分:1)
你可以这样做:
SELECT * FROM `testtab` t
WHERE (t.arr_date,t.unload_date) in(select max(arr_date),max(unload_date)
from `testtab` s where s.name = t.name
and s.auto_num = t.auto_num and s.seal_num = t.seal_num)
这将为每个组合(name,auto_num,seal_num)选择max arr_date和unload_date,然后检查行中两列是否相等,选择它。
答案 1 :(得分:0)
我猜您正在为arr_date
,unload_date
和name
的每个不同组合寻找最新的auto_num
和seal_num
。但是你还没有解释你的表格内容,所以我猜错了。
此查询为您提供。它不给出行ID,因为最新的arr_date
和最新的unload_date
可能来自不同的行。
select name, auto_num, seal_num,
MAX(arr_date) arr_date, MAX(unload_date) unload_date
from testtab
group by name, auto_num, seal_num
<强> Results 强>:
| name | auto_num | seal_num | arr_date | unload_date |
|----------|--------------|----------|-------------------|-------------------|
| contain1 | AT0000004815 | CN44178 | December, 28 2014| December, 28 2014|
| contain2 | AT0000000227 | CG11818 | September, 12 2015| September, 14 2015|
| contain3 | AT0000005297 | FG1005G | January, 25 2015| January, 27 2015|