繁体   English   中英

需要帮助结合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

我该怎么做呢? 我尝试将第二个查询作为嵌套选择放在最前面,但是我无法使其正常工作。 两个结果集共享相同的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;

并且您在表1中有选择结果,因此您可以为问题中的其他选择设置别名

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或其他命令

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM