日期:2014-05-17  浏览次数:20435 次

Distinct能不能过滤两个字段中不重复,并生成列表
select distinct a,b 这种不能处理的,是要列出两个字段里不都不重复的字段

不想用临时表处理。

字段a(外型设计),字段b(结构设计),字段c(产品名称)
技术员有可能是这个产品的外型设计,也有可能是那个产品的结构设计,也有可能是结构、外型设计

要求列出现有技术员手上,都负责那几个产品

distinct 好象只能接受单个过滤,两个字段好象不行

------解决方案--------------------
SQL code

if object_id('tb')is not null drop table tb
go
create table tb(a int,b int,name varchar(10))
insert tb select
1, 2,  '普检'  union all select
2, 2,  'a'  union all select
1, 3,  'b'  union all select
2, 1,  'c'  union all select
4, 2,  'd'  union all select
1, 5,  'e' 


select distinct name, a from 
(select a,name from tb
union all 
select b,name from tb)t
where a=2

name       a
---------- -----------
a          2
c          2
d          2
普检         2

(4 行受影响)

------解决方案--------------------
select name , count(1) 
from 
(
select 产品 , 外型设计 name from tb
union 
select 产品 , 结构设计 name from tb
) t
group by name

------解决方案--------------------
SQL code

---修改一下

if object_id('tb')is not null drop table tb
go
create table tb(ID int, 产品 varchar(2), 外型设计 varchar(20),结构设计 varchar(20))
insert tb select
1001, 'A'  ,  '张三 张四',      '张三' union all select
1002, 'B' ,   '张一' ,          '李一' union all select
1003, 'C' ,   '张三 李二'  ,    '李一' union all select
1004, 'D' ,   '李一'   ,        '李二 李一 李三 张五' 


if object_id('f_str')is not null drop function f_str
go
create function f_str(@s varchar(20))
returns varchar(400)
as
begin 
    declare @str varchar(400)
    select @str=isnull(@str+',','')+产品
    from tc where s=@s  

    return @str
end
go 


select top 1000 ID=Identity(int,1,1) into #Num from syscolumns a,syscolumns b

if object_id('tc')is not null drop table tc     --创建辅助表
go
create table tc(产品 varchar(20),s varchar(20))

insert tc Select distinct  
    a.产品,s=substring(a.s,b.ID,charindex(',',a.s+',',b.ID)-b.ID)
from 
    (select 产品,replace(外型设计,' ',',') as s from tb union all select 产品,replace(结构设计,' ',',') from tb)a
    ,#Num b
where
    charindex(',',','+a.s,b.ID)=b.ID 


select * from tc
---结果
-----------------------------------------
select s ,cp=dbo.f_str(s) from tc
group by s

s                    cp
-------------------- ----------------------------------------------------------------------------------------------------------------
李二                   C,D
李三                   D
李一                   B,C,D
张三                   A,C
张四                   A
张五                   D
张一                   B

(7 行受影响)
drop table #num