- Rongsen.Com.Cn 版权所有 2008-2010 京ICP备08007000号 京公海网安备11010802026356号 朝阳网安编号:110105199号
- 北京黑客防线网安工作室-黑客防线网安服务器维护基地为您提供专业的服务器维护,企业网站维护,网站维护服务
- (建议采用1024×768分辨率,以达到最佳视觉效果) Powered by 黑客防线网安 ©2009-2010 www.rongsen.com.cn
 
  
    
| 作者:黑客防线网安SQL维护基地 来源:黑客防线网安SQL维护基地 浏览次数:0 | 
中间一层的子查询如下:
select  a.xh, ( select    sum (price)  from  t_product b  where  b.xh  <  a.xh)   as  totalprice , a.price
from  t_product a
最外面一层当然就是整个select 语句了。
如果读者不喜欢写太长的SQL ,可以将部分内容写到函数里,代码如下:
create  function  mysum( @xh  int ,  @price  int )  returns  int 
begin 
   return  ( select  
          ( case  when  totalprice  is  null  then  @price    else  totalprice  end )  as  totalprice 
          from  (  select    sum (price)  as  totalprice  from  t_product  where  xh  <  @xh ) x)
end 
可使用下面的SQL 语句来使用这个函数:
select  xh, price, dbo.mysum(xh, price)   as  totalprice
from  t_product
在执行上面的SQL 后,将得出如图3 所示的查询结果。
建立t_product 表的SQL 语句(SQL Server 2005 )如下:
SET  ANSI_NULLS  ON 
GO 
SET  QUOTED_IDENTIFIER  ON 
GO 
IF  NOT  EXISTS  ( SELECT  *  FROM  sys.objects  WHERE  object_id  =  OBJECT_ID (N ' [dbo].[t_product] ' )  AND  type  in  (N ' U ' ))
BEGIN 
CREATE  TABLE  [ dbo ] . [ t_product ] (
     [ xh ]  [ int ]  NOT  NULL ,
     [ price ]  [ int ]  NOT  NULL ,
  CONSTRAINT  [ PK_t_product ]  PRIMARY  KEY  CLUSTERED  
(
     [ xh ]  ASC 
) WITH  (IGNORE_DUP_KEY  =  OFF )  ON  [ PRIMARY ] 
)  ON  [ PRIMARY ] 
END
| 我要申请本站:N点 | 黑客防线官网 | | 
| 专业服务器维护及网站维护手工安全搭建环境,网站安全加固服务。黑客防线网安服务器维护基地招商进行中!QQ:29769479 |