我有一个查询和显示,可以让我按部门分组。它工作正常,但还有一件我需要的东西,我无法弄明白。通过部门名称,我需要添加文字说:“(x employees)”,其中x是该部门的员工人数。例如:
MARKETING (2 employees)
John Doe
Jane Smith
我的代码如下:
<cfquery name="getEmpsByDept" datasource="#application.DSN#" dbtype="ODBC">
SELECT DISTINCT First, Last, Department
FROM SuccessFactorsPeople
ORDER BY Department
</cfquery>
<table border="0" width="70%" cellpadding="0" cellspacing="0">
<cfoutput query="getEmpsByDept" group="Department">
<tr>
<td><b>#Ucase(Department)#</b></td>
</tr>
<cfoutput>
<tr>
<td> #TRIM(First)# #TRIM(Last)#</td>
</tr>
</cfoutput>
<tr>
<td height="0"> </td>
</tr>
</cfoutput>
</table>
答案 0 :(得分:2)
您无法使用内置计数器。您必须遍历组内的每条记录,以获得每个部门的计数器。
另外,请确保查看变量的范围
<cfoutput query="getEmpsByDept" group="Department">
<cfset empCount = 0>
<cfoutput>
<cfset empCount++>
</cfoutput>
<tr>
<td><b>#Ucase(getEmpsByDept.Department)# #empCount# Employees</b></td>
</tr>
<cfoutput>
<tr>
<td> #TRIM(getEmpsByDept.First)# #TRIM(getEmpsByDept.Last)#</td>
</tr>
</cfoutput>
<tr>
<td height="0"> </td>
</tr>
</cfoutput>
答案 1 :(得分:1)
您需要在SQL
中使用group by如果对于任何给定的部门,如果计数不同,如果有不同的名称,那么你想要这个
<cfquery name="getEmpsByDept" datasource="#application.DSN#" dbtype="ODBC">
SELECT First, Last, Department, COUNT(Department) AS Department Count
FROM SuccessFactorsPeople
GROUP BY First, Last, Department
Order by Department
</cfquery>
这样可以保证每个部门都能获得一行,无论如何,但MAX(first)
和MAX(last)
可能会遇到其他问题
<cfquery name="getEmpsByDept" datasource="#application.DSN#" dbtype="ODBC">
SELECT MAX(First) AS First, MAX(Last) AS Last, Department, COUNT(Department) AS DepartmentCount
FROM SuccessFactorsPeople
GROUP BY Department
Order by Department
</cfquery>
如果你不想在第一次和最后一次崩溃。
<cfquery name="getEmpsByDept" datasource="#application.DSN#" dbtype="ODBC">
SELECT DISTINCT First, Last, A.Department, DepartmentCount
FROM SuccessFactorsPeople A
INNER JOIN (
SELECT Department, COUNT(Department) AS DepartmentCount
FROM SuccessFactorsPeople
GROUP BY Department
) B
ON A.Department = B.Department
ORDER BY A.Department
</cfquery>
答案 2 :(得分:1)
如果您使用的是CF 10或Railo 4并且想要发挥创意,可以使用countBy()中的Underscore.cfc:
// instantiate Underscore library
_ = new Underscore();
// get a struct of employee counts by department
empCountsByDept = _.countBy(getEmpsByDept, function (row) {
return row.Department;
});
然后,您只需在输出代码中引用empCountsByDept
结构,如下所示:
<td><b>#Ucase(getEmpsByDept.Department)# (#empCountsByDept[Department]# employees)</b></td>
注意:我写了Underscore.cfc