Click here to Skip to main content
15,898,374 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Pid Sales Month1
1 10 Jan
2 30 Feb
3 60 Mar
4 50 Apr



based on Month1 How to Display sales values diffrence


Like
OutPut

Pid Sales Month1 Differe
1 10 Jan 0
2 30 Feb -20
3 60 Mar -30
4 50 Apr 10
Posted

Try this:
SQL
select t1.pid, t1.sales, t1.month1,
isnull((select t2.sales from table1 t2 where t2.pid = t1.pid - 1) - t1.sales, 0) as differe
from table1 t1
 
Share this answer
 
v2
Comments
Member 10675465 17-Mar-14 6:12am    
thanks its working
Peter Leow 17-Mar-14 6:41am    
You are welcome.
Depends on your database and version thereof.
If it's new enough you can use the analytical function Lag
SQL
Select  Pid,
        Sales,
        Month1,
        LAG(sales, 1, 0) OVER (PARTITION BY Pid ORDER BY Month1) - sales as difference
FROM    MyTable
For other solutions you need to state your Database and model as it differs a bit between them

<update>
You can also use Row_Number:
SQL
With ordered as (
    Select  Pid,
            Sales,
            Month1,
            Row_Number() OVER (PARTITION BY Pid ORDER BY Month1) rn
    FROM    MyTable
    )
Select  O1.Pid,
        O1.Sales,
        O1.Month1,
        O2.Sales - O1.sales as Difference
FROM    Ordered O1 left outer Join Ordered O2 on O1.rn = O2.rn - 1
</update>
 
Share this answer
 
v5
Comments
Member 10675465 17-Mar-14 3:35am    
Its Not working error i am getting Msg 195, Level 15, State 10, Line 4
'LAG' is not a recognized built-in function name.

My Database is sql2005
Jörgen Andersson 17-Mar-14 3:59am    
Lag doesn't exist in SQLServer 2005, but Row_Number does. Updated solution.
Member 10675465 17-Mar-14 4:08am    
notworking i am getting error Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'OVER'.
Jörgen Andersson 17-Mar-14 4:24am    
fixed typo
Member 10675465 17-Mar-14 4:28am    
No luck below error i am getting Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value 'Jan' to data type int.

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