I have a table like so:
ORDER_ID CODE1 CODE2 CODE3 STATUS
1 '001' 'BIGP' NULL 4
2 '002' 'BIGP' NULL 1
3 '001' NULL NULL 6
4 '002' NULL 'L' 1
and second table like so:
ADDRESS_ID ORDER_ID TYPE ADD_DATE CATEGORY
1 1 'K1' '2010-01-01' 'CLIENT'
2 1 'D1' '2010-01-02' 'SYSTEM'
3 2 'D2' '2010-01-02' 'SYSTEM'
4 2 'D2' '2010-02-01' 'CLIENT'
What I must do if to for every order that has:
- status not in (4,6)
- code1='002'
- (code2=null and code3=null) or (code2 in ('BIGA', 'BIGP') and code3=null) or (code2=NULL and code3 = 'L')
I must choose a single address that has type 'D2' or 'K1' (D2 has higher priority, so if there will be 2 addresses one K1 and second D2 I must choose D2).
If there aren't any addresses with type D2 or K1 I must choose the oldest address with category 'CLIENT' for that order.
This is what I have created:
SELECT TOP 1000 o.order_Id
, a.Address_Id
, a.Zip
--, *
FROM orders o
address a
ON a.order_Id = o.order_Id
WHERE
(a.Type='D2' OR a.Type='K1')
AND o.Status NOT IN (4, 6)
AND code1='002'
AND ((code2 IS NULL AND code3 IS NULL) OR (code2 IN ('BIGA', 'BIGP') AND code3 IS NULL) OR (code2 IS NULL AND code3 = 'L'))
You might employ CROSS APPLY for the task as it allows use of TOP 1 / ORDER BY statements in
derived table
.Other than that, you might join in derived table of addresses with minimal Type per order:
just add the order by [Type] desc and it will show the high priority