表a:
xmbm clbm jghj
14880201 1488020110000001 400.00
14880201 1488020110000003 300.00
14880202 1488020210000001 120.00
表b:
xmbm sbbm jghj
14880201 1488020110000001 200.00
14880201 1488020110000002 900.00clbm和sbbm的左边8位就是xmbm。
我现在想把表a中,xmbm相同的记录的jghj 求和,作为jh1,把表b中,xmbm相同的记录求和,作为jh2,然后把jh1和jh2求和作为jh(条件:xmbm相同)。
输出如下:
xmbm jh
14880201 1800
14880202 120其中,jh=1800=400+300+200+900
请问SQl语句怎么写呢?
xmbm clbm jghj
14880201 1488020110000001 400.00
14880201 1488020110000003 300.00
14880202 1488020210000001 120.00
表b:
xmbm sbbm jghj
14880201 1488020110000001 200.00
14880201 1488020110000002 900.00clbm和sbbm的左边8位就是xmbm。
我现在想把表a中,xmbm相同的记录的jghj 求和,作为jh1,把表b中,xmbm相同的记录求和,作为jh2,然后把jh1和jh2求和作为jh(条件:xmbm相同)。
输出如下:
xmbm jh
14880201 1800
14880202 120其中,jh=1800=400+300+200+900
请问SQl语句怎么写呢?
(select xmbm,jghj from 表a
union all
select xmbm,jghj from 表b)group by xmbm
表a:
xmbm clbm jghj
14880201 1488020110000001 400.00
14880201 1488020110000003 300.00
14880202 1488020210000001 120.00
表b:
xmbm sbbm hj
14880201 1488020110000001 200.00
14880201 1488020110000002 900.00clbm和sbbm的左边8位就是xmbm。
我现在想把表a中,xmbm相同的记录的jghj 求和,作为jh1,把表b中,xmbm相同的记录的hj求和,作为jh2,然后把jh1和jh2求和作为jh(条件:xmbm相同)。
输出如下:
xmbm jh
14880201 1800
14880202 120其中,jh=1800=400+300+200+900
请问SQl语句怎么写呢?
declare @a table(xmbm varchar(20),clbm varchar(50),jghj decimal(18,2))
insert into @a
select '14880201','1488020110000001',400.00 union all
select '14880201','1488020110000003',300.00 union all
select '14880202','1488020210000001',120.00
declare @b table(xmbm varchar(20),clbm varchar(50),jghj decimal(18,2))
insert into @b
select '14880201','1488020110000001', 200.00 union all
select '14880201','1488020110000002', 900.00select a.xmbm,jh=jh1+jh2 from
(select sum(jghj) as jh1,xmbm from @a group by xmbm) a
inner join
(select sum(jghj) as jh2,xmbm from @b group by xmbm) b
on a.xmbm=b.xmbm/*
xmbm jh
------ --------
14880201 1800.00
*/
declare @a table(xmbm varchar(20),clbm varchar(50),jghj decimal(18,2))
insert into @a
select '14880201','1488020110000001',400.00 union all
select '14880201','1488020110000003',300.00 union all
select '14880202','1488020210000001',120.00
declare @b table(xmbm varchar(20),clbm varchar(50),jghj decimal(18,2))
insert into @b
select '14880201','1488020110000001', 200.00 union all
select '14880201','1488020110000002', 900.00select a.xmbm,jh=isnull(jh1,0)+isnull(jh2,0) from
(select sum(jghj) as jh1,xmbm from @a group by xmbm) a
full join
(select sum(jghj) as jh2,xmbm from @b group by xmbm) b
on a.xmbm=b.xmbm
/*
xmbm jh
----------- --------
14880201 1800.00
14880202 120.00
*/
select a.xmbm,sum(jh) from
(select xmbm,sum(jghj) as jh from jh1 group by xmbm
union all
select xmbm,sum(jghj) as jh from jh2 group by xmbm)
a group by xmbmselect a.xmbm,sum(jghj) from (select * from jh1 union select * from jh2) a
group by a.xmbm