0

我有一个查询和显示,它为我提供按部门分组的员工。它工作正常,但我还需要另外一件事我无法弄清楚。通过部门名称,我需要添加文字:“(x 员工)”,其中 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>&nbsp;&nbsp; #TRIM(First)#&nbsp;#TRIM(Last)#</td>
    </tr>
    </cfoutput>

    <tr>
        <td height="0">&nbsp;</td>
    </tr>
</cfoutput>
</table>
4

3 回答 3

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>&nbsp;&nbsp; #TRIM(getEmpsByDept.First)#&nbsp;#TRIM(getEmpsByDept.Last)#</td>
    </tr>
  </cfoutput> 
  <tr>
    <td height="0">&nbsp;</td>
  </tr>
</cfoutput>
于 2013-11-12T19:05:17.980 回答
1

如果您使用的是 CF 10 或 Railo 4 并且想要发挥创意,您​​可以使用Underscore.cfc 中的countBy ()

// 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

于 2013-11-13T06:11:57.903 回答
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>
于 2013-11-12T19:07:00.010 回答