如何按日期获取最后一项(但没有分组)

时间:2012-03-16 09:23:09

标签: mysql

我不知道如何在上次约会时在我的数据库中获取项目名称。

我在DB中:

id  | code | date_field | name  |  sales |
----+------+------------+-------+--------+
1   |  AA1 | 20-10-2012 | asd   |    4
2   |  AA1 | 20-13-2012 | asd   |    10
3   |  AA1 | 20-17-2012 | asd   |    20
4   |  AA2 | 20-20-2012 | zad   |    13
5   |  AA3 | 20-10-2012 | 3ad   |    4 
6   |  AA4 | 20-15-2012 | bez   |    0
7   |  AA4 | 20-17-2012 | bez   |    1
8   |  AA4 | 20-22-2012 | bez   |    0
9   |  AA5 | 20-21-2012 | sda2  |    3
10  |  AA6 | 20-21-2012 | goo   |    5

我需要得到:

id  | code | date_field | name  | sales |
----+------+------------+-------+-------+
3   |  AA1 | 20-17-2012 | asd   |   20
4   |  AA2 | 20-20-2012 | zad   |   13
5   |  AA3 | 20-10-2012 | 3ad   |   4
8   |  AA4 | 20-22-2012 | bez   |   1
9   |  AA5 | 20-21-2012 | sda2  |   3
10  |  AA6 | 20-21-2012 | goo   |   5

我想我应该使用类似的东西:

SELECT MAX(date) as date_field, code, name from table
group by date_field

.. 我是对的?

P.S - 看看“销售”字段没有分组!

3 个答案:

答案 0 :(得分:0)

SELECT date_field as `date`, code, name, sales
from my_table
group by date_field
order by sales desc

答案 1 :(得分:0)

试试这段代码: -

SELECT a.date as date_field, a.code, a.name from table a
where a.id = (select max(b.id) from table b where b.name = a.name)
and a.date = (select max(c.date) from table c where c.name = a.name)
order by sales desc

答案 2 :(得分:0)

相关的子查询总是时间性能命中..即使这是一个小集合,谁知道基础可能变得多大。我建议内部预查询只获取每个代码的最大日期,然后重新加入以获取该记录。确保索引(code,date_field)

select
      yt2.*
   from
      ( select yt.code,
               max( yt.date_field ) maxbyDate
           from
              YourTable yt
           group by
              yt.code ) PreQuery
      JOIN YourTable yt2
         on PreQuery.Code = yt2.code
        AND PreQuery.maxByDate = yt2.date_field