日期:2014-05-18  浏览次数:20372 次

聚合函数的查询结果列如何求和?
如下代码
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才开始的,专有的