请教SQL写法

[复制链接]
查看11 | 回复9 | 2012-1-4 11:56:44 | 显示全部楼层 |阅读模式
做报表遇到一个问题,假设我在写了一堆SQL之后得到下面这样的中间数据:
x 1
y 2
怎样让我的最终结果多加一行,达到效果如下:
x 1
y 2
合计 3


回复

使用道具 举报

千问 | 2012-1-4 11:56:44 | 显示全部楼层
select x,nun from a
union all
select '合计' x,sum(num) from a;
回复

使用道具 举报

千问 | 2012-1-4 11:56:44 | 显示全部楼层
with a as (select 'x' a,1 b from dual
union all select 'y',2 from dual)
select nvl(a.a,'合计'),sum(a.b) from a group by rollup(a)
回复

使用道具 举报

千问 | 2012-1-4 11:56:44 | 显示全部楼层
rollup
回复

使用道具 举报

千问 | 2012-1-4 11:56:44 | 显示全部楼层
homeworld80 发表于 2011-12-31 16:59
with a as (select 'x' a,1 b from dual
union all select 'y',2 from dual)
select nvl(a.a,'合计'),su ...



回复

使用道具 举报

千问 | 2012-1-4 11:56:44 | 显示全部楼层
regonly1 发表于 2011-12-31 17:22
rollup

或者cube
最后再decode一下grouping,就可以了
回复

使用道具 举报

千问 | 2012-1-4 11:56:44 | 显示全部楼层
homeworld80 发表于 2011-12-31 16:59
with a as (select 'x' a,1 b from dual
union all select 'y',2 from dual)
select nvl(a.a,'合计'),su ...

要用decode(grouping(a))更好,因为实际环境中,很多时候你不能保证a是没有null的
回复

使用道具 举报

千问 | 2012-1-4 11:56:44 | 显示全部楼层
就LZ那问题,rollup足矣,a没有null,就直接rollup
回复

使用道具 举报

千问 | 2012-1-4 11:56:44 | 显示全部楼层
dingjun123 发表于 2012-1-2 22:21
就LZ那问题,rollup足矣,a没有null,就直接rollup

那得看数据
还是给个通用的办法靠谱
回复

使用道具 举报

千问 | 2012-1-4 11:56:44 | 显示全部楼层
dingjun123 发表于 2012-1-2 22:21
就LZ那问题,rollup足矣,a没有null,就直接rollup

再问大侠个东西
with a as (select 'x' a, 'x2' c, 1 b from dual
union all select 'y', 'y2' c, 2 from dual)
select nvl(a.a,'合计'), a.c, sum(a.b) from a group by rollup(a, c);
1
x
x2
1
2
x
1
3
y
y2
2
4
y
2
5
合计
3
怎么把第二行和第四行去掉,我只要最后一行合计的,有专门的处理方法么
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行