![]() |
SQL: Rewrite a complex join without #temp tables?
Hello, guys
I have an example query which includes a complex join with 4 tables (actually 5, because one of them must be aliased twice). I could not find another option but to use #temporary tables to store some of the inner joins. Do any of you have any idea how could this query be rewritten without using the temporary tables? There are the following tables: Client (Id, Name), OrderType (Id, Name = {'sell', 'buy'}), Order(Id, ClientId, OrderTypeId), OrderItem (OrderId, Quantity, Price) I need to get the following result: A table with the names of the clients that made a positive turnover: Client name | Turnover Where each client's Turnover is calculated as the difference between the sum of all Orders of type 'buy' and the sum of all Orders of type 'sell' or turnover = (SUM(buy) - SUM(sell)) I am quite puzzled, need to confess I haven't written many complex queries by now. Here is what I came to: :
It works fine but I was wondering if I could skip the #temp tables. If you have any ideas I will appreciate. Thanks :) |
Yep I just made a nice experiment and it turned out it works !!! :) Maybe I was too fast in posting the question when I was just on the edge of the answer :) but I have been scratching my head upon this query for two days :) Well it might be useful for someone anyway, so I will post my creation :):) All I did was to paste the code that creates the #temp tables in the places of their names in the last query. And put brackets around it as well. Here it is:
:
|
| All times are GMT -5. The time now is 2:02 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC