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 2000 Forums
 SQL Server Development (2000)
 Help Needed with Query

Author  Topic 

gpadhye
Starting Member

1 Post

Posted - 2008-04-09 : 00:18:21
Hello,

I need to write some queries
The requirements are as follows:

I have the following tables with some sample data like below

Table 'users' Table accounts

Userkey Username Manager Userkey accounts

1 ABC DEF 3 Test1
2 XYZ ABC
3 PQR ABC

Now,
I need to write a query to get:

1. Users who dont have accounts (i.e userkey 1 and userkey 2)..The result I will get is users 'ABC' and 'XYZ'
2. select the user out of the users from step 1(who dont have
accounts i.e 'ABC and XYZ' who is not a manager..i.e not in column manager under table 'users')

Result expected is XYZ since ABC is a manager for user ABC and XYZ


Can someone help me with this query?
Any help is appreciated..


Thanks,
Gaurav

RyanRandall
Master Smack Fu Yak Hacker

1074 Posts

Posted - 2008-04-09 : 05:12:38
Hi Gaurav

Here's one way which should be easy to understand...


--preparation
declare @users table (Userkey int, Username varchar(10), Manager varchar(10))
insert @users
select 1, 'ABC', 'DEF'
union all select 2, 'XYZ', 'ABC'
union all select 3, 'PQR', 'ABC'

declare @accounts table (Userkey int, accounts varchar(10))
insert @accounts select 3, 'Test1'

--query
select * from (
select a.*,
case when b.Userkey is null then 0 else 1 end as HasAccount,
case when c.Manager is null then 0 else 1 end as IsManager
from @users a
left outer join @accounts b on a.Userkey = b.Userkey
left outer join (select distinct Manager from @users) c on a.Username = c.Manager) a
where HasAccount = 0

--to get requirement 2, use add ' and IsManager = 0'


Ryan Randall
Solutions are easy. Understanding the problem, now, that's the hard part.
Go to Top of Page

Jeff Moden
Aged Yak Warrior

652 Posts

Posted - 2008-04-13 : 20:42:10
Who get's the "A" for these homework problems?

--Jeff Moden
"Your lack of planning DOES constitute an emergency on my part... SO PLAN BETTER! "
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row"

For better, quicker answers, click on the following... [url]http://www.sqlservercentral.com/articles/Best+Practices/61537/[/url]
Go to Top of Page

RyanRandall
Master Smack Fu Yak Hacker

1074 Posts

Posted - 2008-04-14 : 04:48:52
You're marking my work now, eh, Jeff?

Ryan Randall
Solutions are easy. Understanding the problem, now, that's the hard part.
Go to Top of Page
   

- Advertisement -