我尝试在子查询表中计算总员工数。假设计数结果将返回0,但它会一直返回1.
如果我尝试只返回employee_id和month,我没有得到任何正确的返回值,但每次我尝试计数(不同)时,我会得到1作为我的返回值。这是我的sql
SELECT
count (distinct(CASE WHEN (x.month =5 and x.employee_id <> 0) THEN
x.employee_id
ELSE 0 END)) as test_may
FROM(
(
SELECT
h.month,
h.employee_id,
eb.employee_no,
ee.company_code,
h.amount,
h.year,
h.trx_type,
h.trx_code,
v.trx_desc,
h.frequency,
h.run_sequence
FROM
v_employee h,
v_trans v,
employee_emp ee,
employee eb
WHERE
( h.year = 2014 ) AND
( h.employee_id = ee.employee_id ) AND
( ee.employee_id = eb.employee_id ) AND
( h.employee_no = eb.employee_no ) AND
( h.trx_code = v.trx_code ) AND
( h.trx_type = v.trx_type ) AND
( v.company_code = ee.company_code OR v.company_code is NULL) AND
( h.trx_type IN ('S','B','N','O','A','D','L') )
)
)x,
employee_emp ee,
employee eb
WHERE
( x.employee_id = ee.employee_id ) AND
( ee.employee_id = eb.employee_id ) AND
( x.employee_no = eb.employee_no ) AND
( x.year = 2014 )
答案 0 :(得分:2)
现在的count
也将计算ELSE
表达式的CASE
子句中的0。即使使用DISTINCT
,仍然会计算该0的一个实例。
删除ELSE 0
,以便NULL
- 不计算在内:
count (distinct(CASE WHEN x.month =5 and x.employee_id <> 0
THEN x.employee_id
END)) as test_may
请注意,使用NULLIF
,您可以将此表达式缩短为:
count (distinct(CASE x.month WHEN 5 THEN NULLIF(x.employee_id, 0) END)) as test_may
答案 1 :(得分:1)
即使在这两种情况下,您的count
也会返回相同的计数。因为在两种情况下都给出了Count函数的值。
从
改变 count (distinct(CASE WHEN (x.month =5 and x.employee_id <> 0) THEN
x.employee_id
ELSE 0 END))
要
count (distinct(CASE WHEN (x.month =5 and x.employee_id <> 0) THEN
x.employee_id
ELSE NULL END))
Count只计算0或100的值为1&amp;计数时跳过空值。因此,在Else条件NULL
将为您提供正确的输出。