I’d like to create a new variable in an outerquery, and then manipulate this new variable in a subquery.
However, when referencing the new column in the subquery, I receive an error that no such column exists
Code:
dbGetQuery(db,
"SELECT id, var1/var2 AS new_var, (SELECT SUM(new_var) AS summed_var
FROM table
GROUP BY id)
FROM table")
In this above code, the issue is that new_var
doesn’t get passed to the subquery. How can I pass the newly defined column, new_var
to the subquery?
EDIT: switching the inner query/outer query still doesn’t work:
dbGetQuery(db,
"SELECT SUM(new_var) AS summed_var (SELECT id, var1/var2 AS new_var
FROM table)
FROM table
GROUP BY id")
EDIT 2: The data is structured as below. Each row is an observation for an id
. I would like to generate a ratio, new_var = var1/var2
for each line. Then, I would like to sum the ratio new_var
for each id. In the toy data, for example, the summed ratio for Sally would be 3/4 + 7/8
.
My challenge was using GROUP BY
with SQL. I was unsure how to perform GROUP BY id
after generating the new_var
on a line-by-line basis.
id var1 var2 new_var
sally 3 4 3/4
susan 5 6 5/6
sally 7 8 7/8
tom 9 10 9/10