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
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:
- How can I optimize this dynamic SQL query in oracle with PL/SQL?Best solution by docs.oracle.com
- How to convert sql query to Hibernate Criteria query?Best solution by Stack Overflow
- How to convert my SQL query to MS Access query?Best solution by Stack Overflow
- How to make only ONE Sql query?Best solution by Stack Overflow
- How to convert SQL query to LINQ query?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
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.