2012-03-16 2 views
0

最後の日付までにデータベースのアイテム名を取得する方法はありません。日付で最後のアイテムを取得する方法(ただし、グループ化しないでください)

私は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 - 'sales'フィールドがグループ化されていないことを確認してください。

+0

どのような日付ですか?それは間違っているようです。 –

+0

この日付が何であれ、私はそれを書き留めます。 – remizpez

答えて

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

thats wayフィールドの販売もグループ化していますか? – remizpez

+0

@remizpez:いいえ、あなたはdate_fieldでグループ化します。私はそれを試してみました。できます。あなたは確認できますか? –

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 
+0

このクエリを試しましたか? –

0

相関サブクエリが...これが基礎になるかもしれどのように大きな知っている小さなセットが、ある場合でも、常に時間のパフォーマンスヒットです。私はちょうどコードあたりの最大の日付を取得するために内部のプリクエリを提案し、その後、そのレコードを取得するために再結合します。 (コード、日付フィールド)のインデックスを確認する

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 
関連する問題