I have a table like:
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 the second table:
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 should I do if for every order that has:
- not in status (4.6)
- code1 = '002'
- (code2 = null and code3 = null) or (code2 in ('BIGA', 'BIGP') and code3 = null) or (code2 = NULL and code3 = 'L')
I have to choose one address that is of type "D2" or "K1" (D2 has a higher priority, so if there are two addresses, one K1 and the second D2, I have to choose D2).
If there are no addresses with type D2 or K1, I must select the oldest address with the category "CLIENT" for this order.
This is what I 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'))
Misiu source
share