Calculate New Column in sql server

CREATE TABLE [dbo].[Table1](
    [Months] [int] ,
    [AccumSD] [decimal](38, 2)
GO
insert into [Table1]([Months],[AccumSD])
select 1    ,0.00
Union All
select 2    ,21574680.03
Union All
select 3    ,16706196.47
Union All
select 4    ,-7873127.29
Union All
select 5    ,-4235468.46
Union All
select 6    ,-2201146.63
Union All
select 7    ,-2102177.16
Union All
select 8    ,-315589.57
Union All
select 9    ,1638011.39
Union All
select 10    ,1826178.79
Union All
select 11    ,1883942.48
Union All
select 12    ,1585631.16
The above is the table structure and data.
I want to calculate the column from AccumSD + previous value of same column (AccumSD)
the calculated column should be like the below
0
21574680.03 
16706196.48 
13701552.75 
12470728.02 
11500406.13 
10368550.87 
11184816.56 
12006562.26 
13010995.35 
13890504.74 
14596626.51 
15540690.5 
16386422.24 
17231803.58 
18101710.92 
18971480.26 
19910089.6 
26235684.8 
32481280 
How can we achieve it? Thanks in advance

The formula from your excel screen grab does not match the formula you posted in your description.
Your example data does not match your screen grab.
Best of luck getting to an answer that works for you.
Agreed. While the OP may regard his maths to be good and his sample data spot on, it leaves their eyes as I fail to see how their data matches what they appear to be asking for.
OP, your first three rows are
select 1   
,0.00
select 2   
,21574680.03
select 3   
,16706196.47
How does that lead to
Select @A= 0 + 0
Select @A
 Select  @A=21574680 +@A
Select @A
 Select  @A= -4868484 + @A
Select @A
Where did "-4868484" come from?
Unless you give accurate requirements, how can anyone help you? Looking at your excel screenshot, you are negating, not summing.

Similar Messages

  • Desc doesn't show datetime columns from SQl Server

    Hi Everyone,
    I have working db link to sql server using hsodbc:
    Oracle 10.2 on AIX using freetds odbc driver version 0.82.
    I can access tables on sql server but oracle sees only varchars and numerics columns in a table.
    Is there a way to select datetime columns from sql server using hsodbc?

    when hsodbc does not show a certain data type it is commonly related to the fact that HSODBC doesn't support the related ODBC data type.
    In general you have a data type in your SQL Server which is mapped to an ODBC data type by the ODBC driver. HSODBC then maps the ODBC data type to an Oracle equivalent and when the ODBC data type isn't supported by HSODBC it just drops it from the select list.
    So for a root cause analysis an ODBC trace is required to determine the mapping of the FreeTDS ODBC driver.
    With this info we can then compare the mapping documented in the HSODBC manual and if the ODBC data type isn't listed as a supported data type you then need to cast the data type on the source side to a different data type (for example varchar/char).
    So please post the ODBC trace and I'll have a look.
    - Klaus
    Edited by: kgronau on Apr 2, 2013 12:50 PM
    BTW, here the link to the HSODBC docu:
    http://docs.oracle.com/cd/B19306_01/server.102/b14232.pdf
    Oracle® Database
    Heterogeneous Connectivity Administrator's Guide
    10g Release 2 (10.2)
    B14232-01
    B.1 Mapping ANSI Data Types to Oracle Data Types Through an ODBC
    Interface

  • SQL Server Radio - A new podcast for SQL Server professionals

    Hi everyone,
    We (Guy Glantser and Matan Yungman) have recently launched a new podcast for SQL Server professionals, called "SQL Server Radio".
    We release two shows a month, and basically talk about everything around SQL Server and the SQL Server community. On one show of each month, we juggle around and talk about interesting blog posts, forum discussions, news, events and other things that happen
    in the SQL Server world. We expand about each of those items and add from our own experience. On the second show of the month, we go more in-depth. Sometimes we bring a guest, and sometimes we talk about a specific topic like SQL Server 2014, conferences or
    professional development.
    So if you love SQL Server and love learning by hearing, whether you're on your way to work, jogging or just chilling and
    want to learn in a fun way, check us out on
    http://www.SQLServerRadio.com
    Two shows are already online..

    Hi everyone,
    We (Guy Glantser and Matan Yungman) have recently launched a new podcast for SQL Server professionals, called "SQL Server Radio".
    We release two shows a month, and basically talk about everything around SQL Server and the SQL Server community. On one show of each month, we juggle around and talk about interesting blog posts, forum discussions, news, events and other things that happen
    in the SQL Server world. We expand about each of those items and add from our own experience. On the second show of the month, we go more in-depth. Sometimes we bring a guest, and sometimes we talk about a specific topic like SQL Server 2014, conferences or
    professional development.
    So if you love SQL Server and love learning by hearing, whether you're on your way to work, jogging or just chilling and
    want to learn in a fun way, check us out on http://www.SQLServerRadio.com
    Two shows are already online..

  • What is Oracle's alternative to IDENTITY Column in SQL Server/ DB2

    What is Oracle's alternative to IDENTITY Column(Auto Increment Column) in SQL Server/ DB2 ? Is Sequence and Trigger the only way out for this?
    Why is Oracle not creating anything like an Identitiy column in SQL Server?

    What is Oracle's alternative to IDENTITY Column(Auto
    Increment Column) in SQL Server/ DB2 ? Is Sequence
    and Trigger the only way out for this?Of course not, you can use in your inserts sequences as well:
    insert into blahh values (my_seq.nextval, ...) and use returniong clause to get the value back if necessary
    You can use them in insert with subselects
    insert into blah
    select my_seq.nextval, ...
    from ....
    >
    Why is Oracle not creating anything like an Identitiy
    column in SQL Server?Because they are different companies with different people and thoughts and existing mechanism is sufficient i.e. one can even argue that it is even more flexible than identity btw ;)
    Gints Plivna
    http://www.gplivna.eu

  • New Login in sql server

    Hi,
       When I'm adding new login in SQL server it searches and gives the available AD groups in my domain in the Checknames box. Anyone knows what is the SP called when it searches the Group names from the domain?

    If you want to know what commands SSMS are emitting to SQL Server, you can use Profiler to find out.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • How to convert rows to columns in sql server 2008

    How to convert rows to columns in sql server 2008 using the GROUP BY function? (only one query allowed)

    Lookup the Pivot transformation. From BOL:
    The Pivot transformation makes a normalized data set into a less normalized
    but more compact version by pivoting the input data on a column value. For
    example, a normalized Orders data set that lists customer name, product, and quantity purchased typically has multiple rows for any customer who purchased multiple products, with each row for that customer showing order
    details for a different product. By pivoting the data set on the product column, the Pivot transformation can output a data set with a
    single row per customer. That single row lists all the purchases by the customer, with the product names shown as column names, and the quantity shown as a value in the product column. Because not every customer purchases every product, many columns may contain
    null values.
    When a dataset is pivoted, input columns perform different roles in the pivoting process. A column can participate in the following ways:
    The column is passed through unchanged to the output. Because many input rows
    can result only in one output row, the transformation copies only the first
    input value for the column.
    The column acts as the key or part of the key that identifies a set of
    records.
    The column defines the pivot. The values in this column are associated with
    columns in the pivoted dataset.
    The column contains values that are placed in the columns that the pivot
    creates.
    Paul

  • How mapping sharepoint list Columns to Sql server data table columns programaticlly

    Hi ,
     I have one Verification List in share Point ,in that list i have 10 columns.And we have sql server in that sql server we have one data table Verification_Table
    in that table we have 25 column, my requirement is all list data  move to  sql data table[ what ever columns mapping to list--->data table that data store in data table reaming column is  Null]
     using grammatically not in BCS

    Hello,
    You can create SQL connection and use Datareader to read from SQL.Firs create a connection string and put this string in web application web.config file of your sharepoint site.
    Now use below code to call your connectionstring in your webpart.
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
    Here is link to read the data from SQL:
    http://www.akadia.com/services/dotnet_data_reader.html
    Here is one MSDN link to read SP list data:
    http://msdn.microsoft.com/en-us/library/dd490727%28v=office.12%29.aspx
    Let me know if you have any doubt
    Hemendra:Yesterday is just a memory,Tomorrow we may never see
    Please remember to mark the replies as answers if they help and unmark them if they provide no help

  • How to Encrypt Column in SQL Server?

    Hi all,
    I am using ColdFusion MX 7 and Microsoft SQL Server 2000
    database. I have a column that contains social security numbers of
    my users and am feeling the need to encrypt that column.
    Trouble is, I have no clue how to do this in SQL Server or
    how I could display the data from that column in my web app once
    the column is encrypted.
    Can anyone offer any suggestions?
    Thanks in advance!

    Here's one way...
    To encrypt:
    URLEncodedFormat(Encrypt(yourSStoencrypt,
    application.encKey)) then
    store this value in MSSQL
    To decrypt:
    Decrypt(URLDecode(yourSStodecryptfromDB), application.encKey)
    HTH
    Tim Carley
    www.recfusion.com
    [email protected]

  • Create Column in SQL Server

    Hi all,
         I am having below table.
    create table Student_Register
    Name varchar(30),
    FatherName varchar(35),
    Address1 varchar(100),
    Address2 varchar(100),
    Place varchar(75),
    Pincode int,
    SchoolName varchar(100),
    StandardStudy varchar(15)
    I am creating after trigger on the above table and inserting into the below table.
    create table StudentDetails
    Name varchar(30),
    FatherName varchar(35),
    Address1 varchar(100),
    Address2 varchar(100),
    Place varchar(75),
    Pincode int,
    SchoolName varchar(100),
    StandardStudy varchar(15)
    I need to create one computed column in studentdetails as StudentID with StandardStudy+Replicate(0,3)+lastvalue+1
    5th student id
    50001
    50002
     12th student like
    120001
    120002
    120003
    how to implement above logic pls ?
    Thanks
    Selvaons
    Thanks - SelvaKumarSubramaniam.Please MARK AS ANSWER, if my answer is useful to U.

    see
    http://www.sqlteam.com/article/custom-auto-generated-sequences-with-sql-server
    You can make it computed column based on UDF
    make UDF as below
    CREATE FUNCTION GenerateStudID
    @StdStudy varchar(15)
    RETURNS int
    AS
    BEGIN
    DECLARE @StudID int
    SELECT @StudID = @StdStudy * 10000 + COALESCE((SELECT MAX(StudentID) FROM StudentDetails WHERE StandardStudy =@StdStudy),0) + 1
    RETURN (@StudID)
    END
    then create column as
    ALTER TABLE StudentDetails ADD StudentID AS dbo.GenerateStudID(StandardStudy)
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Accessing IMAGE Columns in SQL Server

    I'm trying to use the TG4MSSQL to access tables in a SS2k database. All is well, except for 1 table that has an IMAGE column in it. I must say that I'm a little surprised and disappointed that the 10gR2 gateway for MSSQL apparently translates these things into LONG RAW columns, which are known to be antiquated and minimally supported. However, I still need access to the data, and ultimately, I need it in a BLOB. Doing simple queries (in TOAD) such as:
    select * from image@tg4ss where image_id = 1;
    returns the row, and I can use TOAD to determine that all the data is there. However, apparently, you cannot use PL/SQL to bind more than 32K of this data into a variable, so I haven't had much success there.
    The only way I know of converting a long raw to a blob is to use the to_lob function, but that's only good in the select list of a subquery of an insert statement. Thing is, that doesn't seem to work with the gateway. I tried something like:
    insert into my_blob_table( id, image )
    select id, to_lob(image) as image from image@tg4ss where id = 1;
    That gets me a ORA-00997: illegal use of LONG datatype.
    In fact, I can't even do this:
    insert into my_long_raw_table( id, image )
    select id, image from image@tg4ss where id = 1;
    I get the same error on that command.
    Now, I can do this, but I only get the first 32k of the image:
    begin
    for I in (select id, image from IMAGE@tg4ss)
    loop
    insert into my_long_raw_table( id, image )
    values (I.id, I.image);
    end loop;
    end;
    So, does anyone know how you can get image data out of an SQL Server database into a blob value? If so, I'd appreciate a reply. Thanks.
    -Rich.

    Hello Rich,
    I found your article after running into the same problem. I imagine you've dealt with this one way or another already but just in case...
    The reason the LONG RAW gets truncated is explained in:
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/datatypes.htm#i43252
    Basically, LONG RAW variables are limited to 32760 bytes inside PL/SQL. The ORA-00997 error is explained a little in:
    http://www.dbaxchange.com/3_4_longdatatypes.htm
    The only solution I found to work was to create a Java utility that read in each LONG RAW value (one at a time) and then update a record in a table's BLOB column. This was even a bit tricky. I found the gateway would lock up if I tried to do too much at a time. I kept it simple my reading all column IDs into an array and then looping through the array while executing a simple select statement that retrieved the LONG RAW value. I concatenated the id to the end of the select statement because prepared statements seemed to be one of the reasons the gateway locked up. I used a ByteArrayInputStream object to populate the BLOB in an update prepared statement for each LONG RAW value processed in the loop.
    - Aaron

  • How to export an image column from SQL server to an excel

    Hi team,
    Would like to know how can i get an Image column storeed in SQL Server database to get copied in Excel (Hard Drive).
    Requirement : Need to get Username, User email address and User photo in to an excel sheet from SQL server database.
    Fix: I can get Username and Useremail adress however could not find a way to export /Copy user Image.
    Please suggest
    Thanks,
    venkatesh

    This is an Oracle forum. Your question relates to SQL Server and Excel, neither of which are Oracle related.

  • New Files in SQL Server Log Directory

     Does anyone know which process generates files to C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Log.
    I started seeing new files are added from yestoday. The file name pattern is like "ServerName_MSSQLSERVER_SQLDIAG_0_130632533281120000.xel".
    Thanks,

    Can you right click and script the system_health session monitor? Check the corresponding path and name of the file.
    Its enabled by default. The system_health session collects system data that can be used to help troubleshoot performance issues.
    I think someone has created the file.
    --Prashanth

  • How can I export image column from SQL Server 2000

    Hi everybody,could someone tell me how can I export an entire column( pictures type) to a folder on disk?I've tried the textcopy.exe under the SQL installation's binn folder,it can only export one picture a time,I'm trying to find an automated way to export
    the whole colum's images to a folder,I'm using SQL Server 2000.

    Vishal,thanks for the replay,I've tried the BCP method but it seems does not work on my Sql Server 2000,also the SSIS package method is demonstrated with Sql Server 2008 R2 and my machine does not have the visual application to try it.In the BCP method,I
    got prompt  indicating me that I wrote something wrong in the grammer,and I'm pretty sure that maybe I made something wrong in the below part,the grammer makes me confused
    INSERT
    INTO @sqlStatements
    SELECT 'BCP "SELECT Photograph_Data FROM [ALBSCH_Trial].[dbo].[Photograph] WHERE Photograph_ID = '''
    + CAST(Photograph_ID AS VARCHAR(500)) + '''" queryout ' + @OutputFilePath
    + CAST(Photograph_ID AS VARCHAR(500)) + '.jpg -S localhost\SQLEXPRESS2008 -T -f C:\SQLTest\Images.fmt'
    FROM dbo.Photograph

  • Nvarchar column filter - SQL server

    Hello,
    I am using OBIEE 10.1.3.4.2 and I have problem with filtering data coming from SQL server 2008. I am using ODBC connection to access SQL server data. I can see results of my queries without any problem.
    But I have problem with filtering.
    My answer use these columns:
    Id (varchar(36))
    Code (nvarchar(256))
    Name (nvarchar(256))
    HappenedOn (date)
    Please look on this screenshost:
    http://img59.imageshack.us/img59/5242/obieenvarcharcolumn.jpg
    Screenshot
    I have problem when I want to use filter on Code column and use some non-english characters. Specifically Czech characters in windows1250 code page. With that filter I am getting "No result" view. But generated select is working in Microsoft SQL Server Management Studio.
    I think there is some problem with ODBC resource or BI configuration, but I can not find reason of this behaviour.
    Do I need to make some specific configuration to use NVARCHAR columns? Specifiy some encoding etc....
    Thank you

    Thank you Dpka...
    Checking UNICODE option on Write Back tab solved my problem. It is realy nice hidden property :-)
    But my fight is not over...
    Now I am getting error when I try to make join between table from Oracle and table from SQL server.
    It is a Bug ID 9147807 and I hope that Patch (9147807: INCORRECT SYNTAX NEAR 'SESSION' WHEN QUERYING FRAGMENTED LOGICAL FACT TABLE) will help me.

  • New install of SQL Server 2012 x64 Express on Windows 2008 Server, keep getting error when using Management Studio?

    After installing the x64 with all tools excluding the SDK from the SQL Express Edition, I go to Management Studio, log in and get the error when I click under the Instance name- Databases...Have reinstalled many times, removed all directories and registry
    keys from both HKEYs(regular and Wow6432Node) before rebooting and reinstalling. No VS installed on this computer..put it looks like it installed "MS Visual Studio 2010 Shell (Isolated)-ENU" and "Visual Studio 2010 Prerequisites".....tried working past
    the error, it just hangs the Studio after it tries to add things...HELP..PLEASE!!!
    Object reference not set to an instance of an object. (Microsoft.VisualStudio.Platform.WindowManagement)
    Program Location:
       at Microsoft.VisualStudio.Platform.WindowManagement.DocumentObjectSite.QueryService(Guid& guidService, Guid& riid, IntPtr& ppvObject)
       at Microsoft.VisualStudio.Shell.ServiceProvider.GetService(Guid guid, Type serviceType)
       at Microsoft.VisualStudio.Shell.ServiceProvider.GetService(Type serviceType)
       at Microsoft.VisualStudio.Shell.WindowPane.GetService(Type serviceType)
       at Microsoft.SqlServer.Management.SqlStudio.Explorer.ObjectExplorerToolWindow.GetService(Type serviceType)
       at Microsoft.VisualStudio.Shell.WindowPane.System.IServiceProvider.GetService(Type serviceType)
       at System.ComponentModel.Design.ServiceContainer.GetService(Type serviceType)
       at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.ObjectExplorerControl.GetService(Type serviceType)
       at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.ObjectExplorerControl.System.IServiceProvider.GetService(Type serviceType)
       at System.ComponentModel.Design.ServiceContainer.GetService(Type serviceType)
       at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItem.GetService(Type serviceType)
       at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NodeContext.GetService(Type serviceType)
       at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItemBuilder.<GetColumnsFromNavigationService>d__11.MoveNext()
       at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItemBuilder.AddFields(List`1 list, IEnumerable`1 fields, IDictionary`2 allValidFields, AddFieldsFlags flags)
       at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItemBuilder.GetParentFields(INodeInformation source, Dictionary`2& allValidColumns)
       at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItemBuilder.BuildDynamicItemWithQuery(IList`1 nodes, INodeInformation source, INavigableItem sourceItem, String urnQuery, Boolean registerBuilder, Boolean registerBuiltItems)
       at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItemBuilder.BuildDynamicItem(IList`1 nodes, INodeInformation source, INavigableItem sourceItem, IFilterProvider filter)
       at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItemBuilder.Build(IList`1 nodes, INodeInformation source, INavigableItem sourceItem, IFilterProvider filter)
       at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItem.RequestChildren(IGetChildrenRequest request)
       at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.ExplorerHierarchyNode.BuildChildren(WaitHandle quitEvent)

    Hi igorteper,
    Any progress?
    "MS Visual Studio 2010 Shell (Isolated)-ENU" and "Visual Studio 2010 Prerequisites" had been installed in your computer, or there is no Visual Studio installed on this computer?
    You log in SQL Server Management Studio and get an error. For further investigation the issue, please post the error messages in detail.
    TechNet Subscriber Support
    If you are TechNet Subscription user and have any feedback on our support quality, please send your feedback
    here.
    Thanks,
    Maggie
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. This can be beneficial to other community members reading the thread.

Maybe you are looking for

  • Simple XI Scenario

    Hi friends , I am learning XI and right now working on simple XI scenario for Idoc to IDoc . I want to send Sales notification from sandbox sap system to ides sap system.I am able to do it in ale  but nw want to do it in XI. In XI, SLD part is done.

  • How can I get the steps recorded on my iPhone in HealthVault automatically?

    I have been recording my steps in the iPhone, but I do not see an easy way to transfer this data to HealthVault.

  • Currency field in Generic Data Source

    Hi All, I have a case here, where i have few Amount field in my Generic Extractor which is based on a table ZXXX. Now the key figures have 0currency appended in theie currency tab which is coming from table ZYYY, now while saving the data source is g

  • I want to find different time interval btw two times

    hi every body, my question : i ll give start time and end time as input. i want output ,time interval btw start time and end time for exp:  i ll give 7 to 11 as input.     tables have data like   7   to  7.29.59  --->  1 prog                         

  • Gifting a customized wish list

    I am not sure how to make this work with the latest version of iTunes. I have created the list from my wishlist but there is no option to gift the list. Can someone tell me what I am missing?