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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 return min value

Author  Topic 

eugz
Posting Yak Master

210 Posts

Posted - 2010-08-05 : 15:10:23
Hi All.
How to return MIN vallue for CODE field of JOIN two tables?
What I mean. For instance:
select a.Emp_Id, Code
from Table1 a
join table2 b
on a.Emp_Id = b.Emp_Id

if return is:
2 12.51
2 54.3
2 3.25
6 57.6
9 101.3
6 12.1

My question is, how to get result like:
2 3.25
6 12.1
9 101.3

Thanks.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-08-05 : 15:15:53
Sounds like a homework question, but I'll bite:

select a.Emp_Id, MIN(Code) AS MinCode
from Table1 a
join table2 b
on a.Emp_Id = b.Emp_Id
group by a.Emp_Id

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

eugz
Posting Yak Master

210 Posts

Posted - 2010-08-10 : 17:00:49
Thanks for replay.

Now I need to use your select like subselect in other SELECT statment. My target is to display new fields including CODE field witch is MIN in subselect.

select
v.Visit_Id
,Convert(varchar(10),Svc_Date,101) Svc_Date
,Adm_No
,FName
,LName
,(select a.Emp_Id, MIN(Code) AS MinCode
from Table1 a
join table2 b
on a.Emp_Id = b.Emp_Id
group by a.Emp_Id) Code
,Submit
from Table3 v
join dbo.Table4 p
on v.AAA_id = p.AAA_id
left outer join Table2 vd
on v.Emp_Id = vd.Emp_Id

If know other way to get same result I will appreciate for help.

Thanks.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-08-11 : 05:01:10
See if this works

select t1.* from table1 as t1 inner join
(
select emp_id, min(code) as code from table2
group by emp_id
) as t2
on t1.emp_id=t2.emp_id and t1.code=t2.code




Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -