[Question posted by a user on YugabyteDB Community Slack]
I have an SQL related question.I have a query like this:
SELECT SUM("baseOccupancy")
FROM "RoomTypes"
WHERE id IN (134,134)
Now each baseOccupany
is 2
and what I want is 4
but since both ids
inside IN
array are the same, it's just returning 2
instead of 4
.
Can anyone help me write a query where the query runs for each id
inside the array inside the WHERE
clause?
Here is a solution:
But knowing what is the root problem you want to solve may bring a better solution. Because a where clause is the to filter table rows, not to de-multiply them.
The principal misunderstanding here seems to be what
SUM()
andCOUNT()
are doing.COUNT()
counts the number of rows, regardless of the value inside the column it's set to count.SUM()
reads inside the set column and adds up the values. That makes both principally different. Therefore, if rows are using a unique id, aCOUNT()
of two id's that exist and have a value forbaseOccupancy
will result in 2. ASUM()
of these will be the total of the two fields.