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

使用ROLLUP遇到的问题
SQL code

SQL语句:
  SELECT case when (grouping(data0010.cust_code)=1) then '合计:'
       else isnull(data0010.cust_code,'unknown') end  客户代码,--Data0010.abbr_name 客户简称, 
    sum(Data0060.parts_ordered) as 数量,
    sum(Data0060.sq)  AS 面积
  from data0060 inner join DATA0010 on DATA0060.CUSTOMER_PTR=DATA0010.RKEY
 group by 
    data0010.cust_code with rollup  --,Data0010.abbr_name 
ORDER BY
    data0010.cust_code desc
得到结果:

客户代码       数量                     面积
---------- ---------------------- ----------------------
SUNSZ      300                    16.535526
NCASE      19040                  3935.9965624
NCAGB      17560                  3683.5445024
MTPZZ      30720                  1159.65696
INTZZ      3426                   1361.16867256
HPCIS      30240                  141.665328
HHNJX      98                     3.42099282
HESNZ      2320                   390.0781184
HENHZ      2000                   66.41342
CGDPY      9000                   1437.9912
ASEZZ      265400                 5369.934796
ADMZZ      3000                   291.65085
合计:        383104                 17858.05692858

-----
现在想增加 DATA0010 表的 RKEY列和 abbr_name (客户名称)列,使结果为:
rkey        客户代码       客户简称                 数量                     面积
----------- ---------- -------------------- ---------------------- ----------------------
58          SUNSZ      S1012                300                    16.535526
113         NCASE      N1010                19040                  3935.9965624
117         NCAGB      N1011                17560                  3683.5445024
48          MTPZZ      M1013                30720                  1159.65696
35          INTZZ      I1004                3426                   1361.16867256
69          HPCIS      H1019                30240                  141.665328
127         HHNJX      H1024                98                     3.42099282
26          HESNZ      H1009                2320                   390.0781184
25          HENHZ      H1005                2000                   66.41342
109         CGDPY      C1022                9000                   1437.9912
3           ASEZZ      A1020                265400                 5369.934796
1           ADMZZ      A1002                3000                   291.65085
            合计:                        383104                 17858.05692858
请问用rollup,cube 等如何实现?






------解决方案--------------------
SQL code

;with ach as
(
  SELECT case when (grouping(data0010.cust_code)=1) then '合计:'
       else isnull(data0010.cust_code,'unknown') end  客户代码,--Data0010.abbr_name 客户简称, 
    sum(Data0060.parts_ordered) as 数量,
    sum(Data0060.sq)  AS 面积
  from data0060 inner join DATA0010 on DATA0060.CUSTOMER_PTR=DATA0010.RKEY
 group by 
    data0010.cust_code with rollup  --,Data0010.abbr_name 
ORDER BY
    data0010.cust_code desc

)

select a.*,b.[RKEY],b.[abbr_name]
from ach a left join DATA0010 b on a.客户代码 = b.客户代码