Skip to content
Advertisement

Invalid column name grouping by calculated column label

I am trying to run this query to get the sales by month and by account:

select 
    left(cast(datekey as varchar(8)), 6) as themonth, 
    account, sum(sales) 
from 
    Sales
where 
    datekey > 20150101
group by 
    themonth, account
order by 
    themonth asc

datekey is an int following the YYYYMMDD format for dates.

I’m getting this message:

Msg 207, Level 16, State 1, Line 3
Invalid column name ‘themonth’

Why would that column name be invalid?

I’m assuming the error message is meaningless so what else is wrong with this query?

Advertisement

Answer

SQL Server does not allow the alias to be reused in the GROUP BY clause (other databases, such as MySQL, do allow for this). So, one option here would be to just repeat the quantity in the SELECT clause:

SELECT
    LEFT(CAST(datekey AS varchar(8)), 6) AS themonth,
    account,
    SUM(sales)
FROM Sales
WHERE datekey > 20150101
GROUP BY
    LEFT(CAST(datekey AS varchar(8)), 6),
    account
ORDER BY
    themonth;

Note that it is possible to ORDER BY the alias, so you may leave this part of your query as-is.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement