首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > Mysql >

当记录为空时怎么虚拟一笔记录

2012-02-11 
当记录为空时如何虚拟一笔记录SQL:select a.user_name,工作工时,sum(a.work_hour),b.dept_name from use

当记录为空时如何虚拟一笔记录
SQL:
select a.user_name,'工作工时',sum(a.work_hour),b.dept_name from user_work a,sys_dept b
where a.dept_id=b.dept_id
group by a.user_name
union
select a.user_name,'浪费工时',sum(a.waste_hour),b.dept_name from user_waste a,sys_dept b 
where a.dept_id=b.dept_id
group by a.user_name 
如果有一条记录:张三,工作工时,10,采购 (此员工的浪费工时记录为空)
怎么才能返回如下记录:

  张三,工作工时,10,采购 
  张三,浪费工时, 0,采购 
请不吝指教

[解决办法]
union后面的改为
select a.user_name,'浪费工时',ifnull(sum(b.waste_hour),0),c.dept_name from user_work a left join user_waste on a.user_name = b.user_name inner join sys_dept c on a.dept_id=c.dept_id
[解决办法]
最好是创建一个人员表。这样可以使用left join
[解决办法]

SQL code
select a.user_name,'工作工时',sum(a.work_hour),b.dept_name from user_work a left join sys_dept bon a.dept_id=b.dept_idgroup by a.user_nameunionselect a.user_name,'浪费工时',sum(a.waste_hour),b.dept_name from user_waste a left join sys_dept b  on a.dept_id=b.dept_idgroup by a.user_name
[解决办法]
只有增加一个临时表,与工作表连接

热点排行
Bad Request.