跳转到主要内容

描述

If 组合器可应用于 argMin 函数,使用 argMinIf 聚合组合器函数, 查找在条件为真的行中与 val 最小值对应的 arg 值。 当你需要在数据集中查找与最小值对应的值, 但只针对满足特定条件的行时, argMinIf 函数非常有用。

示例用法

在本示例中,我们将创建一个表,用于存储产品价格及其时间戳, 并使用 argMinIf 找出各产品在有库存时的最低价格。
Query
CREATE TABLE product_prices(
    product_id UInt32,
    price Decimal(10,2),
    timestamp DateTime,
    in_stock UInt8
) ENGINE = MergeTree
ORDER BY ();

INSERT INTO product_prices VALUES
    (1, 10.99, '2024-01-01 10:00:00', 1),
    (1, 9.99, '2024-01-01 10:05:00', 1),
    (1, 11.99, '2024-01-01 10:10:00', 0),
    (2, 20.99, '2024-01-01 11:00:00', 1),
    (2, 19.99, '2024-01-01 11:05:00', 1),
    (2, 21.99, '2024-01-01 11:10:00', 1);

SELECT
    product_id,
    argMinIf(price, timestamp, in_stock = 1) AS lowest_price_when_in_stock
FROM product_prices
GROUP BY product_id;
argMinIf 函数会找出每个产品中与最早 timestamp 对应的价格, 但只考虑 in_stock = 1 的行。例如:
  • 产品 1:在有库存的行中,10.99 对应的 timestamp 最早 (10:00:00)
  • 产品 2:在有库存的行中,20.99 对应的 timestamp 最早 (11:00:00)
Response
   ┌─product_id─┬─lowest_price_when_in_stock─┐
1. │          1 │                      10.99 │
2. │          2 │                      20.99 │
   └────────────┴────────────────────────────┘

另请参阅

最后修改于 2026年6月10日