日期:2014-05-18 浏览次数:20577 次
---------------------------- -- Author :SQL77(只为思齐老) -- Date :2010-03-09 15:17:54 -- Version: -- Microsoft SQL Server 2000 - 8.00.194 (Intel X86) -- Aug 6 2000 00:57:48 -- Copyright (c) 1988-2000 Microsoft Corporation -- Desktop Engine on Windows NT 5.1 (Build 2600: Service Pack 3) -- ---------------------------- --> 测试数据:#TB if object_id('tempdb.dbo.#TB') is not null drop table #TB go create table #TB([Mail_From] varchar(6),[Mail_To] varchar(40)) insert #TB select 'liming','aa@sina.com;bb@sina.com;mmm@yahoo.com.cn' union all select 'liming','aa@sina.com' union all select 'liming','bb@sina.com' union all select 'liming','baby@hotmail.com;mmm@yahoo.com.cn' union all select 'liming','mmm@yahoo.com.cn' union all select 'liming','aa@sina.com;mmm@yahoo.com.cn' --------------开始查询-------------------------- SELECT Mail_From, Mail_TO,COUNT(1) C FROM ( select Mail_From, SUBSTRING( Mail_To,NUMBER,CHARINDEX(';',Mail_To+';',NUMBER)-NUMBER)Mail_To FROM #TB,MASTER..SPT_VALUES WHERE TYPE='P' AND SUBSTRING(';'+Mail_To,NUMBER,1)=';' )T GROUP BY Mail_From, Mail_TO ORDER BY 3 DESC ----------------结果---------------------------- (所影响的行数为 6 行) Mail_From Mail_TO C --------- ---------------------------------------- ----------- liming mmm@yahoo.com.cn 4 liming aa@sina.com 3 liming bb@sina.com 2 liming baby@hotmail.com 1 (所影响的行数为 4 行) /* */
------解决方案--------------------
--> 测试数据:[tb] if object_id('[tb]') is not null drop table [tb] create table [tb]([Mail_From] varchar(6),[Mail_To] varchar(40)) go insert [tb] select 'liming','aa@sina.com;bb@sina.com;mmm@yahoo.com.cn' union all select 'liming','aa@sina.com' union all select 'liming','bb@sina.com' union all select 'liming','baby@hotmail.com;mmm@yahoo.com.cn' union all select 'liming','mmm@yahoo.com.cn' union all select 'liming','aa@sina.com;mmm@yahoo.com.cn' select Mail_To=substring(t.Mail_To,r.number,charindex(';',t.Mail_To+';',r.number)-r.number), count(1) as Num from tb t,master..spt_values r where r.number<=len(t.Mail_To) and r.type='p' and substring(';'+t.Mail_To,r.number,1)=';' group by substring(t.Mail_To,r.number,charindex(';',t.Mail_To+';',r.number)-r.number) Mail_To Num ---------------------------------------- ----------- aa@sina.com 3 baby@hotmail.com 1 bb@sina.com 2 mmm@yahoo.com.cn 4 (所影响的行数为 4 行)
------解决方案--------------------
--参考 拆分表: --> --> (Roy)生成測試數據 if not object_id('Tab') is null drop table Tab Go Create table Tab([Col1] int,[COl2] nvarchar(5)) Insert Tab select 1,N'a,b,c' union all select 2,N'd,e' union all select 3,N'f' Go --SQL2000用辅助表: if object_id('Tempdb..#Num') is not null drop table #Num go select top 100 ID=Identity(int,1,1) into #Num from sysc