通过列

时间:2019-06-06 14:09:33

标签: mysql sql

我有一个带有时区的表,看起来像下面的示例:

CREATE TABLE timezones
(`CountryCode` varchar(2),
 `ZoneName` varchar(35),
 `Offset` int not null,
 `Dst` char(1),
 `TimeStart` decimal(11,0) not null);

INSERT INTO 
timezones (`CountryCode`, `ZoneName`, `Offset`, `Dst`, `TimeStart`)

VALUES
('VA', 'Europe/Vatican', 7200, '1', 1521939600),
('VA', 'Europe/Vatican', 3600, '0', 1540688400),
('VA', 'Europe/Vatican', 7200, '1', 1553994000),

('UA', 'Europe/Zaporozhye', 10800, '1', 1521939600),
('UA', 'Europe/Zaporozhye', 7200, '0', 1540688400),
('UA', 'Europe/Zaporozhye', 10800, '1', 1553994000),

('TR', 'Europe/Istanbul', 7200, '0', 1446944400),
('TR', 'Europe/Istanbul', 7200, '1', 1459040400),
('TR', 'Europe/Istanbul', 10800, '0', 1473195600);
+-------------+-------------------+--------+------+------------+
| CountryCode | ZoneName          | Offset | Dst  | TimeStart  |
+-------------+-------------------+--------+------+------------+
| VA          | Europe/Vatican    |   7200 | 1    | 1521939600 |
| VA          | Europe/Vatican    |   3600 | 0    | 1540688400 |
| VA          | Europe/Vatican    |   7200 | 1    | 1553994000 |
| UA          | Europe/Zaporozhye |  10800 | 1    | 1521939600 |
| UA          | Europe/Zaporozhye |   7200 | 0    | 1540688400 |
| UA          | Europe/Zaporozhye |  10800 | 1    | 1553994000 |
| TR          | Europe/Istanbul   |   7200 | 0    | 1446944400 |
| TR          | Europe/Istanbul   |   7200 | 1    | 1459040400 |
| TR          | Europe/Istanbul   |  10800 | 0    | 1473195600 |
+-------------+-------------------+--------+------+------------+

我需要选择具有唯一ZoneName字段的行,这些行在TimeStart列中具有最大值。

因此对于上表,我希望得到以下结果:

+-------------+-------------------+--------+------+------------+
| CountryCode | ZoneName          | Offset | Dst  | TimeStart  |
+-------------+-------------------+--------+------+------------+
| VA          | Europe/Vatican    |   7200 | 1    | 1553994000 |
| UA          | Europe/Zaporozhye |  10800 | 1    | 1553994000 |
| TR          | Europe/Istanbul   |  10800 | 0    | 1473195600 |
+-------------+-------------------+--------+------+------------+

2 个答案:

答案 0 :(得分:0)

这是一个过滤操作。您可以使用相关的子查询:

select t.*
from t
where t.timestart = (select max(t2.timestart) from t t2 where t2.ZoneName = t.ZoneName);

答案 1 :(得分:0)

您可以使用子查询获取最长时间并加入

select * from timezones t1
inner join (
    select  CountryCode, ZoneName , max(1553994000) max_t
    from timezones 
) t2 on t1.CountryCode = t2.CountryCode
    and t1.ZoneName = t2.ZoneName 
      and t1.TimeStart = t2.max_t
相关问题