码迷,mamicode.com
首页 > 数据库 > 详细

Sql使用WITH ROLLUP 进行分类汇总及小计功能

时间:2015-10-08 18:22:50      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:

效果如下:
技术分享
测试代码如下:
CREATE TABLE #test
    (
      Name VARCHAR(10) ,
      [procedure] CHAR(1) ,
      model VARCHAR(5) ,
      quantity INT
    );

INSERT  INTO #test
        SELECT  ‘A‘ ,
                ‘1‘ ,
                ‘φ50‘ ,
                500
        UNION ALL
        SELECT  ‘A‘ ,
                ‘1‘ ,
                ‘φ50‘ ,
                600
        UNION ALL
        SELECT  ‘A‘ ,
                ‘1‘ ,
                ‘φ100‘ ,
                500
        UNION ALL
        SELECT  ‘A‘ ,
                ‘2‘ ,
                ‘φ50‘ ,
                700
        UNION ALL
        SELECT  ‘A‘ ,
                ‘2‘ ,
                ‘φ100‘ ,
                200
        UNION ALL
        SELECT  ‘B‘ ,
                ‘1‘ ,
                ‘φ50‘ ,
                1000;

SELECT  CASE WHEN GROUPING(Name) = 1 THEN ‘总计‘
             WHEN GROUPING(Name) = 0
                  AND GROUPING([procedure]) = 1 THEN Name + ‘合计‘
             WHEN GROUPING(Name) = 0
                  AND GROUPING([procedure]) = 0
                  AND GROUPING([model]) = 1
             THEN Name + ‘的‘ + [procedure] + ‘小计‘
             ELSE Name
        END AS Name ,
        CASE WHEN GROUPING([model]) = 1 THEN ‘‘
             ELSE [procedure]
        END AS [procedure] ,
        ISNULL(model, ‘‘) AS model ,
        SUM(quantity) AS quantity
FROM    #test
GROUP BY Name ,
        [procedure] ,
        model
        WITH ROLLUP;

DROP TABLE #test;

版权声明:本文为博主原创文章,未经博主允许不得转载。

Sql使用WITH ROLLUP 进行分类汇总及小计功能

标签:

原文地址:http://blog.csdn.net/greystar/article/details/48973599

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!