对于此示例表:
表A:
Col1 Col2
-----------
2015 A
2015 B
2015 C
表B:
Col1 Col2
------------
2015 X
2015 Y
2015 Z
我希望查询返回:
Col1 Col2
------------
A X
B Y
C Z
我尝试过这样的事情:
SELECT TA.COL2, TB.COL2
FROM
(SELECT * FROM TABLE_A WHERE COL1=2015) TA,
(SELECT * FROM TABLE_B WHERE COL1=2015) TB,
但是我得到重复的结果
Col1 Col2
-----------
A X
A Y
A Z
B X
B Y
B Z
C X
C Y
C Z
答案 0 :(得分:2)
一种方法是使用行号:
SELECT TA.COL2, TB.COL2
FROM
(SELECT TABLE_A.COL2, ROWNUM AS R1 FROM TABLE_A WHERE COL1=2015) TA,
(SELECT TABLE_B.COL2, ROWNUM AS R2 FROM TABLE_B WHERE COL1=2015) TB,
WHERE T1.R1 = T2.R2
答案 1 :(得分:0)
在SELECT语句中,在SELECT子句之后包含DISTINCT或DISTINCTROW关键字。 更多细节: http://www.geeksengine.com/database/basic-select/eliminate-duplicate-rows.php
答案 2 :(得分:0)
不确定为什么要这样做,但这是我的方法。
SELECT
TA.COL2 AS Col1,
TB.COL2 AS Col2
FROM
(SELECT COL1, COL2, ROW_NUMBER() OVER (PARTITION BY COL1 ORDER BY COL2) AS Seq FROM TABLE_A) TA
JOIN
(SELECT COL1, COL2, ROW_NUMBER() OVER (PARTITION BY COL1 ORDER BY COL2) AS Seq FROM TABLE_B) TB
ON TA.COL1 = TB.COL1
AND TA.Seq = TB.Seq
答案 3 :(得分:0)
您可能想要使用union all
/ group by
方法:
SELECT MAX(COL2_a) as COL2_a, MAX(COL2_B) as COL2_B
FROM ((SELECT COL2 as COL2_A, NULL as COL2_B,
ROW_NUMBER() OVER (ORDER BY COL2) as seqnum
FROM TABLE_A
WHERE COL1 = 2015
) UNION ALL
(SELECT NULL, COL2, ROW_NUMBER() OVER (ORDER BY COL2) as seqnum
FROM TABLE_B
WHERE COL1 = 2015
) UNION ALL
) t
GROUP BY seqnum;
或者,使用FULL JOIN
:
SELECT a.COL2 as COL2_a, b.COL2 as COL2_B
FROM (SELECT a.*,
ROW_NUMBER() OVER (ORDER BY COL2) as seqnum
FROM TABLE_A a
WHERE COL1 = 2015
) a FULL JOIN
(SELECT b.*,
ROW_NUMBER() OVER (ORDER BY COL2) as seqnum
FROM TABLE_B b
WHERE COL1 = 2015
) b
ON a.seqnum = b.seqnum;
如果一个表比另一个表具有更多的值,则这两种方法都将返回 all 个值。