根据最小订单价值按键分组

Grouping by key according to minimum order value

我正在使用 SQL 服务器

我有一个 table 这样的:

Key Rule_Name Rule_Order
Key1 interco 12
Key1 interco 12
Key1 VAT 15
Key1 interco 12
Key1 VAT 15
Key1 VAT 15

我正在寻找这个:

Key Rule_Name
Key1 interco

换句话说,我需要按键分组并获取与 Rule_Order.

的最小值匹配的规则名称

一开始我是这么想的:

select [Key], [Rule_Name]
from (
  select [Key],
    min([Rule_Order]),
    min([Rule_Name])
  from 
    mytable
  group by [Key]
)

适用于上面的示例,但是 min([Rule_Name]) 将查找按字母顺序排在第一位的 Rule_Name

如果我像这样更改规则顺序:

Key Rule_Name Rule_Order
Key1 interco 12
Key1 interco 12
Key1 VAT 10
Key1 interco 12
Key1 VAT 10
Key1 VAT 10

然后上面的查询会给我这个:

Key Rule_Name
Key1 interco

这不是我想要的,因为增值税与最小规则顺序相关联。

我知道单词 'interco' 在字母表中位于 'VAT' 之前。 我天真地认为聚合器的顺序在组中很重要: 使用 min([Rule_Order]) 列出最小顺序的第一条规则,然后检索与此顺序关联的规则名称。在我的例子中,因为总是有一个规则与给定的顺序相关联,所以我认为使用 min 或 max 并不重要。但是结果错了

那么在那种情况下查询应该是什么样的?

谢谢!

函数 FIRST_VALUE 完全符合我们的要求。

create table t(
Key_ varchar(10),
Rule_Name varchar(10),
Rule_Order int);
insert into t values
('Key1','interco',12),
('Key1','interco',12),
('Key1','VAT',10),
('Key1','interco',12),
('Key1','VAT',10),
('Key1','VAT',15),
('Key2','test',5);
select distinct
  key_,
  first_value(rule_name) over
      (partition by key_ 
       order by rule_order)
      as rule_name
from t;
GO
key_ | rule_name
:--- | :--------
Key1 | VAT      
Key2 | test     

db<>fiddle here

我们可以在 sub-query 或 cte 中使用 row_number。

create table t(
Key_ varchar(10),
Rule_Name varchar(10),
Rule_Order int);
insert into t values
('Key1','interco',12),
('Key1','interco',12),
('Key1','VAT',10),
('Key1','interco',12),
('Key1','VAT',10),
('Key1','VAT',15),
('Key2','test',5);
select
  key_,
  rule_name
from 
(select
  key_,
  rule_name,
  row_number() over 
      (partition by key_
      order by rule_order) rn
from t) as sq
where rn = 1;
GO
key_ | rule_name
:--- | :--------
Key1 | VAT      
Key2 | test     

db<>fiddle here