JOIN Query that returns only the first record from every joined second table

Posted on 2006-05-10
Last Modified: 2006-11-18

Here's my problem: I have two tables.


recID       Description
a             record a
b             record b
c             record c
d             record d

recID       Table1RecID       Description
1             a                       Record 1
2             a                       Record 2
3             a                       Record 3
4             b                       Record 4
5             b                       Record 5

I would like to make a left join query, that would return ONLY ONE (can be random) record for every TABLE1 record FROM TABLE 2. Example:

recIDTable1         RecIDTable2        DescTable2
a                         2                       Record2
b                         4                       Record4
Question by:coyotee
    LVL 17

    Expert Comment

    Try this!

    Select Top  1 Table1 .recID,   Table2.RecID,  Table2.Desc From Table1, Table2
    order by newid() --this for random
    LVL 11

    Accepted Solution

    Try this:

    from Table1 t1
    left join (select Table1RecID, max(Description) from Table2 group by Table1RecID) t2 on t1.recID = t2.Table1RecID

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    Nowadays, some of developer are too much worried about data. Who is using data, who is updating it etc. etc. Because, data is more costlier in term of money and information. So security of data is focusing concern in days. Lets' understand the Au…
    When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
    Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
    Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now