How to write a complex query with doctrine?

Help me write an SQL query for the following?

  • I have a table which has 4 fields : Godown, Item, Qty and Date The primary key is a combination of (Godown, Item, Date) Assume it has the following data :- Godown Item Qty Date AM KCDC 10 12/5/2010 AM KCDC 15 13/5/2010 AM KSAI 5 12/5/2010 KB KSAI 10 11/5/2010 KB KSAI 15 12/5/2010 SB KSAI 20 13/5/2010 The SQL Query i'm looking for should give me the row with the LATEST Qty for each pair of (Godown,Item) i.e. for MaxDate only Example : query should return following as output AM KCDC 15 13/5/2010 AM KSAI 5 12/5/2010 KB KSAI 15 12/5/2010 SB KSAI 20 13/5/2010 As you can see the first record in the original table is not shown as a newer (latest) record exists.

  • Answer:

    SELECT a.* FROM someTable a, (SELECT Godown, Item, MAX(Date) AS Date FROM someTable GROUP BY Godown, Item) b WHERE a.Gowdown = b.Godown AND a.Item = b.Item AND a.Date = b.Date

Jatin at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

SELECT *,MAX(Date) as max_date FROM TABLE_NAME

select * from tab_name t1 join (select Godown, Item, max(Date) mDate from tab_name group by Godown, Item) t2 on t1.Godown = t2.Godown and t1.Item = t2.Item and Date = mDate

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.