Question

I'm given a list of transportation lanes with a dollar amount per lane. The problem is that sometimes an indirect route is cheaper than the direct route. I want to be able to find those instances and insert them into a new table. I've tried using a LEFT OUTER JOIN but I can't quite figure it out. Below is an example of what I'm looking for and the code I tried. I'm not sure what database it is.

(Edit) Example: Cost from loc. 0380 to loc. 1428 (direct) is $100.00 but cost from 0380 to 1732 and then 1428 (indirect) is $99.61.

Org | Dest | Amount

0380 | 1428 | $100.00

0380 | 1732 | $92.26

1732 | 1428 | $7.35


INSERT INTO dbo.NewTable 
SELECT T1.Org, T1.Dest, T1.Amount, T2.Org, T2.Dest, T2.Amount, T3.Org, T3.Dest, T3.Amount
FROM (( dbo.RateTable [T1] 
    LEFT OUTER JOIN dbo.RateTable [T2] 
        ON T1.Org = T2.Org) 
    LEFT OUTER JOIN dbo.RateTable [T3] 
        ON T1.Dest = T3.Dest AND T2.Dest = T3.Dest)
WHERE T1.Amount > (T2.Amount + T3.Amount);
Was it helpful?

Solution

I think the only change that needs to be made is in the last join condition:

SELECT T1.Org, T1.Dest, T1.Amount, T2.Org, T2.Dest, T2.Amount, T3.Org, T3.Dest, T3.Amount
FROM dbo.RateTable T1 JOIN
     dbo.RateTable T2
     ON T1.Org = T2.Org JOIN
     dbo.RateTable T3 
     ON T1.Dest = T3.Dest AND T2.Dest = T3.Org
----------------------------------------^
WHERE T1.Amount > (T2.Amount + T3.Amount);

Note that I changed the left outer join to regular inner joins. The where condition requires matches.

This is assuming that "Org" standard for "Origin" or something like that.

OTHER TIPS

How about the following simple selection? Can it be simplified as such where the calcamount is the calculated amount you need. Select (CASE WHEN CalcAmount1 > CalcAmount2 THEN Amount1 ELSE Amount2 END) from Table

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top