I want to add this query to a column in my table.I am using pgadmin
select customer_id,
count(*)
from summary
group by customer_id
order by customer_id asc
I got as far as
ALTER TABLE summary
add sum_of_rentals INT
UPDATE SUMMARY
SET sum_of_rentals =
(
select count(*)
FROM summary
WHERE customer_id= customer_id
GROUP BY customer_id
)
I tried this
UPDATE SUMMARY
SET sum_of_rentals =
(
select count(*)
FROM summary
WHERE customer_id= customer_id
GROUP BY customer_id
)
and got this answer from pgadmin
ERROR: more than one row returned by a subquery used as an expression
SQL state: 21000
3
Answers
in don’t know, what for you need that query.
But as i said in the comment, you produce with your subquery a rowset with as many rows a you have customers, but postgres exoects a sclar value
so one solution is to make a correlated subquery
fiddle
If my understanding is correct, you want to calculate the total rentals for each customer and apply that total to every row associated with that particular customer in the table.
Demo here
In the subquery,
customer_id= customer_id
is referring tocustomer_id
for the rows being selected. You’re querying rows whose customer_id equals their customer_id which is all rows so you get multiple results. You need to disambiguate them by using table aliases and fully qualified column names.Demonstration
Note: you may wish to move statistical caching like this into a join table. Then if you have 1,000,000 rows but only 1,000 unique values you only have 1,000 rows to update.
Demonstration.
Regardless, you probably want to keep it up to date with an insert/update/delete trigger.