Alternative to "First" Function - Distinct and Top 1 :)

Even though I am no SQL guru, a problem poised by one of my colleagues seemed challenging enough for me to investigate further.

Here was his problem:

He was working on a data migration and he had a table with rows made up of 'Dates' and 'Cost' . There were multiple rows with the same date and he wanted to Pick the first "Cost" value for a specific date.

Now having used SQL reportings ervices, it seemed like an easy task.  It is possible to get this done by using the "First" function. Unfortunately T-SQL does not have a "first" function.

Lets take the following sample table shown below:


He wanted a Query that could give him the Unique Names along with the "First" value for that Name. If we take N2 for example the first value is '3' and for N3 it is '8'.

After some experimenting, the query that produces this result is

    

    1   SELECT DISTINCT(Customers_Unique.Name),

    2        (SELECT TOP 1  value

    3         FROM Customers

    4         WHERE Name = Customers_Unique.name)AS value

    5   FROM Customers Customers_Unique



Here is the result



Pretty cool huh ?

Hope this helps someone

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.