View Full Version : Group BY First in SQL


Pauldohert
05-30-2008, 04:37 AM
IN access I have

SELECT First(Table1.EmailAdd) AS FirstOfEmailAdd, Table1.EmailAdd, First(Table1.OrgID) AS FirstOfOrgID, First(Table1.ContactID) AS FirstOfContactID, First(Table1.Name1) AS FirstOfName1, First(Table1.Name2) AS FirstOfName2
FROM Table1
GROUP BY Table1.EmailAdd;

Basically I am getting the unique emails then adding back in the other fields from the first record found with that email.

How do I do this in SQL server?

Ta

georgedwilkinson
05-30-2008, 07:00 AM
I guess you're talking about the "First()" function?

You can write a stored procedure in SQL Server that mimics that function. Then the stored procedure is callable within a sql statement.

You could also replace the entire query with a stored procedure.

Does that help?

Pauldohert
05-30-2008, 08:42 AM
I went for something along these line in the end


SELECT Table1.EmailAdd, Table1.OrgID, Table1.ContactID, Table1.Name1, Table1.Name2
FROM Table1 INNER JOIN [SELECT Table1.EmailAdd, Min(Table1.ContactID) AS MinOfContactID
FROM Table1
GROUP BY Table1.EmailAdd]. AS A ON Table1.ContactID = A.MinOfContactID;

would the sp be based on something like this - Ta?

georgedwilkinson
05-30-2008, 09:13 AM
You can return a result set from an SP. Does that SQL work for you the way you want? If yes, the big advantage to using an SP is that the SQL is already parsed and compiled on subsequent calls.