Tsql统计之二(实例详解grouping() case设置合计字段)

grouping()函数:grouping(字段)=1则对字段进行了合计,grouping(字段)=0则此行没有对字段合计,

根据这个特性我们可以控件要显示的统计列表,例子如下:

 

ExpandedBlockStart.gif View Code
  DROP   TABLE   [ product ]  
 
CREATE   TABLE   [ product ]  (  [ proid ]   [ varchar ]  ( 5 NULL  ,  [ in_date ]   [ varchar ]  ( 10 NULL  ,   [ qty ]   [ int ]   NULL  )

 
INSERT   [ product ]  (  [ proid ]  ,  [ in_date ]  ,  [ qty ]  )  VALUES  (  ' 1 '  ,  ' 2004-1-2 '  ,  10  )
 
INSERT   [ product ]  (  [ proid ]  ,  [ in_date ]  ,  [ qty ]  )  VALUES  (  ' 2 '  ,  ' 2004-1-3 '  ,  13  )
 
INSERT   [ product ]  (  [ proid ]  ,  [ in_date ]  ,  [ qty ]  )  VALUES  (  ' 3 '  ,  ' 2004-1-4 '  ,  10  )
 
INSERT   [ product ]  (  [ proid ]  ,  [ in_date ]  ,  [ qty ]  )  VALUES  (  ' 4 '  ,  ' 2004-1-4 '  ,  13  )
 
INSERT   [ product ]  (  [ proid ]  ,  [ in_date ]  ,  [ qty ]  )  VALUES  (  ' 5 '  ,  ' 2004-1-5 '  ,  14  )
 
INSERT   [ product ]  (  [ proid ]  ,  [ in_date ]  ,  [ qty ]  )  VALUES  (  ' 6 '  ,  ' 2004-1-6 '  ,  15  )
 
INSERT   [ product ]  (  [ proid ]  ,  [ in_date ]  ,  [ qty ]  )  VALUES  (  ' 7 '  ,  ' 2004-1-7 '  ,  63  )
 
INSERT   [ product ]  (  [ proid ]  ,  [ in_date ]  ,  [ qty ]  )  VALUES  (  ' 8 '  ,  ' 2004-1-8 '  ,  43  )
 
INSERT   [ product ]  (  [ proid ]  ,  [ in_date ]  ,  [ qty ]  )  VALUES  (  ' 3 '  ,  ' 2004-1-4 '  ,  10  )
 
INSERT   [ product ]  (  [ proid ]  ,  [ in_date ]  ,  [ qty ]  )  VALUES  (  ' 4 '  ,  ' 2004-1-4 '  ,  13  )
 
INSERT   [ product ]  (  [ proid ]  ,  [ in_date ]  ,  [ qty ]  )  VALUES  (  ' 5 '  ,  ' 2004-1-5 '  ,  14  )
 
INSERT   [ product ]  (  [ proid ]  ,  [ in_date ]  ,  [ qty ]  )  VALUES  (  ' 3 '  ,  ' 2004-1-5 '  ,  10

 

思路分析:先写出最原始的查询,然后根据需要判断grouping(字段)和用case 显示字段值

 

ExpandedBlockStart.gif View Code
select  
case   grouping (proid)  when   1   then   ' 合计 '   -- 在这里处理字符显示 
     when   0   then   case   grouping (in_date) 
                
when   1   then  proid + ' 小计 '
                
when   0   then  proid
    
end  
end  
proid,in_date,
sum (qty)  ' 数量 ' , grouping (proid)  as   ' gpProid ' ,
grouping (in_date)  as   ' gpIn_date '
from  product 
group   by  proid,in_date  with  rollup

having   grouping (proid) + grouping (in_date) = 0 -- 显示常规的sum值,没有合计
or   grouping (proid) + grouping (in_date) = 1
or   grouping (proid) + grouping (in_date) = 2    -- 按proid,in_date总计
order   by  proid   -- 只有按proid,in_date的sum(qty)合计

 

转载于:https://www.cnblogs.com/gaiyang/archive/2011/04/17/2018833.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值