I have table like follows. id is sequential number and they order ascending.
id score name
1 10 A
2 20 B
3 30 C
4 40 D
I would like to calculate subtotal by using specific variable for example 3
in conditioning id<=3
I tried following , but a little complecated,and couldn’t achieved.
SUM(
CASE
WHEN main.id <= 3
THEN main.score
ELSE 0
END
) AS subtotal
From main
My desired result is like follows. Are there any smarter ways to achieve this?
id subtotal name
3 60 C
Thanks
2
Answers
Try this:
If you aggregate your data and you don’t limit this to
WHERE main.id <= 3
, then your approach is the typical way to achieve the result. It is called conditional aggregation. In standard SQL and PostgreSQL, too, you can get this more readable with:or with the nulls replaced by zero as in your original expression:
Most DBMS don’t support the
FILTER
clause yet. This is why most conditional aggregation examples on the Internet useCASE
expressions.