sql 分组问题
我要根据来源和类型查询数据,查询的数据和图一样 sql
[解决办法]
用rollup实现,
参考 http://www.cnblogs.com/gaiyang/archive/2011/04/17/2018645.html
[解决办法]
。。。
第一个 t 是我的测试数据, 里面的所有行,换成你的真实表查询就行了
我说的 union all 只是指
,tt as (
select * from t1 union all
select * from t2 where g1=1 and g2=0
)
with t as (
select 名称 as 来源, 类型, 数据 from 你的表
)
,t1 as (
select GROUPING(来源) g1,GROUPING(类型) g2
,case GROUPING(来源) when 1 then '合计' else 来源 end 来源
,case GROUPING(类型) when 1 then '小计' else 类型 end 类型
,SUM(数据) 数据
from t
group by 来源,类型
with rollup
)
,t2 as (
select GROUPING(来源) g1,GROUPING(类型) g2
,case GROUPING(来源) when 1 then '合计' else 来源 end 来源
,case GROUPING(类型) when 1 then '小计' else 类型 end 类型
,SUM(数据) 数据
from t
group by 来源,类型
with cube
)
,tt as (
select * from t1 union all
select * from t2 where g1=1 and g2=0
)
select 来源,类型,数据
from tt
order by g1 desc,来源,g2 desc ,类型