我正在开发一个基于Web的培训管理系统,为用户提供简短的测验以更新他们的知识。无论如何,我有以下数据库设计:
Employee Table: Username, Name, DivisionCode
Divisions Table: SapCode, DivisionShortcut
Quiz Table: QuizID, Title, IsSent
Question Table: QuestionID, Question, QuizID...
UserQuiz Table: UserQuizID, QuizID, Username, Score.
我能够提出一个查询,在最后一个测验中显示所有部门中所有非参与者的姓名。我现在想要的是在已发送给用户参与其中的所有测验中显示非参与者姓名。结果应按测验标题和DivisionShortcut列出分组。 那怎么做?
我的查询:
SELECT d.DivisionShortcut, e.Name
FROM employee e
join Divisions d on (e.DivisionCode = d.SapCode)
left join (select A.QuizID, a.Username
from UserQuiz a join
(select max(QuizID) QuizID from dbo.Quiz where IsSent=1) b
on a.QuizId = b.QuizID ) c
on e.Username = c.Username
WHERE c.QuizID is null
Order By d.DivisionShortcut
答案 0 :(得分:3)
您可以使用CROSS JOIN
获取员工和测验的所有组合,然后使用NOT EXISTS
来消除已完成的所有组合:
SELECT *
FROM Employee e
INNER JOIN Divisions d
ON e.DivisionCode = d.SapCode
CROSS JOIN Quiz
WHERE Quiz.IsSent = 1
AND NOT EXISTS
( SELECT 1
FROM UserQuiz uq
WHERE uq.QuizID = Quiz.QuizID
AND uq.UserName = e.UserName
)