34,590
社区成员
发帖
与我相关
我的任务
分享
drop table tb
CREATE TABLE tb
(
deptid INT ,
subdeptid INT ,
amount DECIMAL
)
INSERT INTO tb SELECT 1,NULL ,100 UNION ALL
SELECT 2, NULL ,200 UNION ALL
SELECT 3, 1, 500 UNION ALL
SELECT 4, 1 , 600 UNION ALL
SELECT 5, 2 , 300 UNION ALL
SELECT 6, 2 , 400
select a.deptid,(a.amount+b.amount) amount from
(select deptid,sum(amount)amount from tb
where subdeptid is null
group by deptid) a join
(select subdeptid,SUM(amount) amount from tb
where subdeptid is not null
group by subdeptid) b
on a.deptid=b.subdeptid
deptid amount
----------- ---------------------------------------
1 1200
2 900
(2 行受影响)
CREATE TABLE tb
(
deptid INT ,
subdeptid INT ,
amount DECIMAL
)
INSERT INTO tb SELECT 1,NULL ,100 UNION ALL
SELECT 2, NULL ,200 UNION ALL
SELECT 3, 1, 500 UNION ALL
SELECT 4, 1 , 600 UNION ALL
SELECT 5, 2 , 300 UNION ALL
SELECT 6, 2 , 400
select * from tb
;with liang as
(
select *,typeid = deptid from tb where subdeptid is null
union all
select a.*,typeid = b.typeid from tb a ,liang b where a.subdeptid = b.deptid
)
select typeid,sum(amount) as amount from liang group by typeid
CREATE TABLE tb
(
deptid INT ,
subdeptid INT ,
amount DECIMAL
)
INSERT INTO tb SELECT 1,NULL ,100 UNION ALL
SELECT 2, NULL ,200 UNION ALL
SELECT 3, 1, 500 UNION ALL
SELECT 4, 1 , 600 UNION ALL
SELECT 5, 2 , 300 UNION ALL
SELECT 6, 2 , 400
select * from tb
with liang as
(
select *,typeid = deptid from tb where subdeptid is null
union all
select a.*,typeid = b.typeid from tb a ,liang b where a.subdeptid = b.deptid
)
select typeid,sum(amount) as amount from liang group by typeid