Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: SQL-server-2005
Hi....I have Find last record in each ID records.
 
ID	SID	Amount	Pay	Due
1	1	10000	2000	8000
2	2	10000	3000	7000
3	3	10000	5000	5000
4	1	10000	3000	5000
5	2	10000	5000	2000
6	3	10000	2000	3000
7	1	10000	1000	4000
8	2	10000	1000	1000

 
For Eg:Out Put.
SID Due
1   4000
2   1000
3   3000
Posted 18-Mar-13 3:06am
Achal Oza1.4K
Edited 18-Mar-13 3:16am
Maciej Los151.7K
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Try this:
SELECT t1.SID, t1.DUE
FROM YourTable AS t1 RIGHT JOIN (
    SELECT SID, MAX(ID) AS ID
    FROM YourTable
    GROUP BY SID) AS t2 ON t1.SID =t2.SID AND t1.ID=t2.ID
ORDER BY t1.SID
  Permalink  
v3
Comments
Achal Oza at 18-Mar-13 8:32am
   
Ambiguous column name 'SID'.
Maciej Los at 18-Mar-13 8:34am
   
see updated solution ;)
CHill60 at 18-Mar-13 10:40am
   
My 5 to get this (correct) solution above the earlier truly awful one
Maciej Los at 18-Mar-13 10:41am
   
Thank you, Chill60 ;)
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hi,
 
Check the following script
 
DECLARE @AmtDtls TABLE(ID INT,SID INT, Amount NUMERIC(9,0), Pay NUMERIC(9,0), Due NUMERIC(9,0))
INSERT INTO @AmtDtls (ID, SID, Amount, Pay , Due )
SELECT 1, 1, 10000, 2000, 8000
UNION ALL
SELECT 2, 2, 10000, 3000, 7000
UNION ALL 
SELECT 3, 3, 10000, 5000, 5000
UNION ALL
SELECT 4, 1, 10000, 3000, 5000
UNION ALL
SELECT 5, 2, 10000, 5000, 2000
UNION ALL
SELECT 6, 3, 10000, 2000, 3000
UNION ALL
SELECT 7, 1, 10000, 1000, 4000
UNION ALL
SELECT 8, 2, 10000, 1000, 1000
 
SELECT A.SID, A.Due 
FROM @AmtDtls A
INNER JOIN (SELECT MAX(ID) ID, SID FROM @AmtDtls GROUP BY SID) T ON T.ID=A.ID
ORDER BY A.SID
Regards,
GVPrabu
  Permalink  
Comments
Achal Oza at 18-Mar-13 8:25am
   
But I have around 56000 record..
So many time wait for perfact Output..
gvprabu at 18-Mar-13 8:29am
   
You have Index for SID and ID Column for that table?

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

  Print Answers RSS
0 OriginalGriff 7,903
1 Sergey Alexandrovich Kryukov 7,192
2 DamithSL 5,604
3 Manas Bhardwaj 4,986
4 Maciej Los 4,820


Advertise | Privacy | Mobile
Web01 | 2.8.1411023.1 | Last Updated 18 Mar 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100