需要ORACLE SQL查询才能获得不同的值组合

时间:2014-11-28 17:17:56

标签: sql oracle

请帮助解决此问题:(

COL X   COL Y
1       A
1       B
1       C
2       A
2       B
2       C
3       A
3       B
3       C

输出应为

COL X  COL Y
1       A or B or C

如果1选A, 然后2不应该选择A(它可以选择B或C), 如果2选B,那么3不应该选择B.

输出应该像

1 A
2 B
3 C

1 C
2 A
3 B

...

4 个答案:

答案 0 :(得分:1)

我的第一篇文章,但我会用postgres db回答。

select 
  col1,
  col2
from
 (select row_number() over() rn1 , col1 from sample1 group by 2)a
inner join 
 (select row_number() over() rn2, col2 from sample1 group by 2)b
on a.rn1 = b.rn2
order by 1;

这将返回您的规范的结果集。

答案 1 :(得分:0)

如果您想要列B的明确值和A的任意值,那么您可以这样做:

select MIN(A), B
from table t
group by B;

如果您确实想要A和B的不同值,那么请稍微了解bipartite graphs。这尤其是匹配算法。我不知道是否有一种非递归方式在SQL中找到这样的集合。

答案 2 :(得分:0)

假设您的数据以某种方式“修复”,您可以使用CROSS JOIN构建所有组合。由于您的次优数据表示,查询相当复杂:

SELECT t1."COL X" as x1, t1."COL Y" as y1,
       t2."COL X" as x2, t2."COL Y" as y2,
       t3."COL X" as x3, t3."COL Y" as y3
FROM T t1 CROSS JOIN T t2 CROSS JOIN T t3
WHERE t1."COL Y" <> t2."COL Y"
  AND t1."COL X" <> t2."COL X"
  AND t2."COL Y" <> t3."COL Y"
  AND t2."COL X" <> t3."COL X"
  AND t3."COL Y" <> t1."COL Y"
  AND t3."COL X" <> t1."COL X";

请参阅http://sqlfiddle.com/#!4/f9bc0c/4

答案 3 :(得分:0)

在MYSQL中尝试:

set @rank:=1;
select n.X,n.Y from
(select a.SN as SN1,b.SN as SN2,a.X as X,a.Y as Y,(case when a.X=b.X then @rank:=@rank+1 else       @rank:=1 end) as ra from
(select @rownum:=@rownum+1 as SN,X,Y from temp,(select @rownum:=0) r)a left outer join
(select @rownum1:=@rownum1+1 as SN,X,Y from temp,(select @rownum1:=0) s)b
on a.SN-1=b.SN) n
where n.X=n.ra;