根据两个条件返回1行

时间:2020-01-15 15:24:13

标签: sql sql-server

假设我有一个根据下表的价格表。我想返回一个基于以下条件的,由彼此独立的ItemCode值组成的表...

  • 如果USD = true,则返回美元价格行,否则返回EUR价格
  • 如果EndDate为NULL,则返回带有NULL EndDate的行,否则返回带有NOT NULL EndDate的行
#include <memory>

最终结果应类似于:

+-----------+-------+----------+------------+------------+
| ItemCode  | Price | Currency | StartDate  | EndDate    |
+-----------+-------+----------+------------+------------+
| A02143803 | 18    | USD      | 01/09/2019 | NULL       |
+-----------+-------+----------+------------+------------+
| A02143803 | 17    | EUR      | 01/09/2019 | NULL       |
+-----------+-------+----------+------------+------------+
| A02143805 | 18    | USD      | 01/09/2019 | 31/12/2019 |
+-----------+-------+----------+------------+------------+
| A02143805 | 17,7  | USD      | 01/01/2020 | NULL       |
+-----------+-------+----------+------------+------------+
| A02143805 | 16    | EUR      | 01/09/2019 | NULL       |
+-----------+-------+----------+------------+------------+

请您建议什么是获得此结果的最佳方法? +-----------+-------+----------+------------+---------+ | ItemCode | Price | Currency | StartDate | EndDate | +-----------+-------+----------+------------+---------+ | A02143803 | 18 | USD | 01/09/2019 | NULL | +-----------+-------+----------+------------+---------+ | A02143805 | 17,7 | USD | 01/01/2020 | NULL | +-----------+-------+----------+------------+---------+ 可以解决我的问题吗?

1 个答案:

答案 0 :(得分:2)

您可以将row_number()与优先顺序结合使用:

select t.*
from (select t.*, 
             row_number() over (partition by itemcode 
                                order by (case when Currency = 'USD' then 0 else 1 end),
                                         (case when enddate is null then 0 else 1 end), enddate
                               ) as seq
      from table t
     ) t
where seq = 1;