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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pull first record for each

Status
Not open for further replies.

simian336

Programmer
Sep 16, 2009
723
US
I have a list ordered by Account then branch.

Account Branch
0000000605
0000000605 1
0000000605 10
0000000606
0000000606 3
0000000607 2
0000000608 2
0000000608 5


How would I pull only the first account wheather or not the branch is blank.

desired result would be

0000000605
0000000606
0000000607 2
0000000608 2

Thanks Simi


 
Code:
SELECT Account, MIN(Branch) AS Branch
FROM YourTable
GROUP BY Account
ORDER BY Account
 
easy enough... I should have thought of it myeself.

Thanks Riverguy

Simi
 
Watch out for NULL

[tt]Warning: Null value is eliminated by an aggregate or other SET operation.[/tt]

djj
The Lord is my shepherd (Psalm 23) - I need someone to lead me!
 
[tt]Warning: Null value is eliminated by an aggregate or other SET operation.[/tt]

This can be "fixed" be setting ANSI_WARNINGS off. Ex:

Code:
Set ANSI_WARNINGS Off

SELECT Account, MIN(Branch) AS Branch
FROM YourTable
GROUP BY Account
ORDER BY Account

-George
Microsoft SQL Server MVP
My Blogs
SQLCop
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Just wanted to show that if Branch was null it would not show in the aggregate, see "0000000605" which would return 1. At least that is how my test worked.


djj
The Lord is my shepherd (Psalm 23) - I need someone to lead me!
 
If you are using SQL Server 2005 or 2008, then you can easily do this by using the RANK function as shown below:

SELECT tmp.Account, tmp.Branch FROM
(SELECT Account, Branch, RANK() OVER (Partition by Account ORDER BY Branch) as Rank
FROM AccountBranch
) tmp
WHERE tmp.Rank = 1

Explanation:
************
The inner derived table ranks the records broken by Account i.e.

Account Branch Rank
********* ****** ****
0000000605 NULL 1
0000000605 1 2
0000000605 10 3
0000000606 NULL 1
0000000606 3 2
0000000607 2 1
0000000607 5 2
0000000608 2 1

and the outer select has a WHERE clause to filter only records that have a Rank of 1.

Simple yet powerful.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top