Hi guys, I've really been struggling with this issue for quite a while and the solution still elludes me.
If anyone can help me I will worship you as a god for ever! [Wink]
The Scenario is as follows:
I have a table where several documents are linked to each other via a foreign key called ReconNum.
Basically this table is used to link Invoices, Credit Notes and Payments to each other.
Thus you get the following layout:
I've come close, but it seems to be the old chicken or the egg problem.i.e. I need one field to calculate the other and vica-versa.
(Amount Applied, DocBal and Inv Bal are all dependant on each other)
NOTE: The only field I'm really interested in is the AmountApplied field, but amount applied depends on the DocBal and InvBal fields.
I need a running balance on both the Amount Due on the Invoice, and the Amount Availble on the document being assigned to the invoices. The problem is that I'm trhowing the data into a temporary table and cant use fields in the temp table for my calculation.
i.e. AppliedSum = if (Doc.Available amount on Doc < Invoice Balance) then Doc.Available Amount
elseif (Doc.Available amount on Doc > Invoice Balance) then Invoice Balance
Invoice Balance = Invoice Tot - sum(Applied Amounts)
I have a doubt regarding balance sheet calculation in my Software. I am using a stored procedure for these calculations. I have some commands for calculation as given below:
INSERT INTO #Temp (cargo_required, amount_general, amount_ship, amount_shore) SELECT 5000, 1500, 1450, 1490 UNION ALL SELECT 0, 3500, 3500, 3500 UNION ALL SELECT 7000, 4500, 4550, 4560 UNION ALL SELECT 0, 2500, 2000, 2000
DECLARE temp_cursor CURSOR FAST_FORWARD FOR SELECT rec_id, cargo_required, amount_general, amount_ship, amount_shore FROM #Temp
OPEN temp_cursor
FETCH NEXT FROM temp_cursor INTO @tab_id, @car_req, @amt_gen, @amt_shp, @amt_sho
WHILE @@FETCH_STATUS = 0 BEGIN IF (@car_req > 0) BEGIN UPDATE #Temp SET balance_general = @car_req - amount_general ,balance_ship= @car_req - amount_ship ,balance_shore= @car_req - amount_shore WHERE rec_id = @tab_id END ELSE BEGIN UPDATE #Temp SET balance_general = @bal_gen - amount_general ,balance_ship= @bal_shp - amount_ship ,balance_shore= @bal_sho - amount_shore WHERE rec_id = @tab_id END
SELECT @bal_gen = balance_general, @bal_shp = balance_ship, @bal_sho = balance_shore FROM #Temp WHERE rec_id = @tab_id
FETCH NEXT FROM temp_cursor INTO @tab_id, @car_req, @amt_gen, @amt_shp, @amt_sho END
This is what acutally I am having in my stored procedure except the temporary table. The values which I am inserting here will get from my actual tables. What I need is to calculate balance. If you run this script you can see how the balance is calculating using the cursor.
I want an efficient way to calculate the same. I know cursor is not at all good option in stored procedures. Do you have any Idea to make this script in an efficient and simple way?
I have a doubt regarding balance sheet calculation in my Software. I am using a stored procedure for these calculations. I have some commands for calculation as given below:DECLARE @bal_gen FLOAT DECLARE @bal_shp FLOAT DECLARE @bal_sho FLOAT DECLARE @tab_id INT
INSERT INTO #Temp (cargo_required, amount_general, amount_ship, amount_shore) SELECT 5000, 1500, 1450, 1490 UNION ALL SELECT 0, 3500, 3500, 3500 UNION ALL SELECT 7000, 4500, 4550, 4560 UNION ALL SELECT 0, 2500, 2000, 2000
SELECT @bal_gen=0,@bal_shp=0,@bal_sho=0 SELECT @tab_id=MIN(rec_id) FROM #Temp
WHILE @tab_id IS NOT NULL BEGIN UPDATE #Temp SET @bal_gen=balance_general =CASE WHEN cargo_required > 0 THEN cargo_required ELSE @bal_gen END - amount_general , @bal_shp=balance_ship = CASE WHEN cargo_required > 0 THEN cargo_required ELSE @bal_shp END - amount_ship , @bal_sho=balance_shore = CASE WHEN cargo_required > 0 THEN cargo_required ELSE @bal_sho END - amount_shore WHERE rec_id = @tab_id
SELECT @tab_id=MIN(rec_id) FROM #Temp WHERE rec_id >@tab_id END
Select * FROM #Temp This is what acutally I am having in my stored procedure except the temporary table. The values which I am inserting here will get from my actual tables. What I need is to calculate balance. If you run this script you can see how the balance is calculating using the WHILE loop.
I want an efficient way to calculate the same. Is there any way to calculate it without using loop methods. Thanks and Regards Boney
I am working on a software primarily related to accounting with visual basic
Many of the problems and proposed several solutions for running sum, but I have read almost all of these interpretations,
have applied when running sum is a unique ID field. but almost all of the functioning of accounting reports are in chronological order. So he questioned what was the balance on 05.05.2012.
ID of the process is done, if the user enters a process backward a few things since then, the transaction date is old, but the ID is new, are experiencing problems. eg
ID DATE DEBIT CREDIT BALANCE
1 02.02.2012 100.00 0.00 100.00
6 04.04.2012 0.00 150.00 -50.00
3 02.05.2012 70.00 0.00 20.00
4 02.05.2012 80.00 0.00 100.00
2 06.06.2012 120.00 0.00 220.00
must balance the figure above.
if ID = 2 record, the record date 06/06/2012 and if the ID = 6, date 04/04/2012, the date the order is made if the listing is experiencing trouble getting balance. 2 records in the same day when the balance at worst formula breaks down. The big point is that I hang out in my project.
the only solution is to use a temporary table or writing about it in Visual Basic seems to calculate. the use of temporary table is not a solution, but unfortunately also very fast.
I am creating a query that shows the consumption of stock against Manf Orders (M/O) and struggling on the last hurdle. I am having difficulties calculating a running total based on an Opening Balance. The first line returns the correct results but the following lines do not. I have tried other variants of the "Over Partition" but still no joy?
SELECT CASE WHEN ROWNUMBER > 1 THEN '' ELSE A.Component END AS Component , CASE WHEN ROWNUMBER > 1 THEN '' ELSE A.SKU
I created a view that i want to use in ssrs.In the view there is a column for running balance.In the table contain transaction of inventory with their quantity.
"SELECT TOP (100) PERCENT ITEMNMBR, TRXSORCE, DOCTYPE, DOCNUMBR, DOCDATE, HSTMODUL, UOFM, UNITCOST, EXTDCOST, TRXQtyInBase, (SELECT SUM(TRXQtyInBase) AS Expr1 FROM dbo.INVTRXB AS b WHERE (DEX_ROW_ID <= a.DEX_ROW_ID) AND (ITEMNMBR = a.ITEMNMBR)) AS ENDQTY FROM dbo.INVTRXB AS a ORDER BY ITEMNMBR, DOCDATE"
If i run the query on sql or use the view on ssr. The end qty is not showing accurately.I ran it on another database it works perfectly. Then i noticed that the dex_row_ID of the second database is sequential as the date. But for the initial database it was not sequential as with the date.
I have a table with Million plus records. I have been able to calculate the Trial_Balance for all months.
Now I am trying to provide a Beginning Balance for all months and the Logic is the Beginning Balance of July would be the Trial_Balance of June. I thought I could just do a self Join but this is not working.
UPDATE dbo.TrialBalance SET Beginning_Balance_Debit = B.Trial_Balance_Debit FROM (SELECT DATEADD(month, -1, Calendar_Month) AS PrevCalMonth,Trial_Balance_Debit FROM dbo.TrialBalance) AS B INNER JOIN dbo.TrialBalance A ON b.PrevCalMonth=A.Calendar_Month
Hallo, for my project I need to calculate the estimated time an SQL statement will be running. The statements will be composed via a GUI and get become very complex. So the user needs a rough time approximation of how long to wait for the answer. A few seconds, ten minutes or several hours!?
My question: Does anyone know good links, articles or other source to get familiar with this topic? I'd also like to start a little discussion. On what does the runtime depend? (Is runtime the right word here?) Number of JOINs Number of different tables Size of the tables Complexity of the WHERE-Condition ("id=5" or rather "name LIKE '%foo%'") Indizes Hardware Number of users on the DBWhat else influences the time and how?
Aside from that I found the "SET SHOWPLAN_XML ON" for SQL Server 2005 to get the execution plan of the query.
But I can't find a reasonable listing of the elements and attributes and their meaning. I think StatementSubTreeCost sound interesting. Is that the time, the statement needs to run or what does the number 0.0033205 say?
Is anyone familiar with the SHOWPLAN_XML? Or can anyone provide me a link about the values of this plan, perhaps in the Microsoft-MSDN area!? The principle is clear. But what about the values in detail. There must be a documentation somewhere!
INSERT INTO MAIN VALUES ('1000', '1/1/2014',3000,1000,700,1500) INSERT INTO MAIN VALUES ('1000', '3/5/2014',1000,2000,650,200) INSERT INTO MAIN VALUES ('1000', '5/10/2014',500,5000,375,125) INSERT INTO MAIN VALUES ('1000', '11/20/2014',100,2000,400,300) INSERT INTO MAIN VALUES ('1000', '8/20/2014',100,3500,675,1300)
I have created calcalated measures in a SQL Server 2012 SSAS multi dimensional model by creating empty measures in the cube and use scope statements to fill the calculation.
(so I can use measure security on calculations
as explained here )
SCOPE [Measures].[C];
THIS = IIF([B]=0,0,[Measures].[A]/[Measures].[B]);
I am trying to write a trigger which updates the customers balance when an invoice is deleted. The tables are created and I can post if needed, but I get a compilation error when I use the follow code.
create or replace trigger trg_updatecustbalance2 after delete on invoice for each row begin update customer set cust_balance = cust_balance - inv_amount where customer.cust_num = invoice.cust_num; end; /
dear all experts please kindly provide ur help thanks.
suppose i hv 2 records in a table as follow:
customer_id status qty date
123456 install 24 2008-02-20
123456 disconnect -24 2008-02-20
how can i exclude these 2 records from my table? actually you can see the net gain is 0, but in my report reflects install qty is 24 and disconnect qty is -24. i dont want these 2 records reflect in my report, how can i achieve such result? thanks in advance!
I started to use data mining sql server recently, and I have a little problem:
I'm trying to predict a boolean variable, but my database has only 1/4 of true results, because of that my predict probability is a little bit low in this kind of cases.
My question is: Is there a way of increasing the importance of a database entry in order to avoid editing a database with 40000 entries?
For our application we are planning 4 Appserver/webservers with load balancing and 4 SQL servers in cluster with active/active setup. We are looking for some info on the active/active setup for SQL server 2000 Clustering.
1. Which cluster node replication method (2n, 2n +p or n+1) we should go for. 2. How operating system "windows 2003 server" should be configured and its role in failover. 3. How active/active failover setup for SQL Server 2000 really works and how much data loss happens in case of failover. 4. For web applications, how the session state is managed in SQL Clustering
I am novice to intermediate writer of T-SQL. Here is my current Query:
SELECT [FISCALYEAR], [ACCTPERIOD], SUM([ACTIVITYDEBIT]) AS TrialBalanceDebit, [POSTINGTYPE] FROM [dbo].[TB_Lookup] WHERE [POSTINGTYPE]='Profit & Loss' GROUP BY [FISCALYEAR],[ACCTPERIOD], [POSTINGTYPE] ORDER BY acctperiod ASCand this is what is produces.
FISCALYEARACCTPERIODTrialBalanceDebitPOSTINGTYPE 2014 201401 282361372.13000 Profit & Loss 2014 201402 227246272.86000 Profit & Loss 2014 201403 315489534.33000 Profit & Loss 2014 201404 287423793.76150 Profit & Loss 2014 201405 256521290.76000 Profit & Loss 2014 201406 65582951.30000 Profit & Loss
Now I need a way to add another field that takes the TrialBalanceDebit from current ACCTPERIOD and adds it to the Previous ACCTPERIOD TrialBalanceDebit.
My company is planning on using a datacenter for our customers. These are manufacturing plants from which we collect batch and trend data (currently stored in SQL Server)
helo all...,i have create procedure can decrease totalcost from order table(database:games.dbo) with balance in bill table(database:bank.dbo). my 2 database in same server is name "boy" i have 2 database like: bank.dbo and games.dbo in games.dbo, have a table name is order(user_id,no_order,date,totalcost) in bank.dbo, have a table name like is bill(no_bill,balance) this is a list of bill table no_bill balance 111222 200$ 222444 10$ this is a list of order table user_id no_order date totalcost a 1 1/1/07 50$ when customer insert no_bill(111222) in page and click a button, then bill table became no_bill balance 111222 150$ 222444 10$ when customer insert no_bill(222444) in page and click a button, then message "sorry, your balance is not enough" mystore procedure like:ALTER PROCEDURE [dbo].[pay]( @no_bill AS INT, @no_order AS int, @totalcost AS money)ASBEGIN BEGIN TRANSACTION DECLARE @balanc AS money SET @balanc= (SELECT [balance] FROM Bank.dbo.bill WHERE [no_bill] = @no_bill) UPDATE [bank.dbo.bill] SET [balance] = @balanc - @totalcost WHERE [no_bill] = @no_bill COMMIT TRANSACTIONEND it can decrease money in bank, but i want it ceck money if balance > totalcost, so balance-totalcost,if balance<totalcost,so error message"sorry, your balance not enough"is it can make in procedure?thx...
I think this question has been asked number of times. However, I amlooking for some specific information. Perhaps some of you can helpclose the gap. Or perhaps you can point me towards right direction.Perhaps this group can help me fill in ms-sqlserver related followingquestions.1. Do this database have data Clustering capabilities?1a. If yes, what mechanism is used such as shared disk, share nothing,etc.2. Do these dB have Security features?2a. If yes, what security features are supported? For instance do theysupport encryption or SSL connection?3. How does the database perform and what is the criteria for theperformance matrix?4. Do they have inbuilt load balance capabilities?I want to thank everyone for taking your time to read thiscorrespondence. I will also greatly appreciate your efforts in sharingyour thoughts.Regards,Manish
Currently we have a single SQL server. It went down and the higher ups were none to happy. Lots of money lost, down time, unhappy customers....the whole nine yards. They want to throw all sorts of money at the problem and want a solution that is high availability and provides load balancing. I think I came up with a solution.
3x Windows 2003 Enterprise Edition servers running SQL 2005 Standard in a cluster all connected to a SAN.
I'm guessing I need to set up Network Load Balancing in order to load balance the SQL database. What we would love to have happen is if one of the servers goes down, everything else just picks up. That coupled with our database that is increasing in size and transactions gets load balanced.
Am I going down the right path? Something else I should look at? Or that I am missing?
Currently we have a single SQL server. It went down and the higher ups were none to happy. Lots of money lost, down time, unhappy customers....the whole nine yards. They want to throw all sorts of money at the problem and want a solution that is high availability and provides load balancing. I think I came up with a solution.
3x Windows 2003 Enterprise Edition servers running SQL 2005 Standard in a cluster all connected to a SAN.
I'm guessing I need to set up Network Load Balancing in order to load balance the SQL database. What we would love to have happen is if one of the servers goes down, everything else just picks up. That coupled with our database that is increasing in size and transactions gets load balanced.
Am I going down the right path? Something else I should look at? Or that I am missing?
Thanks and sorry for posting this in multiple places!
I am struggling with the Lastdate function. I have got stock balance data and want to show the number of products/models that are on stock at the latest date of the stock balance table.
I get the wanted results for all aggregated product groups, on product/model level however the formula does not give me the information wanted (see screenshot).
Basically, the formula calculates correct, but I want in my example only models shown with the date 2015-10-21.
I have query that calculate a running balance, but I need to reset that balance when it reaches 240. Then start calculating the balance again from that value. For instance, let's see we have the following table:
I am preparing a monthly cash flow statement and for doing so, I need to determine the monthly opening and closing cash balance. To simplify, this is what I did.
1. Dragged months to the columns labels
2. Created a slicer for selecting the Financial Year. In this slicer, I chose 2015-16 i.e. April 1, 2015 to March 31, 2016.
Since I have data only for two months of this Financial Year i.e. April and May, only these two months show up in the column labels.
To determine the monthly opening cash balance, I added the following measure
Much to my surprise, I got the result as seen in the image below. Cells B5, C6 and D5 are blank. On going through my Bank Book, I realised that
1. There is no figure in cell B5 (Opening balance of April) because there was no transaction on the last day of March i.e. March 31. The last transaction was on March 28
2. There is no figure in cell C6 (Closing balance of May) because there was no transaction on the last day of May i.e. May 31. The last transaction was on May 30
3. There is no figure in cell D5 (Opening balance of June) - same reason as mentioned in point 2 above.
As seen in the image, I have also computed the monthly "Last date of previous month" and "last date of current month" but do not know how to make use of them in computing the opening and closing Cash balances.
Please also note that there can be multiple transactions on the last day of any month. For e.g., let's say the last day of transaction in May 2015 was May 30 (not may 31) but there were multiple transactions on this last day (both inflow and outflow).
So I cannot simply determine the last day of transaction and take MAX/MIN/SUM that day. I have to take the final balance on that day.
How to solve this problem i.e. in determining the opening and closing cash balances.
I have one query which is pulling Balance sheet amounts from SAP Business One database. The query is giving the correct figures for the rest of the accounts except for the VAT Input refundable account 123600 and VAT Output Payable account 221400. The query sums up totals at Title account level(FatherNum) and the above accounts are the title accounts:
SELECT CAST(T0.TransId AS Varchar(30)) AS TransId, CASE WHEN t3.FatherNum IN ('100000', '350000') THEN '-3 OK' ELSE CAST(T0.TransType AS Varchar(30)) END AS TransType, CAST(T0.BaseRef AS VarChar(30)) AS BaseRef, T0.RefDate,T0.Number as Docnum, DATEPART(Month, T0.RefDate) AS JrnMonth, T0.FinncPriod, T1.Account, T1.Debit, T1.Credit, T1.Debit - T1.Credit AS JrnAmt, ISNULL(T1.SYSCred, 0) AS SysCred, ISNULL(T1.SYSDeb, 0) AS SysDeb, T1.ShortName, T1.Ref1, T1.Ref2,
I have a Table Having Date,Opening,Addition,Sale values where opening value comes in the very first row other times it is zero.
In ssrs how can i have a report showing closing value = Opening+Addition-Sale in current row (it is simple for 1st row ). this closing be the opening value in next row and same formula to be continued...
In my environment, there is maintenance plan configured on one of the server and while running DBCC checkdb on a database of size around 200GB, log file usage of tempdb is increasing and causing the maintenance job to fail.
What can I do to make the maintenance job run successfully, size of the tempdb database is only 50GB and recovery model is set to simple. It cannot be increased as the mount point on which it is residing is 50GB.
If I start a long running query running on a background thread is there a way to abort the query so that it does not continue running on SQL server?
The query would be running on SQL Server 2005 from a Windows form application using the Background worker component. So the query would have been started from the background workers DoWork event using ado.net. If the user clicks an abort button in the UI I would want the query to die so that it does not continue to use sql server resources.
One of my stored procs, taking one parameter, is running about 2+ minutes. But if I run the same script in the stored proc with the same parameter hardcoded, the query only runs in a couple of seconds. The execution plans are different as well. Any reason why this could happen? TIA.
My predicament is - where do I do these calculations - in my vb.net code or in an SQL stored procedure?
My manager has handed me a task of converting an excel file she uses in to a web aplication.
While it has been easy to devise what should be the screens and how to capture data, I am struggling over how to code the calculations.
The calculations in excel are pretty simple. These are just sequential calculations (about a 150 calculation for average 500 rows). Mathametical operations include sum, average, max min - regular excel stuff. Some calculations involve vlookup (equvalent to calculation based on value derived from a reference table).
So I am stil wondering - where do I do these calculations - in my vb.net code or in an SQL stored procedure?
Since these calculations are required a produce a result in an online environment, what will be faster?
I tried to do a proof of concept by creating a sample calculation in a .NET class and an in a stored procedure. The choice is still not clear. SQL code execution time was not bad. But SQL code tended to be very messy.VB.net code seemed to be a little slow. But seemed a more organised to look at.
Any views that you can offer will be very helpful.
I need to calculate the overall GPA for a student in a particular class.
YEAR SCHOOL STUDENT IDENT GRADE TEACHER CLASS GPA 2007 Snow Canyon High Student1 321649 10 Teacher1 Earth Systems 0.0000 2007 Snow Canyon High Student1 321649 10 Teacher1 Earth Systems 1.6700 2007 Snow Canyon High Student1 321649 10 Teacher1 Earth Systems 3.3300 2007 Snow Canyon High Student1 321649 10 Teacher1 Earth Systems 3.6700 2007 Snow Canyon High Student1 321649 10 Teacher2 Elementary Algebra 0.0000 2007 Snow Canyon High Student1 321649 10 Teacher2 Elementary Algebra 0.6700 2007 Snow Canyon High Student1 321649 10 Teacher2 Elementary Algebra 1.0000
The problem I'm having is that a student may not taken the class for four terms (as in the Elementary Algebra example above). So I can't hard code it to sum the gpa and divide by 4; it needs to be the number of terms the student took the class.
Here's my sql:
select trnscrpt.schyear as [Year], school.schname as School, rtrim(stugrp_active.lastname) + ', ' + rtrim(stugrp_active.firstname) as Student, trnscrpt.suniq as suniq, stugrp_active.graden as Grade, trnscrpt.teachname as Teacher, trnscrpt.descript as Class, gpamarks.gpavallvl0 AS GPA
from dbo.trnscrpt inner join dbo.stugrp_active on trnscrpt.suniq = stugrp_active.suniq INNER JOIN school ON stugrp_active.schoolc = school.schoolc INNER JOIN gpamarks ON trnscrpt.marksetc1 = gpamarks.marksetc AND trnscrpt.markawd1 = gpamarks.mark
where trnscrpt.graden >= 6 and trnscrpt.markawd1 not in ('NC','NG','P','W','WA','WF','WI','WP') and trnscrpt.subjectc in ('LA', 'MA', 'CP', 'CB') and trnscrpt.schyear = 2007 and stugrp_active.schoolc = 725
In period = 2, status code change from InStock to OutOfStock: Product 1 (Count=1) In period = 1, number of products with status code = InStock: product 1 and product 2 (Count=2)