Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
hello freinds
i have a probulm in sqlserver query.
i have a table having records like this.

Bill no     userid      amt          billenterdate
1            1         100              2012-05-24 05:29:35.223
2             2          200               2012-03-24 05:29:35.223
3             2          200            2012-01-24 05:29:35.223
4              1           2000             2012-05-4 05:29:35.223

--------------------------------------------------------------------

now i want to select a single record for each userid where billenter date is maximum from that users all records.


result should be:-

1       1         100    2012-05-24 05:29:35.223
2       2          200   2012-03-24 05:29:35.223



please help me how to achieve this result
Posted
Updated 24-May-12 0:44am
v3

SQL
Select BillNo,userid, amt, billenterdate
From
(
    SELECT
        BillNo,userid, amt, billenterdate, Rank() over (Partition BY userid order by Cast(Convert(varchar,billenterdate,106) as datetime) Desc) as [Rank]
    FROM
    TblBillDetails
) A
where [Rank]=1
 
Share this answer
 
Comments
Maciej Los 24-May-12 8:42am    
Great answer, my 5!
Another solution using subquery and inner join

SQL
select * from Table_1 a 
inner join (select max(billenterdate) as billenterdate,userid from Table_1 group by userid) as userinfoTable 
on a.billenterdate = userinfoTable.billenterdate and a.userid = userinfoTable.userid order by billno
 
Share this answer
 
Or a correlated EXISTS structure
SQL
SELECT *
FROM   YourTable t1
WHERE  NOT EXISTS (SELECT 1
                   FROM   YourTable t2
                   WHERE  t2.UserId        = t1.UserId
                   AND    t2.BillEnterDate > t1.BillEnterDate)
 
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