Is it possible to do something like the following?
select a as res, res * 2 as res2, res2 * 4 from tableA;
The instance I want to do this is much more complicated and it would make the query much more manageable if there was a way to not have to duplicate logic.
I was thinking a function would work but then I would not have the row by row action that the select allows for.
SELECT
comp.playerID,
comp.RC,
comp.RC / (t.BPF + 100) / 200
FROM
(
SELECT
playerID,
coalesce(
(sum(H) + sum(2B) + (2 * sum(3B)) + (3 * sum(HR))) + ((sum(BB) + sum(HBP) - sum(IBB)) * 0.26) - (sum(SH) + sum(SF) + sum(SB)) * 0.52,
0
) AS RC
FROM
Batting
GROUP BY
playerID
) AS comp,
Teams t;
There are a few nested layers outside of this, but this is the root of the duplication.
You can't refer to an alias in the same SELECT list. You need to use a subquery.
SELECT res, res * 2, res * 8
FROM (
SELECT a AS res
FROM tableA
) AS x
In your larger query, you're getting a full cross product between comp
and teams
, so you're duplicating each player on each team. You need to join the tables based on the player's team.
SELECT
comp.playerID,
comp.RC,
comp.RC / (t.BPF + 100) / 200
FROM
(
SELECT
playerID,
teamID,
coalesce(
(sum(H) + sum(2B) + (2 * sum(3B)) + (3 * sum(HR))) + ((sum(BB) + sum(HBP) - sum(IBB)) * 0.26) - (sum(SH) + sum(SF) + sum(SB)) * 0.52,
0
) AS RC
FROM
Batting
GROUP BY
playerID
) AS comp
JOIN Teams t ON comp.teamID = t.teamID
You didn't post your schema, so I had to guess at how the tables are related. You should be able to adjust the answer to the actual relationship (e.g. if there's a join table that relates players to teams, add another join).