当前位置: 首页 > 图文教程 > 数据库 > 数据库技巧 > 交叉表查询sql语句

数据库技巧
SQL中代替Like语句的另一种写法
Sql Server下数据库链接的使用方法
如何取得一个表的所有字段名用逗号分割
使用SQL Mail收发和自动处理邮件中的扩展存储过程简介
MySQL中的mysqldump命令使用详解
SQL 查询语句积累
SQL server 2005的表分区
关于ADOX的相关知识
如何让SQL运行得更快
ACCESS库转SQLSERVER数据库的注意事项
数据库设计技巧[转]
iwms access与sql版的安装与转换
[转载]让SQL运行得更快
[数据库] 通用分页存储过程
Access数据库升级为SQL数据库的注意事项和方法
Win2003系统安装SQL Sever2000后1433端口未开放的解释
SQL SERVER 与ACCESS、EXCEL的数据转换
Access转MS SqlServer的注意事项
数据库的设计方法、规范与技巧
数据库设计技巧奉送了

数据库技巧 中的 交叉表查询sql语句


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 46 ::
收藏到网摘: n/a

表一:
组名
成员1id
成员2id
成员3id
示例数据:
冲锋组 1 2 3
后卫组 2 3 4
表二:
成员id
成员姓名
示例数据:
1 张三
2 李四
3 王五
4 陆二
要求结果
冲锋组 张三 李四 王五
后卫组 李四 王五 陆二
复制代码 代码如下:

--建立测试环境
Create Table 表1(组名 varchar(10),成员1id varchar(10),成员2id varchar(10),成员3id varchar(10))
--插入数据
insert into 表1
select '冲锋组','1','2','3' union
select '后卫组','2','3','4'
Create Table 表2(成员id varchar(10),成员姓名 varchar(10))
--插入数据
insert into 表2
select '1','张三' union
select '2','李四' union
select '3','王五' union
select '4','陆二'
--测试语句
select a.组名,
成员1=(select 成员姓名 from 表2 b where a.成员1id=b.成员id),
成员1=(select 成员姓名 from 表2 b where a.成员2id=b.成员id),
成员1=(select 成员姓名 from 表2 b where a.成员3id=b.成员id)
from 表1 a

--删除测试环境
Drop Table 表1
Drop Table 表2
/*
组名 成员1 成员1 成员1
---------- ---------- ---------- ----------
冲锋组 张三 李四 王五
后卫组 李四 王五 陆二
(所影响的行数为 2 行)
*/

复制代码 代码如下:

select
a.组名,
成员1 = max(case b.成员id = a.成员1id then b.成员姓名 end),
成员2 = max(case b.成员id = a.成员2id then b.成员姓名 end),
成员3 = max(case b.成员id = a.成员3id then b.成员姓名 end),
from
表一 a,
表二 b
group by
a.组名

复制代码 代码如下:

select
a.组名,
成员1 = max(case b.成员id = a.成员1id then b.成员姓名 end),
成员2 = max(case b.成员id = a.成员2id then b.成员姓名 end),
成员3 = max(case b.成员id = a.成员3id then b.成员姓名 end)
from
表一 a,
表二 b
group by
a.组名

复制代码 代码如下:

select a.组名,
成员1=(select 成员姓名 from 表2 b where a.成员1id=b.成员id),
成员1=(select 成员姓名 from 表2 b where a.成员2id=b.成员id),
成员1=(select 成员姓名 from 表2 b where a.成员3id=b.成员id)
from 表一 a

复制代码 代码如下:

正解是
select 表1.组名,
(select 表1.成员姓名 from 表2 b where 表1.成员1id=表2.成员id) as 成员1id,
(select 表1.成员姓名 from 表2 b where 表1.成员2id=表2.成员id) as 成员2id,
(select 表1.成员姓名 from 表2 b where 表1.成员3id=表2.成员id) as 成员3id
from 表1,表2