是否可以使用多个连接和 CTE with 语句来缩小我在查询中选择的范围?
Is there away to narrow down what I am selecting in my query using multiple joins and CTE with statements?
所以我正在处理一个有点像这样的查询(见下文),我试图只提取某些字段,但我在让它工作时遇到了问题。任何见解将不胜感激。
WITH abc1 AS (
<some query that joins two tables together and lets say produces fields (a1,a2,a3)> ),
abc2 AS (
<some query that joins two tables together and lets say produces fields (b1,b2,b3)> ),
abc3 AS (
<some query that joins two tables together and lets say produces fields (c1,c2,c3)> )
SELECT * FROM abc1
这是可行的,也是我需要的方式。
LEFT JOIN abc2
ON abc1.a1 = abc2.b1
假设我只想在最终结果中看到 abc2.b2 而不是 abc2.b1 和 abc.b3。我该怎么做?
LEFT JOIN abc3
ON abc1.a1 = abc3.c1
假设我只想看到 abc3.c3 而不是 abc3.c1 或 abc3.c2。此外,如果在 abc1 和 abc3 之间的连接中产生空值,则填充 0,如果匹配,则填充 1。像这样:
CASE WHEN abc3.c1 IS NULL THEN 0 ELSE 1 END ACTIVE_IND
我试过这个(post CTE WITH 语句)但它没有用。
SELECT
abc1.a1
abc1.a2
abc1.a3
abc2.b2
abc3.c3
从 (
SELECT * 来自 abc1
LEFT JOIN abc2
ON abc1.a1 = abc2.b1
LEFT JOIN abc3
ON abc1.a1 = abc3.c1);
只需指定您希望在主查询中看到的列,而不是 *
。
例如:
WITH abc1 AS (
...
abc2 AS (
...
abc3 AS (
...
)
SELECT
abc1.*, -- all columns from the first CTE
abc2.b2, -- only b2 from the second CTE
abc3.c3 -- only c3 from the third CTE
FROM abc1
LEFT JOIN abc2 ON abc1.a1 = abc2.b1
LEFT JOIN abc3 ON abc1.a1 = abc3.c1
所以我正在处理一个有点像这样的查询(见下文),我试图只提取某些字段,但我在让它工作时遇到了问题。任何见解将不胜感激。
WITH abc1 AS (
<some query that joins two tables together and lets say produces fields (a1,a2,a3)> ),
abc2 AS (
<some query that joins two tables together and lets say produces fields (b1,b2,b3)> ),
abc3 AS (
<some query that joins two tables together and lets say produces fields (c1,c2,c3)> )
SELECT * FROM abc1
这是可行的,也是我需要的方式。
LEFT JOIN abc2
ON abc1.a1 = abc2.b1
假设我只想在最终结果中看到 abc2.b2 而不是 abc2.b1 和 abc.b3。我该怎么做?
LEFT JOIN abc3
ON abc1.a1 = abc3.c1
假设我只想看到 abc3.c3 而不是 abc3.c1 或 abc3.c2。此外,如果在 abc1 和 abc3 之间的连接中产生空值,则填充 0,如果匹配,则填充 1。像这样:
CASE WHEN abc3.c1 IS NULL THEN 0 ELSE 1 END ACTIVE_IND
我试过这个(post CTE WITH 语句)但它没有用。
SELECT abc1.a1 abc1.a2 abc1.a3 abc2.b2 abc3.c3 从 ( SELECT * 来自 abc1
LEFT JOIN abc2
ON abc1.a1 = abc2.b1
LEFT JOIN abc3
ON abc1.a1 = abc3.c1);
只需指定您希望在主查询中看到的列,而不是 *
。
例如:
WITH abc1 AS (
...
abc2 AS (
...
abc3 AS (
...
)
SELECT
abc1.*, -- all columns from the first CTE
abc2.b2, -- only b2 from the second CTE
abc3.c3 -- only c3 from the third CTE
FROM abc1
LEFT JOIN abc2 ON abc1.a1 = abc2.b1
LEFT JOIN abc3 ON abc1.a1 = abc3.c1