Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using COUNT to check if data exists horribly expensive

Status
Not open for further replies.

pwills

Technical User
Sep 14, 2002
54
GB
I have a table of employees, some of which are supervisors.

(ID,NAME,SUP_ID)

When I list them out, I want to mark which ID's are supervisors. E.g.

ID,NAME,SUP_ID,Y/N

It will display Y if any row has a SUP_ID set to ID.

It seems horribly expensive (n^n) to do a count each time. Surely there is an n^2 or even better solution?
 
This should work:


SELECT empID, empName, supID,
CASE supID
WHEN empID THEN 'Y'
ELSE 'N'
END
FROM emp
 
Surely this will check if supID and empID are the same?

Imagine table:

1,Bob,2
2,Bill,<null>
3,Ben,<null>

View should produce

1,Bob,2,N
2,Bill,<null>,Y
3,Ben,<null>,N
 
I was thinking for a list of supervisors

select empid from table t1
where exists (select * from from table where supid = t1.empid)

..but don't know if legal sql
 
do you know if I can have something like:

select empid, empname, supid, case
exists (select * from from table t1 where t1.supid = empid) then 'y' else 'n' end
from table
 
You're making it too hard....

SELECT * FROM emp WHERE empID = supID
 
I believe this will give you the result you seek.

Select
ID, NAME, SUP_ID,
IsSup=Case When Exists
(Select * From Employees
Where SUP_ID=emp.ID)
Then 'Y' Else 'N' End
From Employees emp
Terry L. Broadbent - DBA
Computing Links:
faq183-874 contains &quot;Suggestions for Getting Quick and Appropriate Answers&quot; to your questions.
 
Hi Terry,

Thanks for this post. It does seem to me that is an n^n solution, because sql will search the table n times for each of n employees. But maybe SQL Server is more intelligent than that..
 
If you expect a low number of supervisors, you can try this


select a.empID , a.empName , a.supID , isnull(b.sup_flg,'N') as sup_flg
from emp a left outer join
(select distinct supID , 'Y' as sup_flg
from emp where supID is not null) b
on a.empID = b.supID


However, if the objective is just to get a list of supervisors then just select distinct supID from the table

select distinct supID from emp where supID is not null


RT
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top