If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Nested Sub Queries

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 05-12-04, 12:54
vpatel vpatel is offline
Registered User
 
Join Date: May 2004
Posts: 1
Smile Nested Sub Queries

Hello,

I have a table that contains following user attributes
  • FirstName
  • LastName
  • Title
  • Region
  • District
The table basically lists all the employees and managers in an organization. Each manager has the Title attribute set to "Manager" and each employee has it set to "Employee". Each manager is assigned to a Region and District.

So lets say that an employee has a region = north, and district = 100, then that employee reports the manager with same region and district attributes.

I want to write a query that will allow me the final output to look something like this:

Jon Doe, Manager - District 10, Region North
  • Jim Jackson, Employee reporting to Jon Doe
  • Mary Jones, Employee reporting to Jon Doe
Robert Smith, Manager - District 15, Region East
  • Bobbie Sue, Employee reporting to Jon Doe
  • Richard James, Employee reporting to Jon Doe
... ... ... so on ... ... ...

I would like to accomplish this in 1 query (nested sub queries are ok) if possible.

I would appreciate if someone could help me out with the sql part of this. I tried several different things and by no means I am a DB person.

Thanks
V. Patel
Reply With Quote
  #2 (permalink)  
Old 05-12-04, 16:33
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,534
Code:
select m.FirstName as employeeFirstName
     , m.LastName  as employeeLastName
     , m.Region
     , m.District
     , e.FirstName as employeeFirstName
     , e.LastName  as employeeLastName
  from yourtable m
left outer
  join yourtable e
    on m.Region   = e.Region
   and m.District = e.District       
   and              e.Title = 'Employee'
 where m.Title = 'Manager'  
order
    by 2,1,6,5
then perform some logic while looping over the output to detect the manager name control break, so you can print that nice indented list
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On