SqlServer_select-多次sum查询结果合并;

=>背景介绍

->tableSales表


->第一次查询(2013销售员销售总额)

select salesName, sum(extendedPrice) as sumprice13 from tableSales where salesTime between '2013-01-01' and '2013-12-31' group by salesName

->第二次查询(2014销售员销售总额)

select  salesName, sum(extendedPrice) as sumprice14 from tableSales where salesTime between '2014-01-01' and '2014-12-31' group by salesName

->如何获得销售员13、14年的销售总额?

A、首先,我想到的就是用union all,但不理想;

select salesName, sum(extendedPrice) as sumprice13, null as sumprice14 from tableSales where salesTime between '2013-01-01' and '2013-12-31' group by salesName
union all
select  salesName, null as sumprice13, sum(extendedPrice) as sumprice14 from tableSales where salesTime between '2014-01-01' and '2014-12-31' group by salesName

B最后,通过fredrickhu版主大大的指点,修改如下:

SELECT
    a.salesName, a.sumprice13, b.sumprice14
FROM
    (SELECT
        salesName, SUM(extendedPrice) AS sumprice13
     FROM
        tableSales
     WHERE
        salesTime BETWEEN '2013-01-01' AND '2013-12-31'
     GROUP BY
        salesName
      ) AS a
INNER JOIN
     (SELECT
        salesName, SUM(extendedPrice) AS sumprice14
      FROM
        tableSales
      WHERE
        salesTime BETWEEN '2014-01-01' AND '2014-12-31'
      GROUP BY
        salesName
      ) AS b
ON a.salesName=b.salesName
 

最后再次感谢fredrickhu大大!谢谢!..风雨兼程...


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值