假设我有一个根据下表的价格表。我想返回一个基于以下条件的,由彼此独立的ItemCode值组成的表...
#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 |
+-----------+-------+----------+------------+---------+
可以解决我的问题吗?
答案 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;