SQL没有正确连接

时间:2015-06-12 14:23:36

标签: sql-server inner-join

我有一个带有一些JOIN条件的SQL语句它适用于所有这些,但不是最后一个代码如下:

SELECT 
    A.EMPL_CTG, 
    B.DESCR AS PrName, 
    SUM(A.CURRENT_COMPRATE) AS SALARY_COST_BUDGET, 
    SUM(A.BUDGET_AMT) AS BUDGET_AMT, 
    SUM(A.BUDGET_AMT)*100/SUM(A.CURRENT_COMPRATE) AS MERIT_GOAL,
    SUM(C.FACTOR_XSALARY) AS X_Programp, 
    SUM(A.FACTOR_XSALARY) AS X_Program,
    COUNT(A.EMPLID) AS EMPL_CNT, 
    COUNT(D.EMPLID),
    SUM(CASE WHEN A.PROMOTION_SECTION = 'Y' THEN 1 ELSE 0 END) AS PRMCNT,
    SUM(CASE WHEN A.EXCEPT_IND = 'Y' THEN 1 ELSE 0 END) AS EXPCNT, 
    (SUM(CASE WHEN A.PROMOTION_SECTION = 'Y' THEN 1 ELSE 0 END)+SUM(CASE WHEN A.EXCEPT_IND = 'Y' THEN 1 ELSE 0 END))*100/(COUNT(A.EMPLID)) AS PEpercent 
FROM 
    EMP_DTL A INNER JOIN EMPL_CTG_L1 B ON A.EMPL_CTG = B.EMPL_CTG  
    INNER JOIN 
    ECM_PRYR_VW C ON A.EMPLID=C.EMPLID 
    INNER JOIN ECM_INELIG  D on D.EMPL_CTG=A.EMPL_CTG and D.YEAR=YEAR(getdate()) 
WHERE 
    A.YEAR=YEAR(getdate()) 
    AND B.EFF_STATUS='A' 
GROUP BY 
    A.EMPL_CTG, 
    B.DESCR 
ORDER BY B.DESCR

COUNT(D.EMPLID)返回与COUNT(A.EMPLID)相同的值,但我需要在加入条件中表D EMPLID s计数,任何帮助?

1 个答案:

答案 0 :(得分:0)

COUNT()(以及其他GROUP BY aggregate functions)不会只处理其中一个表中的行。

它们处理JOIN生成的所有行。如果JOIN没有GROUP BY生成42行,则COUNT(*)COUNT(1)会返回42,而COUNT(A.EMPLID)COUNT(D.EMPLID)会返回NULL不是 - NULL这些列中的值。

为了获得从其中一个表中提取的行数,您应该使用COUNT(DISTINCT)。它会忽略JOIN值以及COUNT(D.EMPLID)生成的重复项。

COUNT(DISTINCT D.EMPLID)更改为<div class="wpsl-results loading" style="display: block;"></div>