Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL using sum in where clause

I have a table which has a numeric column named 'capacity'. I want to select first rows which the total sum of their capacity is no greater than X, Sth like this query

select * from table where sum(capacity )<X

But I know I can not use aggregation functions in where part.So what other ways exists for this problem?

Here is some sample data

id| capacity
1 | 12
2 | 13.5
3 | 15

I want to list rows which their sum is less than 26 with the order of id, so a query like this

 select * from table where sum(capacity )<26 order by id

and it must give me

id| capacity
1 | 12
2 | 13.5

because 12+13.5<26

like image 229
Majid Hojati Avatar asked Jan 05 '17 21:01

Majid Hojati


People also ask

Can you use SUM function in WHERE clause?

In SQL, we use the SUM() function to add the numeric values in a column. It is an aggregate function in SQL. The aggregate function is used in conjunction with the WHERE clause to extract more information from the data.

How do I SUM values in PostgreSQL?

Use the SUM() function to calculate the sum of values. Use the DISTINCT option to calculate the sum of distinct values. Use the SUM() function with the GROUP BY clause to calculate the sum for each group.

Can you do calculations in PostgreSQL?

Mathematical operators are provided for many PostgreSQL types. For types without common mathematical conventions for all possible permutations (e.g., date/time types) we describe the actual behavior in subsequent sections. Table 9-2 shows the available mathematical operators.

What is rollup in PostgreSQL?

The PostgreSQL ROLLUP belongs to the GROUP BY clause that provides a short cut for defining multiple grouping sets. Multiple columns grouped together forms a group set. Unlike the CUBE subclause, ROLLUP does not yield all possible grouping sets based on the specified columns. It just makes a subset of those.


3 Answers

A bit late to the party, but for future reference, the following should work for a similar problem as the OP's:

SELECT id, sum(capacity)
FROM table
GROUP BY id
HAVING sum(capacity) < 26
ORDER by id ASC;

Use the PostgreSQL docs for reference to aggregate functions: https://www.postgresql.org/docs/9.1/tutorial-agg.html

like image 151
Hecatonchier Avatar answered Nov 19 '22 07:11

Hecatonchier


Use Having clause

    select * from table order by id having sum(capacity)<X
like image 30
Fahim Al Mahmud Ashik Avatar answered Nov 19 '22 06:11

Fahim Al Mahmud Ashik


You can use the window variant of sum to produce a cumulative sum, and then use it in the where clause. Note that window functions can't be placed directly in the where clause, so you'd need a subquery:

SELECT   id, capacity
FROM     (SELECT id, capacity, SUM(capacity) OVER (ORDER BY id ASC) AS cum_sum
          FROM   mytable) t
WHERE    cum_sum < 26
ORDER BY id ASC;
like image 4
Mureinik Avatar answered Nov 19 '22 06:11

Mureinik