我的sql程序中有以下查询
SELECT
m.managerid,
CASE
WHEN (ISNULL(COUNT(t.employeeid), 0) = 0) THEN 'No Manager'
ELSE COUNT(m.managerid)
END
FROM employee t
LEFT JOIN employenrol m
ON t.employeeid = m.employeeid
GROUP BY t.employeeid
if count(t.employeeid)= 0
我需要显示没有经理其他实际计数。
将varchar值'No Manager'转换为时转换失败 数据类型int。警告:聚合或消除空值 其他SET操作。
如何解决这个问题?
答案 0 :(得分:2)
来自MSDN
else_result_expression和任何result_expression的数据类型 必须是相同的或必须是隐式转换。
您需要在else
部分中进行显式转换,因为第一个then
语句返回VARCHAR
,无法转换为INT
。
SELECT t.employeeid,
CASE
WHEN Count(m.employeeid) = 0 THEN 'No Manager'
ELSE Cast(Count(m.employeeid) AS VARCHAR(50))
END
FROM employee t
LEFT JOIN employenrol m
ON t.employeeid = m.employeeid
GROUP BY t.employeeid
如果您有Count
,0
汇总返回NULL
。无需使用ISNULL
功能
答案 1 :(得分:0)
这个怎么样
Select m.managerid,
Case When count(t.employeeid) =0 Then 'No Manager' Else count(m.managerid) end
From
employee t Left Join employenrol m On t.employeeid=m.employeeid
Group By t.employeeid
答案 2 :(得分:0)
我认为这是你想做的事情。
SELECT t.employeeid,
CASE WHEN COUNT(m.managerid) = 0 THEN 'No Manager'
ELSE CAST(COUNT(m.managerid) AS VARCHAR(10))
END
FROM employee t
LEFT JOIN employenrol m ON t.employeeid = m.employeeid
GROUP BY t.employeeid
不确定为什么你会选择m.managerid并计算t.employeeid哪个会产生错误,因为你只是按t.employeeid进行分组
这甚至可能对你有好处
SELECT t.employeeid,
CASE WHEN m.managercount = '0' THEN 'No Manager'
ELSE m.managercount
END
FROM @employee t
OUTER APPLY (SELECT CAST(COUNT(managerid) AS VARCHAR(10)) managercount
FROM @employenrol m
WHERE t.employeeid = m.employeeid
) m