求指点,多表数据的分组统计
各位高手,小弟想分组统计两张表里的数据,并在一个数据集里显示出来,但是分开定会,要怎么放到一个数据集里就不知道了,求各位高手指点,表结构如下:
表A
A_id cell_0 cell_1
1 1 1
2 2 2
3 5 5
表B
B_id cell_2
1 1
2 2
3 5
我想分组统计id大于1的 cell_0,cell_1,cell_2三列的总和
效果如下
ID cell_sum
2 6
3 15
------解决方案--------------------with a1 (A_id,cell_0,cell_1) as
(
select 1, 1, 1 union all
select 2, 2, 2 union all
select 3, 5, 5
)
,a2 (B_id,cell_2) as
(
select 1, 1 union all
select 2, 2 union all
select 3, 5
)
select a.a_id,sum(a.cell_0+a.cell_1+b.cell_2) cell_sum
from a1 a
inner join a2 b on a.a_id=b.b_id
where a.a_id>1
group by a.a_id
------解决方案--------------------
declare @表A table (A_id int,cell_0 int,cell_1 int)
insert into @表A
select 1,1,1 union all
select 2,2,2 union all
select 3,5,5
declare @表B table (B_id int,cell_2 int)
insert into @表B
select 1,1 union all
select 2,2 union all