This is a follow-up question to this StackOverflow post. I'm trying to use two aliases at once, but it doesn't seem to work.
Some background: I'm using Microsoft SQL Server. I have a data set of Posts and Users from a StackExchange site. I have this SQL statement, which successfully lists the sum of points and the sum of views for each user for every post with a score greater than zero.
SELECT Users.Id, SUM(Posts.Score) AS ScoreSum, SUM(Posts.ViewCount) AS ViewSum
FROM [tsql-dml].[dbo].[Posts] AS Posts
INNER JOIN [tsql-dml].[dbo].[Users] AS Users
ON Posts.OwnerUserId = Users.Id
WHERE Posts.Score > 0
GROUP BY Users.Id
ORDER BY ViewSum DESC
Next, what I would like to do is get the ratio of the ViewSum column to the ScoreSum column. As noted in the linked post above, using the column alias directly doesn't work, but (SELECT Alias)
works. It seems that including these parenthesis is necessary. I tried this (only showing the select part of the query, the rest is the same):
SELECT Users.Id, SUM(Posts.Score) AS ScoreSum, SUM(Posts.ViewCount) AS ViewSum,
(SELECT(ViewSum)) / (SELECT(ScoreSum)) AS ViewScoreRatio
This gives the following error in SQL:
Msg 207, Level 16, State 1, Line 2
Invalid column name 'ViewSum'.
Msg 207, Level 16, State 1, Line 2
Invalid column name 'ScoreSum'.
So I thought, maybe I have to put the parenthesis around the whole thing. I tried this:
SELECT Users.Id, SUM(Posts.Score) AS ScoreSum, SUM(Posts.ViewCount) AS ViewSum,
(SELECT(ViewSum) / SELECT(ScoreSum)) AS ViewScoreRatio
With this one, the left SELECT for ViewSum doesn't show an error, but the right one fails.
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near ')'
Then I thought, what if I need parenthesis both ways? So I tried this:
SELECT Users.Id, SUM(Posts.Score) AS ScoreSum, SUM(Posts.ViewCount) AS ViewSum,
((SELECT(ViewSum)) / (SELECT(ScoreSum))) AS ViewScoreRatio
This fails with the same message as the first try:
Msg 207, Level 16, State 1, Line 2
Invalid column name 'ViewSum'.
Msg 207, Level 16, State 1, Line 2
Invalid column name 'ScoreSum'.
How do I use two column Aliases in SQL calculations?
The only workaround I've found so far is to re-do the sum, but I fear this is inefficient:
SELECT Users.Id, SUM(Posts.Score) AS ScoreSum, SUM(Posts.ViewCount) AS ViewSum,
SUM(Posts.ViewCount) / SUM(Posts.Score) AS ViewScoreRatio