MySQL | Sum Column如果不同ID

时间:2015-02-13 10:43:34

标签: mysql join sum

我正在尝试仅在id不同的情况下对列进行求和。

我试过这样,但它不起作用:

SUM(CASE WHEN 
             DISTINCT empLeaves.ApprovedLeaveID 
         THEN empLeaves.TotalLeavesTaken END) AS Total

SUM它的正确方法是什么?

以下是我要处理的总查询:

SELECT 
      E.employee_id AS EmployeeID, 
      E.employee_code AS EmployeeCode,
      E.full_name AS EmployeeName,
      empLeaves.LeavesFromDate,
      empLeaves.LeavesToDate, 
      -- COUNT(empLeaves.ApprovedLeaveID) AS TotalApprovedApplications,
      ATT.`in_date` AS InDate, 
      ATT.`out_date` AS OutDate,
      SUM(CASE WHEN DISTINCT empLeaves.ApprovedLeaveID THEN empLeaves.TotalLeavesTaken END) AS Total
FROM employee E
LEFT JOIN `attendence` ATT ON ATT.`employee_id` = E.`employee_id`
LEFT JOIN (
           SELECT 
                 LA.`leave_approval_id` AS ApprovedLeaveID,
                 E.`employee_id` AS EmployeeID,
                 LA.`approved_from` AS LeavesFromDate, 
                 LA.`approved_to` AS LeavesToDate,
                 DATEDIFF(LA.approved_to,approved_from) AS TotalLeavesTaken
            FROM leave_application APP
            INNER JOIN leave_approval LA 
                 ON LA.`leave_application_id` = APP.`application_id` AND LA.`trashed` = 0 AND LA.`status` = 2
            INNER JOIN employee E 
                 ON E.`employee_id` = APP.`employee_id` AND E.`trashed` = 0 AND E.`enrolled` = 1
            INNER JOIN ml_leave_type MLLT 
                 ON MLLT.`ml_leave_type_id` = APP.`ml_leave_type_id` AND MLLT.`trashed` = 0
) empLeaves ON E.`employee_id` = empLeaves.EmployeeID
WHERE
     E.`enrolled` = 1 AND E.`trashed` = 0
GROUP BY
     E.`employee_id`,empLeaves.EmployeeID

1 个答案:

答案 0 :(得分:0)

哪个ID与什么不同?

通常,当您在某个字段中有值并且想要将它们添加到一起时,除了特定行集中的值之外,您只需将不需要的值设置为0:

sum( case otherfield when somevalue then row.field else 0 end ) as SumOfValues

因此,当otherfield显示这是您想要包含在总计中的行时,您会公开要添加的字段(在此示例中为row.field)。否则,你暴露零。当然,如果您正在测试的值是在总数中找到想要的行,只需将then之后的零和{{1}之后的字段放入}}