1

I have the below query. This query is supposed to look into my accounts table with my where parameter. That will return all account codes which start with leading 3 letters "DAG". The data return is consistently in the format leading with three letters followed by a number. I then want to get the most largest number. For that I order the string by converting it to Int.

I get this below error:

Msg 207, Level 16, State 1, Line 24
Invalid column name 'AccountCodeWithoutDAG '.

Here is my SQL query.

SELECT TOP 1 
    REPLACE(AccountCode, 'DAG', '') AS AccountCodeWithoutDAG 
FROM 
    Accounts 
WHERE
    MangCode = 'ADFG'  
ORDER BY
    CONVERT(INT, AccountCodeWithoutDAG)

What am I doing wrong?

3
  • 4
    SELECT ... FROM ... WHERE ... ORDER BY ... Commented Nov 2, 2018 at 14:31
  • WHERE comes after FROM Commented Nov 2, 2018 at 14:32
  • sorry that was my bad copy pasting it. I edited it Commented Nov 2, 2018 at 14:36

3 Answers 3

3

You can't use order by with convert alias

but you can try to use a subquery to get the AccountCodeWithoutDAG then order by it

SELECT  TOP 1 AccountCodeWithoutDAG 
FROM 
(
    SELECT REPLACE(AccountCode,'DAG','') AS AccountCodeWithoutDAG
    FROM Accounts 
    where  MangCode = 'ADFG'  
) t1
Order by  Convert(int, AccountCodeWithoutDAG )
Sign up to request clarification or add additional context in comments.

1 Comment

I'm curious how this performs against just repeating the convert in the select and the orderby. Feels a lot cleaner to do it the other way
2

As others have indicated, giving a calculated value an alias in the select does not give you the ability to use the same alias in subsequent clauses.

The way to do this nice-and-organized in sql server is cross apply:

SELECT TOP 1 AccountCodeWithoutDAG
FROM Accounts 
cross apply (select REPLACE(AccountCode,'DAG','') AS AccountCodeWithoutDAG ) as calcquery
where 
   MangCode = 'ADFG'  
   Order by Convert(int, AccountCodeWithoutDAG )

1 Comment

You gotta love the cross apply! Many awesome uses!
1

The problem is the AccountCodeWithoutDAG, this is an alias and cannot be used in the order Look what I did in testing below , use your replace statement in the convert part of the order by

declare @AccountCode varchar(100)='DAG123456'

SELECT  top 1 REPLACE(@AccountCode,'DAG','') AS AccountCodeWithoutDAG 
   Order by Convert(int, REPLACE(@AccountCode,'DAG','')) 

2 Comments

ORDER by runs after the SELECT statement hence the Alias is visible
@AjanBalakumaran Totally depends on which version of sql server he's using. What you describe is a fairly new feature

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.