sql 难题

贪玩的老鼠 2009-02-14 02:05:13
有表
table1(a int ,b char(10),c char (10),d char(10) )
数据
1 , "天津","上海“,"北京"
2,"湖南","广东","香港"
---------------
table2(int a,b char)
100,'d'
100,'b'
101,'d'
101,'b'
101,'c'
我要的结果是,通过table2中a字段的字找出table1中的列,在根据table1中字段a过滤
比如 我要查找table1表中a=1 且table2中a字段为a=100的结果输出如下:
"天津"
"北京"
我要查找table1表中a=2 且table2中a字段为a=101的结果输出如下:
"湖南"
"广东"
"香港"
最后不用临时表和游标
...全文
55 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2009-02-15
  • 打赏
  • 举报
回复
我要查找table1表中a=1 且table2中a字段为a=100的结果输出如下:
"天津"
"北京"

select m.* from table1 m , table2 n where m.a = 1 and n.a = 100 and (m.b = n.b or m.c = n.c and m.d = n.d)


我要查找table1表中a=2 且table2中a字段为a=101的结果输出如下:
"湖南"
"广东"
"香港"

select m.* from table1 m , table2 n where m.a = 2 and n.a = 101 and (m.b = n.b or m.c = n.c and m.d = n.d)


如果要竖者显示

select m.b from table1 m , table2 n where m.a = 1 and n.a = 100 and m.b = n.b 
union all
select m.c from table1 m , table2 n where m.a = 1 and n.a = 100 and m.c = n.c
union all
select m.d from table1 m , table2 n where m.a = 1 and n.a = 100 and m.d = n.d


select m.b from table1 m , table2 n where m.a = 2 and n.a = 101 and m.b = n.b 
union all
select m.c from table1 m , table2 n where m.a = 2 and n.a = 101 and m.c = n.c
union all
select m.d from table1 m , table2 n where m.a = 2 and n.a = 101 and m.d = n.d



肥龙上天 2009-02-14
  • 打赏
  • 举报
回复

要是需要竖着的结果的话,可以将上面的结果存到一个临时表里面,再行列转换一下,
行列转换的方法csdn上有的时,需要的话,楼主可以自己找找看
肥龙上天 2009-02-14
  • 打赏
  • 举报
回复

使用动态语句

if object_id('ta') is not null drop table ta
create table ta(a int ,b char(10),c char (10),d char(10))
insert ta values(1,'天津','上海','北京')
insert ta values(2,'湖南','广东','香港')

if object_id('tb') is not null drop table tb
create table tb(a int,b char)
insert tb values(100,'d')
insert tb values(100,'b')
insert tb values(101,'d')
insert tb values(101,'b')
insert tb values(101,'c')

declare @a int,@b int,@sql nvarchar(max)
select @a = 2,@b = 101

select @sql = tt.s from(
select a,s = stuff((select ','+cast(b as nvarchar(256)) from tb where a = t.a for xml path('')),1,1,'') from tb t group by a
) tt
where tt.a = @b
set @sql = @sql +' from ta where a ='+cast(@a as nvarchar(10))
select @sql = 'select '+ @sql
exec(@sql)

d b c
---------- ---------- ----------
香港 湖南 广东

(1 row(s) affected)
duanzhi1984 2009-02-14
  • 打赏
  • 举报
回复




create table #t2( a int ,b char)
insert into #t2
select 100,'d' union all
select 100,'b'union all
select 101,'d' union all
select 101,'b' union all
select 101,'c'

declare @sql varchar(100)
declare @t varchar(100)
select @t=''
select @t=@t+','+b from #t2 where a=100 --a=100
select @t=substring(@t,2,len(@t)-1)


select @sql=N'select '+@t +' from #t where a=1' --a=1
PRINT @sql
exec(@sql)



北京
天津
贪玩的老鼠 2009-02-14
  • 打赏
  • 举报
回复
“最后不用临时表和游标” , 打错字了,”最好“不是"最后"
panfeifeibs 2009-02-14
  • 打赏
  • 举报
回复
没看懂啊

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧