我有这样的一张表userId     userName    money       roleId     roleName
(用户ID)  (用户名称) (拥有金钱) (所属角色ID) (所属角色名称)
  1         小明        100         1            一般用户
  2         小华     80        1            一般用户
  3         小李    120         2            高级用户
  4         小兰     50         2            高级用户
  5         小郑     75         3            管理员
  6         小朱        130        4            超级管理员要查询出这样的结果
请问sql改怎么写?  名称       统计
-------------------------
合计        555
一般用户    180
 小明        100
 小华        80
高级用户    170
 小李        120
 小兰        50
管理员      75
超级管理员  130请高手赐教!

解决方案 »

  1.   

    select '合计' name,sum(money) from tabname
    union all
    select s.name,s.money from 
    (
       select roleId,roleName name,sum(money) money,0 numb from tabname group by roleName,roleId
       union all
       select roleId,username, money,1 numb form tabname
    ) s order by s.roleId,s.numb
      

  2.   

    create table test(userId int, userName varchar2(100), money int, roleId int, roleName varchar2(100))
    insert into test 
    select 1,'小明',100,1,'一般用户' from dual
    union all
    select 2,'小华',80,1,'一般用户' from dual
    union all
    select 3,'小李',120,2,'高级用户' from dual
    union all
    select 4,'小兰',50,2,'高级用户' from dual
    union all
    select 5,'小郑',75,3,'管理员' from dual
    union all
    select 6,'小朱',130,4,'超级管理员' from dual;
    --执行sql
    select case when username is null then rolename else username end name,stat from
    (
    select 
    decode(rolename,null,'合计',rolename) rolename,username,sum(money) stat
    from (select * from test order by roleid asc)
    group by rollup(rolename,username)
    )t1
    order by rownum desc
    --Result
    1 合计 555
    2 一般用户 180
    3 小明 100
    4 小华 80
    5 管理员 75
    6 小郑 75
    7 高级用户 170
    8 小李 120
    9 小兰 50
    10 超级管理员 130
    11 小朱 130
      

  3.   

    --正确写法
    Select  name , money from 
    ( Select roleId,roleName name,sum(money) money,0 as numb 
        from test group by roleName,roleId
       union all
       select roleId,Username, sum(money) as Money,1 as numb 
        from test group by roleId,Username
       union all
       select 0 as roleId,'合计' as name,sum(money) as Money,
              2 as numb from test Order by roleId, numb  ) t
      

  4.   

    hongqi162(失踪的月亮) 强人呀,是不是搞数据库的?