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
是每次运行时查询都会有所不同的地方。
答案 0 :(得分:1)
您可以尝试使用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;
答案 1 :(得分:1)
如果您不想组合查询,可以为查询设置别名,例如此查询
select * from example ... as table1;
并且您在table1中有选择结果,因此您可以在问题中为其他选择设置别名
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