在两个表中,有不同值的记录(颜色)。我希望结果仅显示两个表中具有所有相同值的颜色。如果缺少任何值,则应将其完全拒绝。
另一个例子:
下面的代码应仅返回BLUE
WITH
t1 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
UNION
SELECT 'RED' as COLOUR, ('2') as VALUESY FROM DUAL
UNION
SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
UNION
SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL),
t2 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
UNION
SELECT 'RED' as COLOUR, ('3') as VALUESY FROM DUAL
UNION
SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
UNION
SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL)
SELECT *
FROM t1
FULL OUTER JOIN t2 ON t2.VALUESY = t1.VALUESY AND t2.COLOUR = t1.COLOUR
答案 0 :(得分:2)
您可以通过多种方法来执行此操作,一种方法是先执行FULL OUTER JOIN
,然后执行GROUP BY COALESCE( t1.COLOUR, t2.COLOUR )
,然后计算连接的两边是否有任何NULL
值;如果存在,则存在不匹配的值(假设所有输入值都不是NULL
:
Oracle设置:
CREATE TABLE t1 ( colour, valuesy ) as
SELECT 'RED', '1' FROM DUAL UNION
SELECT 'RED', '2' FROM DUAL UNION
SELECT 'BLUE', '1' FROM DUAL UNION
SELECT 'BLUE', '2' FROM DUAL
CREATE TABLE t2 ( colour, valuesy ) as
SELECT 'RED', '1' FROM DUAL UNION
SELECT 'RED', '3' FROM DUAL UNION
SELECT 'BLUE', '1' FROM DUAL UNION
SELECT 'BLUE', '2' FROM DUAL
查询:
SELECT COALESCE( t1.COLOUR, t2.COLOUR ) AS COLOUR
FROM t1
FULL OUTER JOIN t2
ON t2.VALUESY = t1.VALUESY AND t2.COLOUR = t1.COLOUR
GROUP BY COALESCE( t1.COLOUR, t2.COLOUR )
HAVING COUNT( CASE WHEN t1.COLOUR IS NULL OR t2.COLOUR IS NULL THEN 1 END ) = 0
输出:
| COLOUR | | :----- | | BLUE |
db <>提琴here
答案 1 :(得分:0)
您也可以使用以下查询。
WITH
t1 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
UNION
SELECT 'RED' as COLOUR, ('2') as VALUESY FROM DUAL
UNION
SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
UNION
SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL),
t2 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
UNION
SELECT 'RED' as COLOUR, ('3') as VALUESY FROM DUAL
UNION
SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
UNION
SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL)
--
-- query starts from here
--
SELECT
T1.COLOUR
FROM
(
SELECT
T1.COLOUR,
LISTAGG(T1.VALUESY) WITHIN GROUP(
ORDER BY
T1.VALUESY
) VAL
FROM
T1
GROUP BY
T1.COLOUR
) T1,
(
SELECT
T2.COLOUR,
LISTAGG(T2.VALUESY) WITHIN GROUP(
ORDER BY
T2.VALUESY
) VAL
FROM
T2
GROUP BY
T2.COLOUR
) T2
WHERE
T1.COLOUR = T2.COLOUR
AND T1.VAL = T2.VAL;
谢谢。
答案 2 :(得分:-1)
SELECT t1.COLOR, t1.VALUE
FROM TABLE1 t1
INNER JOIN TABLE2 t2 ON (t1.COLOR = t2.COLOR) AND (t1.VALUE = t2.VALUE);