如何制作有条件的SUM?

时间:2011-03-03 09:08:19

标签: sql oracle exists

我需要创建一个SQL查询来计算为特定客户工作的员工小时数(编号108538)。我们区分了两种类型的计数:一周工作的人(37h50)和周六和周日工作的人(22h50)。

为了不惩罚他们,决定向他们提供15小时奖金 要知道谁只在周末工作,我们在合同中使用特定类别,即206号。其他员工有其他类别(001,250,604 ......),因此我不能在该类别上制作简单的GROUP BY。

请求的目的是计算所有员工在2008年1月至2011年3月期间的工作小时数,同时考虑到“仅为周末工作的人”提供的小时数。

我认为使用EXISTS知道何时添加这些奖励时间,但我没有得到理想的结果。

这是我写的查询:

SELECT   employee.name, employee.surname, SUM(timesheet.hours_par_day + 
            (CASE
                WHEN EXISTS (
                      SELECT *
                        FROM (SELECT contract.contrat_id
                                FROM contract, contract_categories
                               WHERE contract.customer_id = '108538'
                                 AND contract.begin_date BETWEEN '01/01/2008' AND '01/03/2011'
                                 AND contract_categories.contract_id = contract_categories.id_avenant
                                 AND contract_categories.id_category = '206') ctrsd
                       WHERE ctrsd.contrat_id = contract.contrat_id)
                   THEN 15
                ELSE 0
            END
            )
        ) AS hours_worked
FROM contract JOIN employee ON contract.employee_id = employee.employee_id
     JOIN timesheet ON contract.contrat_id = timesheet.contrat_id
WHERE contract.customer_id = '108538'
 AND contract.begin_date BETWEEN '01/01/2008' AND '01/03/2011'
 AND employee .employee_id IN (
                   SELECT employee_id
                     FROM contract
                    WHERE contract.client_id = '108538' AND contract.end_date >= '01/01/2011')

它计算正确...但不包括额外的15个小时。我想我误用了EXISTS,但我不知道还能用什么......有没有人有任何想法?

1 个答案:

答案 0 :(得分:1)

我认为在这种情况下你不需要CASE中的子查询,你可以改为外连接(虽然,我不确定“contract_financial”来自哪里 - 可能缺少一个表?):

SELECT   employee.name, employee.surname, SUM(timesheet.hours_par_day + 
            (CASE
                WHEN contract.id_category = '206'
                THEN 15
                ELSE 0
            END
            )
        ) AS hours_worked
FROM contract JOIN employee ON contract.employee_id = employee.employee_id
     JOIN timesheet ON contract.contrat_id = timesheet.contrat_id
     LEFT JOIN contract_categories
     ON contract.contract_id = contract_categories.contract_id
WHERE contract.customer_id = '108538'
 AND contract.begin_date BETWEEN '01/01/2008' AND '01/03/2011'
 AND employee .employee_id IN (
            SELECT employee_id
            FROM contract
            WHERE contract.client_id = '108538'
            AND contract.end_date >= '01/01/2011')