prestodb/presto

Add aggregate function SUM_IF()

Open

#19,060 建立於 2023年2月15日

在 GitHub 查看
 (8 留言) (2 反應) (0 負責人)Java (5,240 fork)batch import
functiongood first issue

倉庫指標

Star
 (15,558 star)
PR 合併指標
 (平均合併 34天 14小時) (30 天內合併 120 個 PR)

描述

Feature Request

Implement a SUM_IF(x, y) aggregate function that would return the sum of TRUE input values. This would be equivalent to SUM(CASE WHEN x THEN y END)

Desired Functionality

Add a function similar to COUNT_IF(x) that would allow developers to simplify their code and improve readability of conditional sums.

Example Usage

Take the following example of conditional sums:

SELECT
    key_column,
    SUM(CASE WHEN category = "sports" THEN budget END) AS sports_budget,
    SUM(CASE WHEN category = "food" THEN budget END) AS food_budget,
    SUM(CASE WHEN category = "advertising" THEN budget END) AS advertising_budget
FROM table_name
GROUP BY 1

Adding a SUM_IF() function would allow it to be rewritten as:

SELECT
    key_column,
    SUM_IF(category = "sports", budget) AS sports_budget,
    SUM_IF(category = "food", budget) AS food_budget,
    SUM_IF(category = "advertising", budget) AS advertising_budget
FROM table_name
GROUP BY 1

Additional Information

The syntax could optionally allow for a third parameter n to allow specifying a fallback SUM value that would avoid NULL values. So for example, SUM_IF(condition, value, 0) would be equivalent to SUM(CASE WHEN condition THEN value ELSE 0 END).

貢獻者指南