读书人

一个sql server 查询解决方案

发布时间: 2013-01-11 11:57:35 作者: rapoo

一个sql server 查询
如果有这么三张表:
1、表jglx: 字段 id jglx ……
1 平开窗 ……
2 推拉窗 ……
3 平开门 ……
…… …… ……

表1 jglx 中的记录为表2 jgmx 中的字段名
2、表jgmx: 字段 id gcmc zzlh 平开窗 推拉窗 平开门 dates ……
1 15 T80 10 null 15 2010-5-9 ……
2 15 T81 20 null null 2010-1-6 ……
3 16 T90 NULL 10 NULL 2010-9-10 ……
4 16 T91 null null 10 2010-10-11 ……
5 17 T70

NULL NULL NULL 2010-10-15 ……
…… …… …… …… …… …… ……
为表gcmc的id ** 数字为所对应的数量

3、表gcmc: 字段 id gcmc rq ……
1 test 2010-5-9 ……
…… …… 2011-1-5 ……
15 名称 2010-6-18 ……
16 名称2 2010-8-10 ……
17 名称3 2010-7-9 ……
…… ……

求一查询语句:要就得到表3 gcmc 中 的 id 与 gcmc 内容集。条件为,表3中rq在2010年 及 表2字段中有表1(jglx)内容的列不为空或0(如,平开窗不能为null、空或0)。

也就是。通过表1 jglx 求得 表2 的gcmc 值,再根据表3 的rq,求得最后的,id与gcmc

请哪位大虾帮帮忙!
[解决办法]

create table jglx
(
id int identity,
jglx nvarchar(100)
)
insert into jglx(jglx)
select N'平开窗' union all
select N'推拉窗' union all
select N'平开门'

create table jgmx
(
id int identity,
gcmc int,
zzlh varchar(100),
平开窗 int,
推拉窗 int,
平开门 int,
dates datetime
)
insert into jgmx(gcmc, zzlh, 平开窗, 推拉窗, 平开门, dates)
select 15, 'T80', 10, null, 15, '2010-5-9' union all


select 15, 'T81', 20, null, null, '2010-1-6' union all
select 16, 'T90', null, 10, null, '2010-9-10' union all
select 16, 'T91', null, null, 10, '2010-10-11' union all
select 17, 'T70', null, null, null, '2010-10-15'

create table gcmc
(
id int identity,
gcmc nvarchar(100),
rq datetime
)
insert into gcmc(gcmc, rq)
select 'test1', '2010-5-9' union all
select 'test2', '2011-1-5' union all
select 'test3', '2010-6-18' union all
select 'test4', '2010-8-10' union all
select 'test5', '2010-7-9'

--select * from jglx
--select * from jgmx
--select * from gcmc

declare @sql nvarchar(4000)
set @sql = N' where 1 <> 1 '

select @sql = @sql + N' or isnull(' + Name + N', 0) <> 0' from
(select Name from SysColumns Where id=Object_Id('jgmx') and Name in (select jglx from jglx)) a

set @sql = N'select distinct gcmc from jgmx ' + @sql
set @sql = N'select c.id, c.gcmc from gcmc c inner join (' + @sql + N') b on c.id = b.gcmc and (c.rq >= ''2010-1-1'' and c.rq < ''2011-1-1'')'
exec(@sql)

读书人网 >SQL Server

热点推荐