Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Simple Q: How to join, without duplicating left?

Author  Topic 

IvanJAdv
Starting Member

2 Posts

Posted - 2011-07-21 : 21:40:38
Let's say I have 2 tables:

"Student"
ID, Name
1, Ivan
2, Tom

"Data"
ID, Data
1, blah
1, blah2

What I want to accomplish is to pull all the records from the "Student" table, but pull no more than 1 corresponding record from the "Data" table. The result I want to end up with is:

"Result"
ID, Name, Data
1, Ivan, blah (or blah 2, don't care which)
2, Tom, null

...how do I go about this? I used to think full outer join would get me there, but looks like I'm wrong.

Thanks!

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2011-07-21 : 22:08:54
try

1. use LEFT JOIN to Data table
2. use GROUP BY column ID, NAME and applied aggregate function (min or max) on column Data


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-07-22 : 10:47:24
[code]
SELECT s.ID,s.Name, d.MinData
FROM (SELECT ID,MIN(Data) AS MinData FROM Data GROUP BY ID) d
LEFT JOIN Student s
ON s.ID = d.ID
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

IvanJAdv
Starting Member

2 Posts

Posted - 2011-07-22 : 10:58:11
Thanks that helps!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-07-22 : 11:05:12
wc

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -