SQL查询返回错误的结果

时间:2015-08-15 08:44:11

标签: sql sql-server

我的查询返回错误的结果。请看下面的内容。我得到了所有员工同样的工资总额。

我想要的结果如下表所示:

S.no  Employee_name  Emoloyee_id  Gross Salary
-----------------------------------------------
1     Abc            001          1234567
2     Xyz            002          2345667
3     Dfg            003          456784

以下是上述查询的示例表。这包括以下视图和表格:

(a)V_HR_PP_PROCESS_DATA,其中包含工资总额的Amount

EMPLOYER_CODE  TAX_YEAR EMPLOYEE_ID  PROCESS_MONTH  PD_CODE
-----------------------------------------------------------
RAD             2014          1          1          D001
RAD             2014          1          1          Z001
RAD             2014          3          2          Z500

(b)I_HR_SYS_DATE_MONTHLY

EMPLOYER_CODE  TAX_YEAR  MONTH 
------------------------------
RAD               2014    1
RAD               2014    2

(c)I_HR_EMPLOYEE_MASTER

EMPLOYER_CODE EMPLOYEE_ID   EMPLOYEE_NAME 
-----------------------------------------------
RAD                1        GODWIN  KOMBA
RAD                2        JANE  SHIBANDA
RAD                3        ANDREW JOACHIM KIIZA
RAD                4        AHMED IBRAHIM DAHAL
RAD                5        ADAM  KAWA

EMPLOYER_CODE = 'RAD'对于所有这三个表都很常见。

请查看查询,但未按要求提供结果:

SELECT 
    b.EMPLOYEE_NAME AS employeename,
    (SELECT SUM(AMOUNT)
     FROM V_HR_PP_PROCESS_DATA
     WHERE EMPLOYER_CODE = A.EMPLOYER_CODE
       AND EMPLOYEE_ID IN (SELECT EMPLOYEE_ID
                           FROM I_HR_EMP_EMPLOYMENT_DTL
                           WHERE EMPLOYER_CODE = A.EMPLOYER_CODE
                             AND CONTRACT_TERM = 'F')
       AND PROCESS_MONTH BETWEEN 1 AND 10
       AND PD_CODE = 'Z500') AS GROSS_CASUAL
FROM 
    I_HR_SYS_DATE_MONTHLY A
INNER JOIN 
    I_HR_EMPLOYEE_MASTER b ON b.EMPLOYER_CODE = A.EMPLOYER_CODE
GROUP BY 
    A.EMPLOYER_CODE, b.EMPLOYEE_NAME

1 个答案:

答案 0 :(得分:0)

您的SELECT SUM(AMOUNT)子查询计算所有员工的金额,而不是一个一个。你有EMPLOYEE_ID IN (SELECT EMPLOYEE_ID...。仅过滤雇主代码,但处理所有雇员。因此,获得所有工资的摘要是正常的。在join / where条件中添加V_HR_PP_PROCESS_DATA.EMPLOYEE_ID = b.EMPLOYEE_ID