【问题标题】:Getting distinct values using tiered criteria使用分层标准获取不同的值
【发布时间】:2021-06-01 08:34:33
【问题描述】:

我正在尝试弄清楚如何获取包含数千条记录的表格并根据一些标准对其进行提炼。但是,标准是分层的。最好用一个例子来解释:

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

使用上面的数据作为示例数据,我想最终得到一个列表,其中对于每个产品代码,我们只返回一个产品密钥。标准是:如果产品代码的数量捆绑值 = 1,则使用该产品密钥,如果产品代码有多个数量捆绑 = 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

任何建议都会有所帮助!

谢谢!

【问题讨论】:

  • 如果有“1”的行但所有行都过期了怎么办?

标签: sql select datatables distinct criteria


【解决方案1】:

您可以使用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;

【讨论】:

  • 感谢 Gordon - 这很好用!非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2022-11-22
  • 1970-01-01
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多