Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Composite Key and Group By Issue 3

Status
Not open for further replies.

Foada

Programmer
Feb 4, 2002
1,110
US
Thanks in advance for any insight on this one. I have a composite key that is formed by a customer id and an address sequence number. Each time a address sequence is added to a customer a new Address id is added. If I perform a Max() on the sequence number and group by the customer id I get the correct rows back but I cannot pull the address id as it is not an aggregate or in the group by.

CustId SeqNum AddressId
1000 1 20001
1000 2 23409
1000 3 24706
1000 4 25103

Basically I need to pull the AddressId of 25103 as it is the highest sequence number for customer 1000.

Code:
Select CustId, Max(SeqNum) from tblCust Group By CustId
Returns my CustId of 1000 and SeqNum of 4 but I need the AddressId. Any thoughts?

If you choose to battle wits with the witless be prepared to lose.

[cheers]
 
Try:
Code:
select A.*
from YourTable A
inner join
(    select CustID, Max(SeqNum) as maxSeqNum
    from YourTable
    group by CustID
) B on A.CustID=B.CustID and A.SeqNum=B.maxSeqNum
 
Are your address IDs can be smaller when SeqNum is bigger?
In other words can you have something like this:
[tt]
CustId SeqNum AddressId
1000 1 28912
1000 2 25103
1000 3 24706
1000 4 23409
[/tt]
?

If yes, you could use a derived table to get what you want:
Code:
SELECT YourTable.*
FROM YourTable
INNER JOIN (SELECT CustId, MAX(SeqNum) AS SeqNum
                   FROM YourTable
            GROUP BY CustId) Tbl1
      ON YourTable.CustId = Tbl1.CustId AND
         YourTable.SeqNum = Tbl1.SeqNum


Borislav Borissov
VFP9 SP2, SQL Server 2000/2005.
 
Thanks everyone. I knew it would be something easy, I just could not get it figured the way I needed to.

If you choose to battle wits with the witless be prepared to lose.

[cheers]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top