SQL查询 - 返回表A中与表B中的任何行匹配的行

时间:2014-05-27 12:35:40

标签: sql

我正在尝试编写一个查询,该查询使用从第一个查询中获取的唯一LOCATION列表作为查询第二个表中行的条件。

例如:

SELECT
 TABLE_A."LOCATION",
 MIN(TABLE_A.WORKDATE) AS MIN_WORK_DATE
FROM
 DB.TABLE_A
WHERE
 MIN_WORK_DATE > '201201'

然后以某种方式:

SELECT
 TABLE_B."LOCATION",
 (other fields of interest)
FROM
 DB.TABLE_B
WHERE
 TABLE_B."LOCATION" (is contained in the result above)

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您可以将任何表格的列与任何其他表格的列匹配:

EX:

SELECT
 TABLE_A."LOCATION",
 TABLE_A.WORKDATE AS WORK_DATE
FROM
 DB.TABLE_A, DB.TABLE_B
WHERE
 TABLE_A.SOME_COLUMN > 'some_value_given' and TABLE_A.SOME_COLUMN=TABLE_B.SOME_COULMN

答案 1 :(得分:0)

你可以通过加入来实现:

SELECT
 b.location,
 (other fields of interest)
FROM
 tableB b
JOIN
 (SELECT a.location, min(a.workdate) as min_workdate
   FROM tableA a   
   GROUP BY a.location) c
ON b.location = c.location
WHERE c.min_workdate > '201201'

Fiddle