SQL一次性查询一个字段不同条件下的统计结果

参考了一下这篇文章:https://blog.csdn.net/xichenguan/article/details/51764100 , 感谢原作者

有两个表,分别存放了【操作员】和【单据】,要根据单据的不同类型来分类汇总(销售单、销售退货单,笔数和金额),并且显示在同一张表里,不想用做两次查询再合并的方法,研究了一下,终于搞定:

d_employee表

d_bilndx表

代码如下:

select  b.inputid as 开单员编号, 
        e.fullname as 开单员, 

        isnull( ( select count(*)
          from d_bilndx
          where draft=3 and biltype=12 and d_bilndx.inputid=e.id
        ), 0) as '销售开单笔数',

        isnull( ( select sum(d_bilndx.amount)
          from d_bilndx
          where draft=3 and biltype=12 and d_bilndx.inputid=e.id
        ), 0) as '销售开单金额',

        isnull( ( select count(*)
          from d_bilndx
          where draft=3 and biltype=13 and d_bilndx.inputid=e.id
        ), 0) as '销售退单笔数',

        isnull( ( select sum(d_bilndx.amount)
          from d_bilndx
          where draft=3 and biltype=13 and d_bilndx.inputid=e.id
        ), 0) as '销售退单金额',

        count(b.biltype) as 开单总笔数,
        sum(b.Amount) as 开单金额

from d_bilndx as b
left join d_employee as e 
on b.inputid=e.id 
where b.draft=3 and ( b.biltype=12 or b.biltype=13 )
group by b.inputid, e.fullname, e.id

得到完美结果:

猜你喜欢

转载自www.cnblogs.com/skysowe/p/9117099.html