日期:2014-05-18  浏览次数:20683 次

一复杂SQL求写法,谢谢大家了!!!!
先讲表结构并给出示例数据:
1、gsm_config_cert_type
字段名 字段类型
fd_id int 主键
fd_name varchar(200) 
数据:
1 tx1
2 tx2
3 tx3
2、gsm_config_cert_org
字段名 字段类型
fd_id int 主键
fd_name varchar(200)
数据:
1 jg1
2 jg2
3 jg3
3、gsm_pm_staff
字段名 字段类型
fd_id int 主键
fd_name varchar(200) 
数据:
1 张三
2 李四
3 王五
4 马六
4、gsm_config_cert_range
字段名 字段类型
fd_id int 主键
fd_code varchar(200)
fd_order int (排序号)
fd_org_id int 外键 指向gsm_config_cert_org
fd_type_id int 外键 指向gsm_config_cert_type
fd_parent_id int 外键 指向自身
数据:
1 01 1 1 1 NULL
2 01 2 1 2 NULL
3 01 3 2 1 NULL
4 01 4 2 2 NULL
5 01.01.01 103 1 1 1
6 01.18.02 104 1 1 1
7 17.11.23 105 1 1 1
8 01.01.01 106 1 2 2
9 01.17.14 107 1 2 2
10 01.02.03 108 1 2 2
11 19.00.03 109 2 1 3
12 19.01.01 110 2 1 3
13 14.01.03 111 2 1 3
14 14.02.04 112 2 1 3
5、gsm_pm_assessor
字段名 字段类型
fd_id int
fd_code varchar(8000)
fd_person_id int 外键 指向gsm_pm_staff
fd_type_id int 外键 指向gsm_config_cert_type
fd_org_id int 外键 指向gsm_config_cert_org
数据:
1 01.01.01;01.18.02 1 1 1 
2 01.01.01;17.11.23 2 1 1
3 01.01.01;01.18.02;17.11.23 3 1 1
4 01.01.01 1 1 2
5 01.17.14;01.01.01 3 1 2 
6 01.02.03;01.17.14 2 1 2 
7 19.00.03;14.01.03;14.02.04 4 2 1
8 14.01.03;14.02.04 3 2 1
9 14.01.03;14.02.04 2 2 1
10 19.01.01 2 2 1

我想要得到的查询数据是:
代码 体系 机构 人员 人数
01.01.01 tx1 jg1 张三;李四;王五 3
01.18.02 tx1 jg1 张三;王五 2
17.11.23 tx1 jg1 李四;王五 2
01.01.01 tx1 jg2 张三;王五 2
01.17.14 tx1 jg2 王五;李四 2
01.02.03 tx1 jg2 李四 1
19.00.03 tx2 jg1 马六 1
19.01.01 tx2 jg1 李四 1
14.01.03 tx2 jg1 马六;王五;李四 3
14.02.04 tx2 jg1 马六;王五;李四 3
希望我把这个结构写清楚了,请各位高手帮帮写一下,能到处到EXCEL最好了,谢谢大家!!!

------解决方案--------------------
就是多表连查 ,然后列值拆分
SQL code

--提供测试数据
declare @gsm_config_cert_type table 
(fd_id int,fd_name varchar(3))
insert into @gsm_config_cert_type
select 1,'tx1' union all
select 2,'tx2' union all
select 3,'tx3'

declare @gsm_config_cert_org table 
(fd_id int,fd_name varchar(3))
insert into @gsm_config_cert_org
select 1,'jg1' union all
select 2,'jg2' union all
select 3,'jg3'

declare @gsm_pm_staff table 
(fd_id int,fd_name varchar(4))
insert into @gsm_pm_staff
select 1,'张三' union all
select 2,'李四' union all
select 3,'王五' union all
select 4,'马六'

declare @gsm_config_cert_range table 
(fd_id int,fd_code varchar(8),fd_order int,fd_org_id int,fd_type_id int,fd_parent_id int)
insert into @gsm_config_cert_range
select 1,'01',1,1,1,null union all
select 2,'01',2,1,2,null union all
select 3,'01',3,2,1,null union all
select 4,'01',4,2,2,null union all
select 5,'01.01.01',103,1,1,1 union all
select 6,'01.18.02',104,1,1,1 union all
select 7,'17.11.23',105,1,1,1 union all
select 8,'01.01.01',106,1,2,2 union all
select 9,'01.17.14',107,1,2,2 union all
select 10,'01.02.03',108,1,2,2 union all
select 11,'19.00.03',109,2,1,3 union all
select 12,'19.01.01',110,2,1,3 union all
select 13,'14.01.03',111,2,1,3 union all
sele