简体   繁体   中英

Sum on subqueries on SQL Server

I have a query with some subqueries inside and I want to add a sum query to sum them all.
How can I do that?

example:

Id,
(SELECT COUNT(*) FROM table1 LEFT JOIN table2 on ...) as col1,
(SELECT COUNT(*) FROM table3 LEFT JOIN table4 on ...) as col2,
** Sum of both col1 and col2 here **

Try this:

SELECT ID, col1, col2, [Total] = (col1 + col2)
FROM (
    SELECT Id,
    (SELECT COUNT(*) FROM table1 LEFT JOIN table2 on ...) as col1,
    (SELECT COUNT(*) FROM table3 LEFT JOIN table4 on ...) as col2
    FROM [TABLE]) T

Hope that helps.

the easiest way would be to treat all your query as a subquery

select Id, col1 + col2 as total
from
(<yourCode>) s

Because it's not possible to use alias in the same "level of query" in the select clause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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