SQL:使用 WHERE 子句连接表
SQL: Joining tables with WHERE clauses
我正在尝试加入共享同一个人 ID (key
) 的两个 table。第一个 table (a
) 是一个 'wide' table,有很多变量,包括 key
和 age
,第二个 table (b
)是一个'long'table,只包含变量key
、diagnosis_number
和diagnosis
,其中每个个体可以有多个值diagnosis
.
我想要 select 列 key
、age
以及以下个人的初步诊断:
diagnosis
= "a"、"b" 或 "c" 当 diagnosis_number
= 1 ['primary diagnosis']
- AND
diagnosis
= "y" 对于任何 diagnosis_number
= 2:20
我试过:
SELECT main.key, main.age, diag.diagnosis
FROM a as main
INNER JOIN
(
SELECT prim.key, prim.diagnosis
FROM
(SELECT DISTICT key, diagnosis
FROM b
WHERE diagnosis IN ('a', 'b', 'c')
AND diagnosis_number = 1) as prim
INNER JOIN
(SELECT DISTICT key, diagnosis
FROM b
WHERE diagnosis = 'y'
AND diagnosis_number BETWEEN 2 AND 20) as sec
ON prim.key = sec.key) as diag
ON main.key = diag.key
认为这可以在没有 subqueries/SELECTs 内部联接的情况下解决:
SQL 服务器
SELECT a.key, a.age, b.diagnosis
FROM a
INNER JOIN b
ON b.key = a.key
WHERE b.diagnosis IN ('a', 'b', 'c')
AND b.diagnosis_code = 1
AND a.key IN (SELECT b1.key
FROM b AS b1
WHERE b1.diagnosis = 'y'
AND b1.diagnosis_code BETWEEN 2 AND 20)
我正在尝试加入共享同一个人 ID (key
) 的两个 table。第一个 table (a
) 是一个 'wide' table,有很多变量,包括 key
和 age
,第二个 table (b
)是一个'long'table,只包含变量key
、diagnosis_number
和diagnosis
,其中每个个体可以有多个值diagnosis
.
我想要 select 列 key
、age
以及以下个人的初步诊断:
diagnosis
= "a"、"b" 或 "c" 当diagnosis_number
= 1 ['primary diagnosis']- AND
diagnosis
= "y" 对于任何diagnosis_number
= 2:20
我试过:
SELECT main.key, main.age, diag.diagnosis
FROM a as main
INNER JOIN
(
SELECT prim.key, prim.diagnosis
FROM
(SELECT DISTICT key, diagnosis
FROM b
WHERE diagnosis IN ('a', 'b', 'c')
AND diagnosis_number = 1) as prim
INNER JOIN
(SELECT DISTICT key, diagnosis
FROM b
WHERE diagnosis = 'y'
AND diagnosis_number BETWEEN 2 AND 20) as sec
ON prim.key = sec.key) as diag
ON main.key = diag.key
认为这可以在没有 subqueries/SELECTs 内部联接的情况下解决:
SQL 服务器
SELECT a.key, a.age, b.diagnosis
FROM a
INNER JOIN b
ON b.key = a.key
WHERE b.diagnosis IN ('a', 'b', 'c')
AND b.diagnosis_code = 1
AND a.key IN (SELECT b1.key
FROM b AS b1
WHERE b1.diagnosis = 'y'
AND b1.diagnosis_code BETWEEN 2 AND 20)