Click here to Skip to main content
15,899,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two querys that i need to substract, i the first query i get the results like this :

SQL
ROOMS | ROOM_Type
    3 | JRS
    7 | HPT


And the Second one returns

SQL
ROOMS | ROOM_Type
    13 | JRS
    11 | HPT


i need to get 1 result in wich both querys substract each other making a total count like this:

SQL
ROOMS | ROOM_Type
   10 | JRS
    4 | HPT


What I have tried:

I have tryed EXCEPT method and (Select(...) - Select (...) with no results i dont know how to make them substract their first result's
This are my 2 query's

Query 1
SQL
<pre>SELECT SUM(ROOMS), [ROOMS_Type] FROM   
  [RESERVATION]
WHERE  (SALIDA > N'2016-10-03') AND (ESTATUS = N'RV') AND (LLEGADA <= N'2016-10-03')
GROUP BY [ROOMS_Type]
ORDER BY ROOMS_Type


Query 2:
SQL
<pre>SELECT SUM(ROOMS) , [ROOMS_Type] 
FROM     [CHECKINS]
WHERE  (SALIDA > N'2016-10-03') AND (ESTATUS = N'IN')
GROUP BY [ROOMS_Type]
Posted
Updated 7-Mar-17 11:42am

1 solution

Updated to use CTE. Wrap both the queries in Common Table Expression.

This should do it. I saw the Query1 and 2 late, but the concept still the same, In your case, assume RESERVATION = #test1, CHECKINS=#test2

SQL
WITH cteReservation AS (SELECT SUM(ROOMS) ROOMS, [ROOMS_Type] FROM   
  [RESERVATION]
WHERE  (SALIDA > N'2016-10-03') AND (ESTATUS = N'RV') AND (LEGADA <= N'2016-10-03')
GROUP BY [ROOMS_Type]
--ORDER BY ROOMS_Type
), cteCheckins AS (
SELECT SUM(ROOMS) Rooms, [ROOMS_Type] 
FROM     [CHECKINS]
WHERE  (SALIDA > N'2016-10-03') AND (ESTATUS = N'IN')
GROUP BY [ROOMS_Type] )

SELECT t2.ROOMS - t1.ROOMS 'ROOMS', t1.[ROOMS_Type]   FROM 
cteCheckins t2 JOIN cteReservation t1
ON t2.[ROOMS_Type] = t1.[ROOMS_Type]
ORDER BY t1.[ROOMS_Type] DESC

Output:
ROOMS	ROOMS_Type
  10	JRS
   4	HPT
 
Share this answer
 
v4
Comments
Member 12839758 7-Mar-17 19:19pm    
This anwser does what i want but i dont want to créate a table for eachof my querys can i do this in 1 stament? or i have to use a temp table for each query and then use the "-"??
Bryian Tan 7-Mar-17 19:31pm    
You don't have to create temp table, I was using temp table as an example.

You can use Common table expression cte , https://www.simple-talk.com/sql/t-sql-programming/sql-server-cte-basics/
Bryian Tan 7-Mar-17 21:07pm    
I updated the example to use CTE.
Member 12839758 8-Mar-17 10:31am    
Thank you very much i understand your solution and could implemented correctly, but now i want to substract two CTE and give one result but cant do it i will post my approach

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900