晚上被一个类似树型结构的查询语句困扰 终于解决了。不过好象查询的效率不是很高
问题可以被抽象为求每个 hetongid 中的B的和 、D的和
/*************************设计的测试表*****************************/
create table t( hetongid char(20), A int, B int ,D int )
insert into t values ( '公司1',1 ,100 ,1 )insert into t values ( '公司1',1 ,100 ,2 )insert into t values ( '公司1',1 ,100 ,22 )insert into t values ( '公司1',1 ,100 ,23 )
insert into t values ( '公司1',2 ,100 ,5 )insert into t values ( '公司1',2 ,100 ,6 )
insert into t values ( '公司1',3 ,200 ,3 )insert into t values ( '公司1',3 ,200 ,4 )
insert into t values ( '公司2',4 ,300 ,1 )insert into t values ( '公司2',4 ,300 ,2 )insert into t values ( '公司2',4 ,300 ,22 )insert into t values ( '公司2',4 ,300 ,23 )
insert into t values ( '公司2',5 ,200 ,3 )insert into t values ( '公司2',5 ,200 ,4 )
insert into t values ( '公司2',6 ,100 ,5 )insert into t values ( '公司2',6 ,100 ,6 )
select * from t
/************************表的格式***********************/
hetongid A B D
公司1 1 100 1公司1 1 100 2公司1 1 100 22公司1 1 100 23公司1 2 100 5公司1 2 100 6公司1 3 200 3公司1 3 200 4公司2 4 300 1公司2 4 300 2公司2 4 300 22公司2 4 300 23公司2 5 200 3公司2 5 200 4公司2 6 100 5公司2 6 100 6
/********************错误的语句*********************************/select * from tselect hetongid, sum( distinct (B)),SUM(D) from tGROUP BY hetongid,A
/***************正确的语句*************/
select * from t
select a.hetongid, sum(a.b),SUM(a.d) from ( select hetongid, sum( distinct (B)) as b,SUM(D) as d from t group by hetongid, A ) a GROUP BY hetongid
/*****************结果*********************/
公司1 400 66
公司2 600 66
如果有更好的办法 请指点指点。
