Sql where部分中的不同查询,如何转换为1个查询?

Sql where部分中的不同查询,如何转换为1个查询?,sql,union,Sql,Union,我有两个简单的问题 select sum(deb)-sum(cre) as result1 from CXC where id='22731999' select sum(deb)-sum(cre) as result2 from CXC where id='22731999' and tipo='IM' 不同之处在于,例如,第一个查询结果在769686中,第二个查询结果在3469中,为了在一个结果中看到两个查询的结果,我必须做什么 result1 result2 -----------

我有两个简单的问题

select sum(deb)-sum(cre) as result1 from CXC where id='22731999' 

select sum(deb)-sum(cre) as result2 from CXC where id='22731999' and tipo='IM'
不同之处在于,例如,第一个查询结果在769686中,第二个查询结果在3469中,为了在一个结果中看到两个查询的结果,我必须做什么

result1  result2
----------------
769686   3469
我试过了

select sum(C.deb)-sum(C.cre) as Result1 from CXC C where C.id='22731999'
UNION
select sum(X.deb)-sum(X.cre) as Result2 from CXC X where X.id='22731999' and .tipo='IM'
但这不是我想要的,因为它会产生两行

result1
result2
我必须说,我在ODBC桥下使用了这个查询来连接Cobol文件,驱动程序太旧了。。所以sql是非常基本的。。我有这个限制:(


驱动程序的名称是RM Cobol的Relational DataBridge

请尝试自联接。它类似于:

选择sum(C.deb)-sum(C.cre)作为结果1,sum(X.deb)-sum(X.cre)作为结果2
从CXC到CXC X
其中C.id='22731999'和X.id='22731999'以及.tipo='IM'

试试看

SELECT max(Result1) as Result1, max(Result2) as Result2
FROM
    (
    SELECT 
    select sum(C.deb)-sum(C.cre) as Result1, null as Result2
    from CXC C where C.id='22731999'
    UNION
    select null as Result1, sum(X.deb)-sum(X.cre) as Result2 
    from CXC X where X.id='22731999' and .tipo='IM'
    ) x
使用:

…获得:

result1  result2
----------------
769686   3469
我是这样想的。。。 联合将查询置于彼此之上。 联接将查询放置在彼此相邻的位置

在这种情况下我所做的是

SELECT result1, result2 FROM
  (select sum(deb)-sum(cre) as result1, id from CXC where id='22731999' ) query1
JOIN
(select sum(deb)-sum(cre) as result2, id from CXC where id='22731999' and tipo='IM') query2
 ON query1.id = query2.id
为了简化这里发生的事情,假设query1是一个表,query2是一个表

select result1, result2 
from query1
join query2 on query1.id = query2.id

希望这有帮助。

此查询不会失败。。但结果太不一样。可能有笛卡尔乘积。可能需要将主键添加到where子句(例如C.id=X.id)
select result1, result2 
from query1
join query2 on query1.id = query2.id