Equivalent of sum(case when-then-else-end) SQL statements in Ibis? #4657
-
I'm essentially trying to replicate this but in Ibis: https://github.com/dbt-labs/dbt-demo-data/blob/main/models/marts/orders.sql#L34-L51 these {% for product in products %}
sum(case when products.product_name = {{ product }} then product_price else 0 end) as subtotal_{{ product }},
{% endfor %}
sum(product_price) as subtotal I've achieved this in dataframe APIs with my code, minus embarrassing attempts to get this to work, is here: https://github.com/dbt-labs/dbt-demo-data/blob/cody/ibis/ibis.ipynb |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Most aggregates in ibis have a products.aggregate(
products["product_price"].sum(where=product["is_drink_item"] == 1).name("subtotal_drink_price")
)
products.aggregate(
(product["is_drink_item"] == 1).sum().name("drink_items_count")
) There might be an even easier way, but that is how you'd translate it most directly. |
Beta Was this translation helpful? Give feedback.
Most aggregates in ibis have a
where
parameter that you can use for conditional aggregation. You can also just sum a boolean comparison if you are trying to get a conditional count. Try something like this:There might be an even easier way, but that is how you'd translate it most directly.