Skip to content
Advertisement

Subtract sum of column from a column in sql

I am inserting First four column multiple times, with new paidVal . Now I want to get sid,snameVal, balance

I have used a inner join on studenttbl and feetlb.

here I have tried. But I am getting 3 row when I should get 2 only. In the table there is a field cNameVal, and as much different value i m entering I am getting that much row.

sql
SELECT studenttbl.sid,
       studenttbl.snameVal,
       studenttbl.sPhoneVal,
       coursefeeval - SUM(paidval) AS balance,
       CONVERT(varchar, studenttbl.sdateVal, 106) AS sdateVal
FROM feeTbl
     INNER JOIN studenttbl ON feeTbl.sid = studenttbl.sid
GROUP BY studenttbl.sid,
         studenttbl.snameVal,
         coursefeeval,
         sPhoneVal,
         sdateVal;

feetbl

 sid       snameVal cNameVal    courseFeeVal    paidVal 
    1001    Vivek     7            4000          1000   
    1001    Vivek     7            4000          1000   
    1002    Rahul     8            5000          1000   
    1002    Rahul     5            6000          5000   

Advertisement

Answer

With no expected results, this is based on this comment:

I want to get sid,snameVal, balance here balance means courseFeeVal - SUM(paidVal)'

Seems like you want a windowed SUM:

SELECT st.sid,
       st.snameVal,
       st.sPhoneVal,
       coursefeeval - SUM(paidval) OVER (PARTITION BY st.sid) AS balance, --2 of these columns need qualifying
       st.sdateVal AS sdateVal --leave dates as a date and time data time, don't convert to a string
FROM feeTbl fT
     INNER JOIN studenttbl st ON fT.sid = st.sid;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement