SQL Server - Subtract value 2 from value 1 in sql

Asked By Priyanka on 23-Feb-14 10:57 AM
with cte as
(
  select userid, parentid from  user_detail where userid = '100002'
  union all select t.userid, t.parentid
  from  user_detail t inner join cte on cte.userid = t.parentid
 )
  
   SELECT (10 - B.AMOUNT) AS DUE FROM cte AS A
   CROSS APPLY (SELECT SUM(Pairs) AS AMOUNT FROM payout WHERE user_id = '100002') AS B
   WHERE A.userid = '100002'
   
  
 
i have to change below line from above code :
SELECT (10 - B.AMOUNT) AS DUE FROM cte AS A
 
i have to subtract, total number of rows in cte from B.Amount instead of 10 - B.Amount.
 
i.e No.of rows in cte - B.Amount.
 
when i try something like below it gives error :
SELECT (count(*) - B.AMOUNT) AS DUE FROM cte AS A
Error is :
Msg 8120, Level 16, State 1, Line 8
Column 'B.AMOUNT' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
 
otherwise it works fine..
Hope you understand my question..
Erik Little replied to Priyanka on 28-Feb-14 02:58 PM
Where are you getting the B.AMOUNT column from?

You might want to create a column list in your cte expression so that you can reference B.AMOUNT because as of now there is no B.AMOUNT column, or am I missing something?