Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I want to find total expence by LOB.
SQL
SELECT  
      [dte]
      ,Year([dte]) as RP_Year
      ,[LOB]
      ,Sum([Cost]) as Sum_cost
     
  FROM xxx
  Where [RP_Year] = '2017'
  Group by [LOB]

and get error
Msg 207, Level 16, State 1, Line 27 Invalid column name 'RP_Year'

what to do?

What I have tried:

...........................................................................................
Posted
Updated 27-Apr-17 5:13am
v2

1 solution

You can't use RP_Year in the WHERE clause - that's an alias not a column name. Try
SQL
SELECT  
      [dte]
      ,Year([dte]) as RP_Year
      ,[LOB]
      ,Sum([Cost]) as Sum_cost
     
  FROM xxx
  Where Year([dte]) = '2017'
  Group by [LOB]
 
Share this answer
 
Comments
Richard Deeming 27-Apr-17 12:02pm    
It would probably be better to use a SARGable query:
WHERE [dte] >= CAST('20170101' As date) And [dte] < CAST('20180101' As date)
Member 13156636 28-Apr-17 8:39am    
SELECT
Year([dte]) as RP_Year
,[LOB]
,sum([cost]) as sum_cost
FROM xxx
WHERE [dte] >= CAST('20170101' As date) And [dte] < CAST('20180101' As date)
Group by Year([dte]), [LOB]

now it says

Msg 8115, Level 16, State 2, Line 2
Arithmetic overflow error converting expression to data type int.
Member 13156636 28-Apr-17 8:46am    
i used
sum(cast([cost] as BIGINT)) as sum_cost
ant it works
CHill60 28-Apr-17 10:26am    
What type is cost

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900