需要帮助组合 SQL 个查询

Need help combining SQL queries

SELECT 
    tableA.col1,
    tableA.col2,
    LEFT(tableB.col3, 4) as person

FROM tableA

LEFT JOIN tableB ON

    tableB.col1 = tableA.col1 AND
    tableB.col2 = tableA.col2

WHERE tableA.col3 = '000000'

AND tableA.col4 <> ''

AND person = 'Zeus'

ORDER BY tableA.col1, tableA.col4 ASC;

---

col1          col4        person
001           abc         Zeus
002           abc         Zeus
003           xyz         Zeus
004           xyz         Zeus

+

SELECT
    tableC.col1,
    SUM(tableC.col2) as cost

FROM tableC

WHERE tableC.col3 = 'L'

GROUP BY tableC.col1, tableC.col3;

---

col1          cost
001           23462
002           25215
003           92381
004           29171

=

col1          col4          person          cost
001           abc           Zeus            23462
002           abc           Zeus            25215
003           xyz           Zeus            92381
004           xyz           Zeus            29171

我该怎么做?我尝试将第二个查询作为嵌套 select 放在最上面的查询中,但我无法让它工作。两个结果集共享相同的 col1 值,这些值是唯一的,所以我想他们需要加入吗?最终 person 是每次我 运行 查询都会不同的地方。

您可以尝试在 col1 上使用内部联接

SELECT tableA.col1, tableA.col2, LEFT(tableB.col3, 4) as person, tableC.col1, SUM(tableC.col2) as cost
FROM tableA
LEFT JOIN tableB ON ( tableB.col1 = tableA.col1 AND tableB.col2 = tableA.col2)
INNER JOIN tableC ON ( tableA.col1 = tableC.col1)
WHERE tableA.col3 = '000000'
AND tableA.col4 <> ''
AND person = 'Zeus'
GROUP BY tableA.col4, person, tableC.col1, tableC.col3;
ORDER BY tableA.col1, tableA.col4 ASC;

如果您不想合并您的查询,您可以像这个查询一样为您的查询设置别名

select * from example ... as table1;

并且您的 select 结果在 table1 中,因此您可以为问题中的其他 select 设置别名

SELECT
    tableC.col1,
    SUM(tableC.col2) as cost

FROM tableC

WHERE tableC.col3 = 'L'

GROUP BY tableC.col1, tableC.col3 as table2

现在您可以在问题 table1 和 table 上使用加入或其他命令

join can give you preffered result.
SELECT 
    table1.*,
    table2.*   
FROM table1
JOIN table2 ON
    table1.col1 = table2.col1
ORDER BY table1.col1