用于检索具有相同名称且最近创建一个

时间:2017-01-10 10:01:58

标签: mysql sql database

表名税。

id     | name            | value  | created_at           | updated_at 
:----: | :----:          | :----: | :-------:            | :----:
1      | VAT             | 9.56   | 2017-01-10 09:25:40  | 2017-01-10 09:25:40
:----- | :-----          | :----: | :-----               | :----
2      | Service Tax     | 10.56  | 2017-01-10 10:25:40  | 2017-01-10 10:25:40
:----- | :-----          | :----: | :-----               | :----
3      | Service charge  | 11.56  | 2017-01-10 11:25:40  | 2017-01-10 11:25:40
:----- | :-----          | :----: | :-----               | :----
4      | vat             | 2.56   | 2017-01-12 08:25:40  | 2017-01-12 08:25:40
:----- | :-----          | :----: | :-----               | :----
5      | service charge  | 21.56  | 2017-01-13 09:25:40  | 2017-01-13 09:25:40
:----- | :-----          | :----: | :-----               | :----
6      |  Service tax    | 21.56  | 2017-01-21 09:25:40  | 2017-01-21 09:25:40
:----- | :-----          | :----: | :-----               | :----
7      | Vat             | 12.56  | 2017-01-23 09:25:40  | 2017-01-23 09:25:40
:----- | :-----          | :----: | :-----               | :----
8      | Serivce Charge  | 16.56  | 2017-01-23 10:25:40  | 2017-01-23 10:25:40
:----- | :-----          | :----: | :-----               | :----

我必须检索每种税的最新创建税。

预期输出:

    id    | name        | value  | created_at           | updated_at 
   :----: | :----:      | :----: | :-------:            | :----:
    6     |  Service tax| 21.56  | 2017-01-21 09:25:40  | 2017-01-21 09:25:40
   :----- | :-----          | :----: | :-----               | :----
    7     | Vat             | 12.56  | 2017-01-23 09:25:40  | 2017-01-23 09:25:40
   :----- | :-----          | :----: | :-----               | :----
    8     | Serivce Charge  | 16.56  | 2017-01-23 10:25:40  | 2017-01-23 10:25:40

请帮帮我,谢谢你。

2 个答案:

答案 0 :(得分:2)

SQL服务器和Oracle

with taxes as
(
select id, name, value, row_number() over(partition by name order by created_at desc) as tax_ord
from table1
)
select *
from taxes
where tax_ord = 1

的MySQL

select a2.*
from 
(select name, max(created_at) as Max_Create
from table1
group by name) a1
inner join table1 a2
on a1.name = a2.name
and a1.Max_Create = a2.created_at

答案 1 :(得分:0)

以下查询至少应该适用于MySQL:

select * from tax t
where (t.name, t.created_at) IN 
  (select t2.name, max(t2.created_at) from tax t2
   group by t2.name)