I have two tables, one containing polls and the other poll votes, like this (simplified):
CREATE TABLE IF NOT EXISTS polls (
id SERIAL PRIMARY KEY,
token VARCHAR(20)
);
CREATE TABLE IF NOT EXISTS poll_votes (
id SERIAL PRIMARY KEY,
account VARCHAR(255) NOT NULL,
poll_id INT NOT NULL,
token_one BIGINT,
token_two BIGINT,
token_three BIGINT
[etc.]
);
There is a growing number of token columns in the poll_votes
table, there can be over a thousand of them. There are multiple poll_votes
rows for each poll
row and I need to compute how many tokens in total are voting for each poll. The polls.token
column has the name of the token column to be used, i.e. it specifies which token shall be used to count the results for that particular poll.
So I have a query like this to calculate the results when there's, say, just one token column:
SELECT p.token,
(
SELECT SUM(token_one)
FROM poll_votes pv
WHERE p.id = pv.poll_id
GROUP BY pv.poll_id
) AS total_token_one
FROM polls p;
However, this hardcodes the token_one
column. Whereas I need it to be dynamically set based on what value there is in the token
column of the polls
table. How can I do that?
Update:
I came up with this table structure (even though it creates challenges) because there are a large and continuously growing number of tokens. If there is a separate row in poll_votes
for each token, then each single vote could require inserting hundreds of rows (since each account can have hundreds of token balances). So for a large number of voting accounts, it becomes a massive number of rows.
poll_votes
references tablepolls
, so the type of token is determined by that reference. There should be a singletoken
column in tablepoll_votes
. While stuck with your broken design, you need dynamic SQL. Plain SQL does not allow to parameterize a column name. Or a lengthyCASE
expression to switch between all cases.