union all 和 group by 的顺序问题
通过三个实验,来看 union all 及 group by 不同的使用顺序对CPU时间及耗时的影响
1. 先Union All, 再Group By
select inctmid ctmid,cnlid,inwhsid whsid,sum(qty) qty,goodsid
from
( select inctmid,cnlid,inwhsid,qty,goodsid
from DtrBill a,DtrDetail b
where a.billno=b.billno
union all
select inctmid,cnlid,inwhsid,-1*qty qty,goodsid
from DtrBillRet a,DtrDetailRet b
where a.billno=b.billno
)a
group by inctmid,cnlid,inwhsid,goodsid
2. 分别Group By,再Union All,再Group By
select inctmid ctmid,cnlid,inwhsid whsid,sum(qty) qty,goodsid
from
( select inctmid,cnlid,inwhsid,sum(qty) qty,goodsid
from DtrBill a,DtrDetail b
where a.billno=b.billno
group by inctmid,cnlid,inwhsid,goodsid
union all
select inctmid,cnlid,inwhsid,sum(-1*qty) qty,goodsid
from DtrBillRet a,DtrDetailRet b
where a.billno=b.billno
group by inctmid,cnlid,inwhsid,goodsid
)a
group by inctmid,cnlid,inwhsid,goodsid
3. 先Group By,再Union
select inctmid,cnlid,inwhsid,sum(qty) qty,goodsid
from DtrBill a,DtrDetail b
where a.billno=b.billno
group by inctmid,cnlid,inwhsid,goodsid
union
select inctmid,cnlid,inwhsid,sum(-1*qty) qty,goodsid
from DtrBillRet a,DtrDetailRet b
where a.billno=b.billno
group by inctmid,cnlid,inwhsid,goodsid