very inexperienced with SQL, and I've found myself needing to write a query. Hopefully you can help me understand how I'd go about this:
I have two tables.
"table_requests" contains all requests, some of which are batches
"table_pages" contains information for each page of a batch, connects to "table_requests" on the column "table_request_id"
In addition, "table_pages" has a numeric column "word_count" that lists a number for each page and a "table_request_id" column that can match to the PK of "table_requests".
For my query, I'd like to connect "table_requests" to "table_pages" on that matching column, and select everything from "table_requests" with an added column on the end that totals the "word_count" for each "table_request" (from all pages in "table_pages").
So far I have:
select tr.id, tr.creation_date, sum(tp.word_count) as total_wc
from table_requests tr
join table_pages cp on tp.table_request_id = tr.id
Thank you all, let me know if there is any more information I can provide!
I think that the simplest approach is a correlated subquery:
select
tr.*,
(
select sum(tp.word_count)
from table_pages tp
where tp.table_request_id = tr.id
) total_wc
from table_requests tr
For performance with this query, make sure that you have an index on table_pages(table_request_id )
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.