我正在使用MSSQL server 2008并有两个表forms
和employees
。
forms
包含员工填写的所有表格,例如
[id][employeeId][formId]
只有6种类型的表单,每种表单都有自己的ID。如何构建查询以列出每种类型的表单以及它们是否已完成(存在于forms
表中),例如
[employeeId][formType1][formType2][formType3]...
1 1 null 1
2 1 1 null
编辑:我当前的查询列出了所有需要“过滤”到上面架构的信息:
SELECT *
FROM forms as f
inner join employees as e on e.EmployeeID = f.EmployeeID
答案 0 :(得分:3)
您可以按员工ID进行分组,并“计算”每种表单类型的实例数:
SELECT employeeid,
SUM(CASE WHEN f.ID = 1 THEN 1 ELSE 0 END) formType1,
SUM(CASE WHEN f.ID = 2 THEN 1 ELSE 0 END) formType2,
SUM(CASE WHEN f.ID = 3 THEN 1 ELSE 0 END) formType3,
SUM(CASE WHEN f.ID = 4 THEN 1 ELSE 0 END) formType4,
SUM(CASE WHEN f.ID = 5 THEN 1 ELSE 0 END) formType5,
SUM(CASE WHEN f.ID = 6 THEN 1 ELSE 0 END) formType6
FROM forms as f
GROUP BY employeeid
答案 1 :(得分:2)
也许这可以解决问题
SELECT emp.[employeeName], form1.formId as formType1, form2.formId as formType2, form3.formId as formType3, form4.formId as formType4, form5.formId as formType5, form6.formId as formType6
FROM [database_name].dbo.[employees] as emp
RIGHT OUTER JOIN [database_name].dbo.[form] as form1 ON (emp.[EmployeeID] = form1.[EmployeeID] AND form1.id='ID_FOR_THE_FORM1')
RIGHT OUTER JOIN [database_name].dbo.[form] as form2 ON (emp.[EmployeeID] = form2.[EmployeeID] AND form2.id='ID_FOR_THE_FORM2')
RIGHT OUTER JOIN [database_name].dbo.[form] as form3 ON (emp.[EmployeeID] = form3.[EmployeeID] AND form3.id='ID_FOR_THE_FORM3')
RIGHT OUTER JOIN [database_name].dbo.[form] as form4 ON (emp.[EmployeeID] = form4.[EmployeeID] AND form4.id='ID_FOR_THE_FORM4')
RIGHT OUTER JOIN [database_name].dbo.[form] as form5 ON (emp.[EmployeeID] = form5.[EmployeeID] AND form5.id='ID_FOR_THE_FORM5')
RIGHT OUTER JOIN [database_name].dbo.[form] as form6 ON (emp.[EmployeeID] = form6.[EmployeeID] AND form6.id='ID_FOR_THE_FORM6') ;
不完全是你在寻找什么你可以评估是否为NULL然后员工没有回答那个形成他回答的所有其他内容。我希望这有帮助
答案 2 :(得分:0)
如果您希望看到那些没有填写任何表格的员工,那么您可以试试这个:
Select FormName, EmpName, id
FROM
(SELECT formID ,FormName , empID, EmpName
FROM FormTypes
CROSS JOIN Emp) x
LEFT JOIN Forms f on (x.empid = f.employeename and x.formID = f.formID)