Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Joining tables

Author  Topic 

chrisjones2004
Starting Member

4 Posts

Posted - 2013-03-07 : 07:20:59
I have two tables, which I want to join

Table Deals
* id
* date_date
* ccy_pair
* amount
* rate
* buyOrSell
* order_id

Table Orders
* order_id
* status
* sent_date
* ccy_pair
* buyOrSell
* rate
* amount

For orders that have no deals i.e order with a 'Status' of 'CANCELED', I want to find the next deal (i.e the deal that came after the order sent date) for the same ccy_pair and buyOrSell column values.




select deals.deal_date as d_date, orders.order_id ,orders.buysell, orders.ccy_pair, orders.amount as o_amount, orders.rate as o_rate, 
deals.amount as d_amount, deals.rate as d_rate
from orders


inner join deals on

and orders.status = 'CANCELED'
--trying to find deal
and deals.id = (SELECT id
FROM (SELECT id,
rank() over (partition by ccy_pair,buysell
order by deal_date) rnk
FROM deals where ccy_pair= orders.ccy_pair and deal_date > orders.sent_date
and buysell = orders.buysell
)
WHERE rnk = 1)
order by orders.sent_date desc


This is my beat attempt but I keep getting exceptions. Any help please?

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-03-07 : 08:43:27
[code]
select o.*,
case when o.status = 'CANCELLED' THEN d1.id ELSE d.id END AS DealID,
case when o.status = 'CANCELLED' THEN d1.date_date ELSE d.date_date END AS DealDate,
...
from Orders o
left join Deals d
ON d.order_id = o.order_id
outer apply (select *
from Deals
where ccy_pair = o.ccy_pair
and buyOrSell = o.buyOrSell
and date_date > o.sent_date
order by date_date asc)d1
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

chrisjones2004
Starting Member

4 Posts

Posted - 2013-03-07 : 09:49:40
Thanks for your reply, however I only want canceled orders, i.e d.order_id will never equal o.order_id
Go to Top of Page

chrisjones2004
Starting Member

4 Posts

Posted - 2013-03-07 : 09:51:52
Also can 'apply' be used in oracle databases?
Go to Top of Page

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-03-07 : 09:55:16
As far as I know, Oracle does not have CROSS/OUTER APPLY - but then again, I know so little about Oracle.

This forum is for Microsoft SQL Server, so expertise on Oracle would be hard to find.
Go to Top of Page

chrisjones2004
Starting Member

4 Posts

Posted - 2013-03-07 : 10:05:17
Ah ok thanks James, ill ask my question in an oracle forum instead.
Go to Top of Page
   

- Advertisement -