简体   繁体   中英

Case statement order by - invalid column name 'yearmonth'

My query doesn't recognize the column when I use a case statement, but does when I don't. I really need to use the case statement. Can you please let me know why it is wrong. Thank you very much.

i will update what i am trying to do thank you

You should use your Table Column Name Instead of using its yearmonth ALIAS NAME .

Alias name is just for renaming a table or a column temporarily by giving another name.

SELECT (LEFT(DATENAME(MONTH,SRVC_DT),3)  + '-'  + CAST(YEAR(SRVC_DT) AS NCHAR)) AS YEARMONTH
FROM  IRX_MAIN.ESA.VW_CLM_PHRMCY_DLY_MSTR
WHERE DATEDIFF(MM, SRVC_DT, GETDATE()) BETWEEN 1 AND 12
ORDER BY (CASE (LEFT(DATENAME(MONTH,SRVC_DT),3)  + '-'  + CAST(YEAR(SRVC_DT) AS NCHAR)) WHEN 'JUL-2020'  THEN 7 
                                                                        WHEN 'AUG2020' THEN 8 
                                                                        WHEN 'SEP2020' THEN 9 
                                                                        WHEN 'OCT2020' THEN 10 
                                                                        WHEN 'NOV2020' THEN 11  
                                                                        WHEN 'DEC2020' THEN 12 END)

Also, You can try this:

SELECT (LEFT(DATENAME(MONTH,SRVC_DT),3)  + '-'  + CAST(YEAR(SRVC_DT) AS NCHAR)) AS YEARMONTH
FROM  IRX_MAIN.ESA.VW_CLM_PHRMCY_DLY_MSTR
WHERE DATEDIFF(MM, SRVC_DT, GETDATE()) BETWEEN 1 AND 12
ORDER BY SRVC_DT 

SQL Server doesn't recognize the column alias when it is in an expression. Sad.

But there is an easier way:

order by min(SRVC_DT)

This just orders by the minimum of SRVC_DT in each group.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM