TSQL select rows by one from 2 conditions

2019-09-15 16:03发布

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'))

2条回答
ゆ 、 Hurt°
2楼-- · 2019-09-15 16:52

You might employ CROSS APPLY for the task as it allows use of TOP 1 / ORDER BY statements in 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'))

Other than that, you might join in derived table of addresses with minimal Type per order:

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
查看更多
Evening l夕情丶
3楼-- · 2019-09-15 16:52

just add the order by [Type] desc and it will show the high priority

查看更多
登录 后发表回答