prestodb / presto

The official home of the Presto distributed SQL query engine for big data
http://prestodb.io
Apache License 2.0
16.08k stars 5.39k forks source link

Add aggregate function SUM_IF() #19060

Open Stevoisiak opened 1 year ago

Stevoisiak commented 1 year ago

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).

tdcmeehan commented 1 year ago

CC @kaikalur

ges1227 commented 1 year ago

I'd like to take on this feature request 😀

tsafacjo commented 1 year ago

I'd like to take on this feature request too.

tdcmeehan commented 1 year ago

Feel free to submit a PR!

DHRUV6029 commented 1 month ago

hi @tdcmeehan is this still open can i work on this

tdcmeehan commented 4 weeks ago

@DHRUV6029 yes it's still open.