Quantcast
Channel: Forum Getting started with SQL Server
Viewing all articles
Browse latest Browse all 7129

Issue selecting records from multiple tables where id not in a sub query

$
0
0

I'm struggling with what seems like a fairly simple query ...

Here's some background: the database is used to track training that is assigned to individuals depending on their job/projects.

My query needs data from three tables -

Employee: a table that holds employee data

Training: a table that holds data about the various training courses available

Matrix: a table that holds Employee.id, Training.id, and DateCompleted. Think of it as a training assignment table where an admin can go in and assigne specific courses to specific individuals.

With that background, I need to create a query that will show a group of selected users and training courses that have not completed their training by a specific date. It's possible that that group of individuals might be those who:

1. have never been assigned a course (e.g. there is no record in the Matrix table for them)

2. they have had the course assigned but haven't completed yet (e.g there is an assignment, but Matrix.DateCompleted IS NULL)

3. they have had the course assigned and they have completed it, but the completed date is before the date given for the report (Matrix.DateCompleted < '10/29/2014')

The closest I have come so far is this:

WITH A AS (
	SELECT Employee.UserID, Employee.Username, training.id AS courseid, training.Course,
	  (SELECT TOP 1 (Matrix.datecompleted) FROM Matrix WHERE Matrix.courseid=training.ID AND Matrix.userid = Employee.UserID ORDER BY datecompleted DESC)
		AS LastCompleted
	FROM Employee
	INNER JOIN Matrix ON Employee.UserID = Matrix.userid
	INNER JOIN training ON training.id = Matrix.courseid
	WHERE
		Employee.UserID NOT IN
		(
			SELECT Matrix.userid
			FROM Matrix
			WHERE  Matrix.datecompleted > '10/29/2014'
		)
)

SELECT *
FROM A
WHERE
	UserID IN (1,2,3,4,5,6,7,8,9)
AND
	courseid IN (1,30,63)
ORDER BY courseid,Username

I get close to the correct output, but it's only displaying rows that exist in the matrix table.

For example, if I were to run that query, I might get a result for users 1,2,8, and 9 because they have a course assigned in the Matrix table.  But I also want to see users that list of provided UserIDs (1,2,3,4,5,6,7,8,9) that don't have a course assigned yet too, not just the ones who have either never completed the assignment or whose completion date is before the report date.


Viewing all articles
Browse latest Browse all 7129

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>