当前位置:首页 > 芯闻号 > 充电吧
[导读]今天在做数据分析报表的时候遇到一个这样的问题。表结构如下。部门编码、部门名称、部门人员ID(中间用逗号分割)我想通过和人员表链接,查询出一个新的数据集,查询出的结果集格式如下:人员信息(ID或者姓名)

今天在做数据分析报表的时候遇到一个这样的问题。

表结构如下。
部门编码、部门名称、部门人员ID(中间用逗号分割)


我想通过和人员表链接,查询出一个新的数据集,查询出的结果集格式如下:
人员信息(ID或者姓名)、部门编码、部门名称

 

以前都是通过程序遍历拆分表字段组成新的集合字段,然后在结合SQL语句查询出结果集,但是这个报表要求只能通过SQL语句实现,以前记得可以通过写字段分割函数再结合游标实现。然而今天在网上无意间找到一个新的方法。用“master..spt_values”来实现,具体实现方法见下面实例1感觉这个东西太好用了。把网上的实例都整理了一下,希望各路大神批评指教,也希望大家继续把这方面的应用贴上.

 

select number from master..spt_values with(nolock) where type='P'
/**解释:master..spt_values表的字段值为P的对应number字段值是从0-2047*/ 
  
  
--1.将字符串转换为列显示 
  
if object_id('tb') is not null drop table tb 
go 
create table tb([编号] varchar(3),[产品] varchar(2),[数量] int,[单价] int,[金额] int,[序列号] varchar(8)) 
insert into tb([编号],[产品],[数量],[单价],[金额],[序列号]) 
select '001','AA',3,5,15,'12,13,14' union all
select '002','BB',8,9,13,'22,23,24'
go 
select [编号],[产品],[数量],[单价],[金额] 
,substring([序列号],b.number,charindex(',',[序列号]+',',b.number)-b.number) as [序列号] 
from tb a with(nolock),master..spt_values b with(nolock) 
where b.number>=1 and b.number=1 and number=1 and number1 
/** 
value 
----- 
朋 
友 
的 
*/ 
--------- 
  
  
--4.提取两个日期之间的所有月份 
if object_id('tb') is not null drop table tb 
go 
create table tb(id int identity(1,1),startDate varchar(10),endDate varchar(10)) 
insert into tb(startDate,endDate) select '2013-01-01','2013-09-25'
go 
declare @startDate varchar(10) 
declare @endDate varchar(10) 
select @startDate=startDate,@endDate=endDate from tb with(nolock) 
select convert(varchar(7),dateadd(mm,number,@startDate),120) as [月份] 
from master..spt_values with(nolock) 
where type='P' and number>=0 
and dateadd(mm,number,@startDate)=1 
--and number<=datediff(dd,@date,dateadd(mm,1,@date)) --对于mssql而言该语句不试用于2013-08-31的情况,这时由于9月没有31号,固计算出来的天数是30天 
and number=left(@time,2) and b.number=1 and number<=len(s) 
and substring('|'+s,number,1)='|'
)select left(ss,charindex(',',ss)-1)as s1,substring(ss,charindex(',',ss)+1,len(ss))as s2 from cte 
drop table tb 
/** 
s1             s2 
----------- ------------ 
车位地址1      车位状况1 
车位地址2      车位状况2 
车位地址n      车位状况n 
*/


本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭