当前位置: 代码迷 >> Sql Server >> 聚合函数的查询结果列怎么求和
  详细解决方案

聚合函数的查询结果列怎么求和

热度:78   发布时间:2016-04-27 11:51:34.0
聚合函数的查询结果列如何求和?
如下代码
SQL code
select ...,(b.quantity-isnull(sum(c.quantity),0))*b.unit_price as totalprice from table b left join table2 c on ... where ... group by ...


以上代码的查询结果 totalprice 列的值,需要全部值累加起来求和,如果不用另外写程序,只用sql语句就能一次性出来,可以吗?
效率和用程序totalprice+=的做法有区别吗?


------解决方案--------------------
可以,把你这句放到with里面,然后再select,大致如下:

with tablename as
(
你的select
)
select 你要的列, sum(totalprice) 
from tablename
group by你要的列
------解决方案--------------------
SQL code
WITH tb AS(select ...,(b.quantity-isnull(sum(c.quantity),0))*b.unit_price as totalprice from table b left join table2 c on ... where ... group by ...)SELECT SUM(totalprice )FROM tb
------解决方案--------------------
探讨
如下代码

SQL code

select ...,(b.quantity-isnull(sum(c.quantity),0))*b.unit_price as totalprice from table b left join table2 c on ... where ... group by ...



以上代码的查询结果 totalprice 列的值,需要全部值累加起来……

------解决方案--------------------
子查询算不算一次出来?
子查询与with类似了

另外,不使用group,直接sum就是你要的结果了
------解决方案--------------------
with是mssql2005才开始的,专有的
  相关解决方案