首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求一条SELECT语句。该怎么解决

2012-05-23 
求一条SELECT语句。部门表:dpt_id dpt_name1客服2市场3财务调拨表:db_id bm_id1 bm_id2100112100213100

求一条SELECT语句。
部门表:dpt_id; dpt_name
  1 客服
  2 市场
  3 财务

调拨表:db_id; bm_id1; bm_id2;  
  1001 1 2  
  1002 1 3
  1003 3 2  


问题:
选择调拨表中所有记录,如何把bm_id1; bm_id2; 这两个部门ID直接和部门表关联,select出部门名称dpt_name

效果如:
1001 客服 市场
1002 客服 财务
1003 财务 市场
 

[解决办法]

SQL code
select a.db_id,b.dpt_name,c.dpt_namefrom 调拨表 aleft join 部门表 b on a.bm_id1=b.dpt_idleft join 部门表 c on a.bm_id2=c.dpt_id
[解决办法]
SQL code
--> 测试数据:[a1]if object_id('[a1]') is not null drop table [a1]create table [a1]([dpt_id] int,[dpt_name] varchar(4))insert [a1]select 1,'客服' union allselect 2,'市场' union allselect 3,'财务'--> 测试数据:[b2]if object_id('[b2]') is not null drop table [b2]create table [b2]([db_id] int,[bm_id1] int,[bm_id2] int)insert [b2]select 1001,1,2 union allselect 1002,1,3 union allselect 1003,3,2select b.[db_id],a.dpt_name as namea,c.dpt_name as namecfrom b2 binner join a1 aon b.bm_id1=a.dpt_idinner join a1 con b.bm_id2=c.dpt_id/*db_id    namea    namec1001    客服    市场1002    客服    财务1003    财务    市场*/ 

热点排行
Bad Request.