PDA

View Full Version : یک سوال به ظاهر ساده



syyd morteza
جمعه 01 دی 1385, 12:44 عصر
فرض کنید table با دو فیلد f1 , f2 داریم می خواهیم یک select بنویسیم یه طوری که به شکل ضربدری رکوردهای این table را distinct کند یعنی به طور مثال اگر در یک رکورد مقدار F1 برابر با 1 بود و مقدار f2 برابر با 2 بود و در رکورد دیگر مقدار F1 برابر با 2 بود و مقدار f2 برابر با 1 بود .
از این دو رکورد یکی را نمایش دهد

AminSobati
جمعه 01 دی 1385, 16:15 عصر
من به دو روش مینویسم ولی احتمال میدم روش دوم در حجم بالای اطلاعات کمی بهتر عمل کنه، باید تست کرد:


create table t1(
pk_col int primary key identity,
c1 int,
c2 int)
go
insert t1 values(1,2)
insert t1 values(2,1)
insert t1 values(3,4)
insert t1 values(5,2)
insert t1 values(2,5)
insert t1 values(6,6)
go
create index ix1 on t1(c1,c2)
go

select * from t1
where (not exists (select * from t1 tmp1 where tmp1.c2=t1.c1 and tmp1.c1=t1.c2))
or (exists (select * from t1 tmp1 where tmp1.c2=t1.c1 and tmp1.c1=t1.c2 and t1.pk_col>=tmp1.pk_col))
go

select * from t1 where pk_col in
(select max(pk_col) from
(select pk_col, c1, c2 from t1
union all
select pk_col, c2, c1 from t1) tmp
group by c1,c2)