使用分层标准获取不同的值

Getting distinct values using tiered criteria

我正在尝试弄清楚如何使用具有数千条记录的 table 并根据一些标准将其提炼出来。但是,标准是分层的。最好用一个例子来解释:

Product Key Product Code Qty Bundle Product Group Product Expiry
1 000ABC 1 Widgets null
2 000ABC 5 Widgets null
3 000ABC 1 Widgets null
4 000ABC 10 Widgets null
5 000DEF 1 Widgets null
6 000DEF 10 Widgets 01/15/2021
7 000DEF 10 Widgets null
8 000HIJ 5 Widgets 11/20/2020
9 000HIJ 10 Widgets null
10 000HIJ 5 Widgets null

使用上面的示例数据,我最终想要的是一个列表,其中对于每个产品代码我们只返回一个产品密钥。标准是:如果产品代码的 Qty Bundle 值 = 1,则使用该产品密钥,如果产品代码有多个 Qty Bundles = 1,并且这两个产品密钥都没有过期,则使用最小的产品密钥,如果一个产品代码没有Qty Bundle = 1,只取最小未过期的产品密钥。

根据这些标准,脚本的结果应该是:

Product Key Product Code Qty Bundle Product Group Product Expiry
1 000ABC 1 Widgets null
5 000DEF 1 Widgets null
9 000HIJ 10 Widgets null

任何建议都会有所帮助!

谢谢!

您可以使用 row_number() 和适当的排序标准:

select t.*
from (select t.*,
             row_number() over (partition by productcode
                                order by (case when qty_bundle = 1 and expiry is null then 1
                                               else 2
                                          end),
                                         (case when expiry is not null then 1 else 2
                                               else 3
                                          end),
                                         productkey
                               ) as seqnum
      from t
     ) t
where seqnum = 1;