选择另一列匹配记录-Oracle SQL

时间:2019-05-05 11:22:39

标签: sql oracle

我有这个查询:

SELECT
    t1.*,
            (
                SELECT
                    MIN(t2.e_nm)
                FROM
                    table2 t2
                WHERE
                    t2.c_type = t1.c_type
                    AND t2.h_level = t1.h_level
                    AND t2.loop = t1.loop
                    AND t2.e_id = t1.e_id
                HAVING
                    COUNT(*) = 1
            ) AS e_nm
        FROM
            table1 t1
        ORDER BY
            t1.f_name,
            t1.line_num;

当从table2中选择e_nm作为第二个参数时,我还想从表1中获取另一列匹配记录-seq_nm

如何在上述查询中做到这一点?

1 个答案:

答案 0 :(得分:1)

如果count(*) = 1,则可以将join用于聚合

SELECT t1.*, t2.e_nm, t2.x
FROM table1 t1 LEFT JOIN
     (SELECT t2.c_type, t2.h_level, t2.loop, t2.e_id,
             MIN(t2.e_nm) as e_nm, MIN(x) as x
      FROM table2 t2
      GROUP BY t2.c_type, t2.h_level, t2.loop, t2.e_id
      HAVING COUNT(*) = 1
     ) t2
     ON t2.c_type = t1.c_type AND
        t2.h_level = t1.h_level AND
        t2.loop = t1.loop AND
        t2.e_id = t1.e_id
ORDER BY t1.f_name, t1.line_num;

这行得通,因为您有COUNT(*) = 1,因此只有一行匹配。如果没有,您仍然可以使用KEEP

MIN(x) KEEP (DENSE_RANK FIRST ORDER B t2.e_num ASC) as x