我是蒻鸡 2021-12-18 19:43 采纳率: 39.1%
浏览 80
已结题

select跨表查询之分表汇总后联合显示数据如何处理?

img

对于数据的要求,请见上图,左侧为两个表,右侧为查询输出的语言,可能描述的混乱,我随时在线。

PS,感谢一楼的分析,能否提供一个在sqlitespy的解决方案,谢谢。

  • 写回答

1条回答 默认 最新

  • DarkAthena ORACLE应用及数据库设计方案咨询师 2021-12-18 20:39
    关注

    在两张表中都有可能关联数据缺失的情况下,如果要让数据不会由于关联而遗漏,需要使用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了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 12月26日
  • 已采纳回答 12月18日
  • 赞助了问题酬金 12月18日
  • 修改了问题 12月18日
  • 展开全部

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料