Results 1 to 3 of 3

Thread: sql join

  1. #1
    Join Date
    Aug 2006
    Posts
    39

    Unanswered: sql join

    Hi,
    There are three tables:

    tblUsers --> 28 records
    tblDepartments
    tblDepartmentsUsers --> something like a junction table between the above two tables.

    I have entered several test records into tblDepartmentsUsers.
    So that some of the users have Departments allocated to them.

    I would like to have a query so that you can pass in a departmentID. The result should show all users in the users table. In addition, it should show the departmentID for the users that do have a department and null for the unacclocated users.

    This the stored procedure that I have.
    The problem is the where clause. because when I pass in the departmentID it returns only those allocated departments. Whereas I would like to see all users (null for users with unAllocated departmentID)

    ALTER PROCEDURE [dbo].[DepartmentUsers_Get]

    @DepartmentID int

    AS

    select
    u.UserID,
    u.UserName,
    du.Percentage
    from
    Users as u left join DepartmentsUsers as pu on u.UserID = du.UserID
    where
    du.DepartmentIDID = @DepartmentID

  2. #2
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    Code:
    select u.UserID
         , u.UserName
         , du.Percentage
      from Users as u 
    left outer
      join DepartmentsUsers as du 
        on du.UserID = u.UserID
       and du.DepartmentIDID = @DepartmentID
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

  3. #3
    Join Date
    Aug 2006
    Posts
    39
    Solved.
    Thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •