Click here to Skip to main content
15,893,564 members
Please Sign up or sign in to vote.
4.00/5 (4 votes)
See more:
I have a table with ID(auto number),dealerMobile, totalCost and deliveryDate.
Some example data:
ID, dealerMobile, totalCost, deliveryDate
1,  01723325484,  5000,      20-Apr-14
2,  01723325484,  1000,      22-Apr-14
3,  01723325484,  2000,      22-Apr-14
4,  01852136544,  7000,      23-Apr-14

I need to Show only one row based on dealerMobile which is lastly insert. That is If I Search 01723325484 then It show me the third row only. Currently I am applying the below query, It's not working as I want.
SQL
SELECT DISTINCT dealerMobile, totalCost, deliveryDate FROM tbMain WHERE dealerMobile = '" + txtdealerMobile.Text + "' ORDER BY deliveryDate DESC

Please help.
Posted
Updated 23-Apr-14 23:12pm
v2
Comments
ccalma 23-Apr-14 21:31pm    
Are you using MS SQL or MySQL?

You want to use the find-Nth-pattern in SQL

SQL
Select dealerMobile, totalCost, deliveryDate
FROM
(
    select ROW_NUMBER() over (partition by  dealerMobile, totalCost, convert(date, deliveryDate) order by dealerMobile, totalCost, convert(date, deliveryDate)) as rownr,
     dealerMobile, totalCost, deliveryDate
    from tbMain
    where dealerMobile='set the wanted number here' -- <-- your input here
    order by deliverydate desc
) as rows
where rows.rownr = 1
 
Share this answer
 
a more primitive ansi sql way to do the same

SQL
SELECT dealerMobile, totalCost, deliveryDate 
FROM   tbMain
where  dealerMobile = '01723325484'
and    deliveryDate = (Select max(deliveryDate) from tblMain where dealerMobile = '01723325484')
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900