22,209
社区成员
发帖
与我相关
我的任务
分享
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-07-11 14:53:43
-- Version:
-- Microsoft SQL Server 2012 - 11.0.2100.60 (Intel X86)
-- Feb 10 2012 19:13:17
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([name] varchar(8),[adress] varchar(2),[favorite] varchar(28))
insert [tb]
select 'BobBob','CN','swimming;pingpang;swimming;' union all
select 'Jack','US','music' union all
select 'hankhank','UN','KALA;KALA;BENG'
--------------开始查询--------------------------
select * from tb where name in(
select name
from(
select name,favorite,count(1) as num
from
(
Select
a.name,favorite=substring(a.favorite,b.number,charindex(';',a.favorite+';',b.number)-b.number)
from
Tb a join master..spt_values b
ON B.type='p' AND B.number BETWEEN 1 AND LEN(A.favorite)
where
substring(';'+a.favorite,b.number,1)=';'
) as t
group by
name,favorite
having
count(1)>1) as t)
----------------结果----------------------------
/* name adress favorite
-------- ------ ----------------------------
BobBob CN swimming;pingpang;swimming;
hankhank UN KALA;KALA;BENG
(2 行受影响)
*/
--drop table tb
create table tb(name varchar(20),adress varchar(20),favorite varchar(200))
insert into tb
select'BobBob','CN','swimiming;pingpangswimming;' union all
select'Jack','US','music' union all
select'hankhank','UN','KALA;KALA;BENG'
go
select de,count(*) from
(
select tb.name ,adress,substring (favorite,a.number,charindex(';',favorite+';',a.number)-a.number) as de
from tb,master.dbo.spt_values a
where a.type='p' and a.number>=1 and a.number <len(favorite) and substring (';'+favorite,a.number,1)=';'
) t group by de
--de (无列名)
--BENG 1
--KALA 2
--music 1
--pingpangswimming 1
--swimiming 1