简体   繁体   English

如何在SELECT查询中的两个不同表中获得两列的区别

[英]How can I get a difference of two columns in two different tables in a SELECT query

I have the two queries below I'd like to combine into one and get a difference result. 我想将以下两个查询合并为一个并得到不同的结果。

Query 1 查询1

SELECT SUM(col1 + col2) As total FROM tableA

Query 2 查询2

SELECT SUM(total) FROM tableB WHERE color not like '%black' and model not like 'CF%'

I'd like to combine these in a SELECT query and get the result: Query 1 - Query 2 = result. 我想将它们合并到SELECT查询中并获得结果:查询1-查询2 =结果。 The tables both have a "id" as a common key between them. 这两个表之间都有一个“ id”作为公用键。 I'm using MS SQL Server 2008 我正在使用MS SQL Server 2008

SELECT  (
        SELECT  SUM(col1 + col2)
        FROM    tableA
        ) -
        (
        SELECT  SUM(total) 
        FROM    tableB
        WHERE   color NOT LIKE '%black'
                AND model NOT LIKE 'CF%'
        ) AS result

Do an outside select with both of your queries as columns. 用两个查询作为列进行外部选择。

Something like 就像是

SELECT (Query1) - (Query2) as Diff SELECT(Query1)-(Query2)为Diff

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

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