我有一个带有一些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计数,任何帮助?
答案 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>
。