对于数据的要求,请见上图,左侧为两个表,右侧为查询输出的语言,可能描述的混乱,我随时在线。
PS,感谢一楼的分析,能否提供一个在sqlitespy的解决方案,谢谢。
对于数据的要求,请见上图,左侧为两个表,右侧为查询输出的语言,可能描述的混乱,我随时在线。
PS,感谢一楼的分析,能否提供一个在sqlitespy的解决方案,谢谢。
在两张表中都有可能关联数据缺失的情况下,如果要让数据不会由于关联而遗漏,需要使用full join,并且对select的字段做判断为空的处理,另外就是对除数为0的处理。
以下是在oracle数据库中的写法,其他数据库可能有些函数名不一样,但思路都是一样的
select nvl(a.id, b.id) id,
sum(nvl(a.numb, 0)) yonggongshu,
sum(nvl(b.numb, 0)) zichanshu,
decode(sum(nvl(a.numb, 0)),
0,
null,
sum(nvl(b.numb, 0)) / sum(nvl(a.numb, 0))) pinjun
from (select * from book1 a where a.leibie in ('中层', '临时工')) a
full join (select * from book2 b where b.zichan in ('房屋', '门面')) b
on a.id = b.id
group by nvl(a.id, b.id)
我手上目前没有sqlite,关于full join 的替代方式可以在网上搜一下,当然针对你这个问题有另外一种方式,无需join
select id,
sum(case when t= 'book1' then sum_numb else 0 end ) yonggongshu,
sum(case when t= 'book2' then sum_numb else 0 end) zichanshu,
case
when
sum(case when t= 'book2' then sum_numb else 0 end)=0 then null
else
sum(case when t= 'book1' then sum_numb else 0 end) /
sum(case when t= 'book2' then sum_numb else 0 end)
end pinjun
from (select id, 'book1' t, sum(numb) sum_numb
from book1 a
where a.leibie in ('中层', '临时工')
group by id
union all
select id, 'book2' t, sum(numb) sum_numb
from book2 b
where b.zichan in ('中层', '临时工')
group by id)
group by id
搜了下,sqlite好像不支持decode,所以改成case when了