当前位置: 代码迷 >> Sql Server >> Sql联合查询跟计算
  详细解决方案

Sql联合查询跟计算

热度:5   发布时间:2016-04-24 18:39:47.0
Sql联合查询和计算
SELECT  Smsname,
       grade ,
        depname ,
        zyname ,
        pubnum ,
        pbname ,
        pbprice ,
        pbdiscount ,
        SUM(enum) enum,
        SUM(eprice) eprice
FROM  A
GROUP BY
        Smsname, 
        grade ,
        depname ,
        zyname ,
        pubnum ,
        pbname ,
        pbprice ,
        pbdiscount

上面是表A查询

下面是表B查询
SELECT Smsname,
       grade ,
        depname ,
        zyname ,
        pubnum ,
        pbname ,
        pbprice ,
        pbdiscount ,
        Escount,
        Esdsum
  FROM B


我要联合这两个表,B为主表并且需求:
(B.Escount - A.SUM(enum) enum ) as Dnum 
(B.Esdsum  - A.SUM(eprice) eprice) as Dprice
如何来写SQL语句?

------解决方案--------------------

select b.Smsname,
       b.grade,
       b.depname,
       b.zyname,
       b.pubnum,
       b.pbname,
       b.pbprice,
       b.pbdiscount,
       (b.Escount-isnull(a.enum,0)) as Dnum, 
       (b.Esdsum-isnull(a.eprice,0)) as Dprice
from
(select Smsname,
        grade,
        depname,
        zyname,
        pubnum,
        pbname,
        pbprice,
        pbdiscount,
        Escount,
        Esdsum
  FROM B) b
left join
(select Smsname,
        grade,
        depname,
        zyname,
        pubnum,
        pbname,
        pbprice,
        pbdiscount,
        SUM(enum) enum,
        SUM(eprice) eprice
 from A
 group by
        Smsname, 
        grade,
        depname,
        zyname,
        pubnum,
        pbname,
        pbprice,
        pbdiscount) a 
on b.Smsname=a.Smsname and b.grade=a.grade and b.depname=a.depname
and b.zyname=a.zyname and b.pubnum=a.pubnum and b.pbname=a.pbname
and b.pbprice=a.pbprice and b.pbdiscount=a.pbdiscount
  相关解决方案