SELECT dpcode1+dpcode2+dpcode3 as 部门代码,dpname1+dpname2+dpname3 as 部门名称 FROM T_Dpt where dpname1 is not null and dpname2 is not null and dpname3 is not null union all SELECT dpcode1+dpcode2+dpcode3 as 部门代码,dpname1+dpname2 as 部门名称 FROM T_Dpt where dpname1 is not null and dpname2 is not null and dpname3 is null UNION ALL SELECT dpcode1+dpcode2+dpcode3 as 部门代码,dpname1 as 部门名称 FROM T_Dpt where dpname1 is not null and dpname2 is null and dpname3 is null;
运行结果:
部门代码 部门名称
01外语系
0102 外语系日语专业
0102001外语系日语专业0331班
0103 外语系商务英语
0103001外语系商务英语0341班
0104 外语系教工
0103002 外语系商务英语0242班
附:
用到的基本表
CREATE TABLE [dbo].[T_Dpt] (
[DpCode1] [char] (2) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[DpCode2] [char] (2) COLLATE Chinese_PRC_CI_AS NULL ,
[DpCode3] [char] (3) COLLATE Chinese_PRC_CI_AS NULL ,
[DpName1] [varchar] (30) COLLATE Chinese_PRC_CI_AS NULL ,
[DpName2] [varchar] (30) COLLATE Chinese_PRC_CI_AS NULL ,
[DpName3] [varchar] (30) COLLATE Chinese_PRC_CI_AS NULL ,
) ON [PRIMARY]
示例数据:
DpCode1 | DpCode2 | DpCode3 | DpName1 | DpName2 | DpName3 |
01 | 外语系 | null | null | ||
01 | 02 | 外语系 | 日语专业 | null | |
01 | 02 | 001 | 外语系 | 日语专业 | 0331班 |
01 | 03 | 外语系 | 商务英语 | null | |
01 | 03 | 001 | 外语系 | 商务英语 | 0341班 |
01 | 04 | 外语系 | 教工 | null | |
01 | 03 | 002 | 外语系 | 商务英语 | 0242班 |