TSQL selects rows according to one of two conditions

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'))
0
source share
2 answers

CROSS APPLY , TOP 1/ORDER BY derived table.

SELECT TOP 1000 o.order_Id
              , a.Address_Id
              , a.Zip
            --, *
FROM orders o
CROSS APPLY
(
 select TOP 1
        a.Address_Id,
        a.Zip
   from address a
  WHERE a.order_Id = o.order_Id
  ORDER BY case a.Type 
                when 'D2' then 1 
                when 'K1' then 2 
                else 3 
            end,
        a.ADD_DATE
) a
WHERE
 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'))

, :

from orders o
inner join address a
  ON a.order_Id = o.order_Id
inner join
(
  select a.order_id, a.Type,
         row_number () over (partition by a.order_id
                             order by case a.Type when 'D2' then 1 
                                                  when 'K1' then 2 
                                                  else 3 
                                       end, 
                                      a.ADD_DATE) rn
    from Address a
   group by a.order_id, a.Type
) onlyOneAddress
  on a.order_id = onlyOneAddress.order_id
 and a.type = onlyOneAddress.type
 and onlyOneAddress.rn = 1
+3

[Type] desc,

0

All Articles