Sql-server – concatenating columns from multiple unrelated 1-row resultsets

sql servert-sql

Assume I have these two queries in SQL Server 2014, both of which return one row from unrelated tables:

SELECT SUM(A) A, SUM(B) B FROM X
SELECT SUM(C) C, SUM(D) D FROM Y

I'd like to combine these queries into a single resultset that contains A, B, C, D.

What's a good way to do this within a single query, as opposed to multi-query solutions like selecting the results into and out of scalar variables?

Best Answer

Two subqueries?

SELECT Q1.A, Q1.B, Q2.C, Q2.D
FROM (SELECT SUM(A) A, SUM(B) B FROM @X) Q1(A, B)
CROSS APPLY (SELECT SUM(C) C, SUM(D) D FROM @Y) Q2(C, D);