# SQL Server 2012 :: Reset Running Total To X Amount

Dec 22, 2014

I need to calculate running total which resets when reached to 16, and also needs to calculate remaining amount as paid.

I have attached sample data, so we have two columns Earned, and Used. And we need to calculate Balance, and Paid columns.

## SQL Server 2012 :: Split Total Days And Amount Between Start And End Month

Mar 21, 2015

I have the table below and like to create a view to show the no of days the property was vacant or void and rent loss per month. The below explanation will describe output required

For example we have a property (house/unit/apartment) and the tenant vacates on 06/09/2014. Lets say we fill the property back on 15/10/2014. From this we know the property was empty or void for 39 days. Now we need to calculate the rent loss. Based on the Market Rent of the property we can get this. Lets say the market rent for our property is \$349/pw. So the rent loss for 39 days is 349/7*39 = \$1944.43/-.

Now the tricky part and what im trying to achieve. Since the property was void or empty between 2 months, I want to know how many days the property was empty in the first month and the rent loss in that month and how many days the property was empty in the second month and the rent loss incurred in that month. Most of the properties are filled in the same month and only in few cases the property is empty between two months.

As shown below we are splitting the period 06/09/2014 - 15/10/2014 and then calculating the void days and rent loss per month

Period No of Void Days Rent Loss
06/09/2014 - 30/09/2014 24 349/7*24 = 1196.57
01/10/2014 - 15/10/2014 15 349/7*15 = 747.85

I have uploaded a screenshot of how the result on this link: [URL] ....

Declare @void Table
(
PropCode VARCHAR(10)
,VoidStartDate date
,LetDate date
,Market_Rent Money

[Code].....

## Running Total: Summing On Distinct Amount

May 9, 2007

I am trying to do a sum on a goal amount that is repeated for each record. But what is the the forumla to only sum on the distinct goal amount.

Example:

Month Year Goal Other Value

March 2007 500 5568

March 2007 500 5568

March 2007 500 5569

April 2007 600 5568

April 2007 700 5569

March-April 2007 1600 5568

March-April 2007 1200 5569

Total (I excpect)

March-April 2007 1100 5568

March-April 2007 1200 5569

I haven't found anything online to help.

Thanks,

Sam

## Transact SQL :: How To Reset Running Total To 0 Based On Other Column Value

Nov 9, 2015

I am trying to calculate the the running total but also tried to reset to reset to zero based on a value of a column.

here I am trying to calculate the value of CalcVal column based on column Flag value...actually it is running total but it reset to zero if Flag value is 0.

Here is the example of data along with required column

MonthId Flag CalcVal

201401 1 1
201402 1 2
201403 1 3
201404 1 4
201405 1 5

and so on .........

## Calculating The Total Amount Of Drugs Prescribed, Total Amount

Aug 10, 2006

Hi all,

I have a table named Prescription that consists of attributes like PatientId, MedicineCode, MedicineName, Prices of different drugs, quantity of different drugs(e.g 1,2,3,10), date .

I would like to get a summary of the total number and amount of different drugs in a specific period, the total amount of each type of drug.

I kindly request for help.

Ronnie

## SQL Server 2012 :: Running Sum With Reset Option And BULK Update

Jul 22, 2015

I have come up with an issue where I want to update data in a table using bulk/SET update to get the result shown in below code with output in column titled "Arrear Amt".

CREATE TABLE ##vOD_Calc
(
Seq_No INT ,
Contract_id INT ,
Rental_id INT ,
Actual_OD INT ,
Logic_OD INT ,
Due_dte DATETIME ,

[Code] .....

Logic required is that once the sum of column [ArrearAmt] of current row and all previous rows becomes greater than \$100 then column [ChArrrearAmt] should show that summed up value and in else case the column [ChArrrearAmt] should show the same value as that of column [ArrearAmt].

Once the column [ChArrrearAmt] reaches the threshold of \$100 then the same cycle should start again i.e. in above example rental#1 had \$37.17 < \$100 then rental#1 + rental#2 is also < \$100 and at rental#3 sum of rental#1, rental#2 and rental#3 becomes \$111.51 which is greater than \$100 so its updated in column [CHArrrearAmt]. The same cycle start overs from rental#4 onwards however the summation of [ArrearAmt] will now begin after rental#4 onwards and not from the starting.

Below is the loop based SQL script which handles the above situation, however in BULK its a total deterioration of performance if thousands of rows are to be processed i.e. with a contract having multiple rentals.

The case here is that I have to use the result of previously updated column value of [ChArrrearAmt] to take decision for the next row, however with BULK update since the row is not yet updated with latest amount therefore the decision on next row is also giving wrong result.

This is the code with which I have achieved to update the column 'chArrear Amount', however its a loop based solution and performance killer.

INSERT INTO ##vOD_Calc_loop
( Rows_count ,
contract_id
)
SELECT COUNT(*) ,
T.Contract_id
FROM ##vOD_Calc T
GROUP BY T.Contract_id

[Code] ....

## SQL Server 2012 :: Running Total On 2 Columns

Jul 25, 2014

Table A has day to day transactions, Table B has beginning balance. I'd like to get a running total balance day to day. Really what I want to do is use the previous days total to add the current days transaction to, but I don't know how to do it. The basic layout is below, but as you can see, I'm not getting the totals correct.

create table #current(acctNum int,
dates date,
transtype char(10),
amt INT
)
insert into #current(acctNum, dates, transtype, amt)

[Code] .....

## SQL Server 2012 :: Running Total With Thresholds?

Mar 18, 2015

I have a data table in below format and the need the desired output in 2nd table format

TABLE1

RANKBOOLEANREVENUE
1TRUE100
2FALSE150
3FALSE200
4FALSE250
5FALSE300

[code]....

Desired Output to be:

RANKBOOLEANREVENUERUNNINGTOTAL
1TRUE 100250
2FALSE150400
3FALSE200600
4FALSE250850
5FALSE3001150

[code]....

## SQL Server 2012 :: Producing Running Total Column In Select Clause

Jul 27, 2014

I want to create the following scenario. I have a table that stores employees working on projects and their project hours by week, but now I also need a running total per week for each of those projects. For example take a look below:

EmployeeID, Project, Sunday, Monday, Tuesday,....Saturday, ProjectHours, TotalProjectHoursPerWeek(this is the column I am trying to derive), FiscalWeek

101, ProjectABC, 5,5,5,...5, 20, 40,25
102, ProjectXYZ 4,4,4,....4, 20 ,40,25
103,ProjectQWE, 2,2,2,...2, 8, 32,26
104, ProjectPOP, 6,6,6,...6, 24, 32,26

What I have tried so far:

Correlated Subquery:
SELECT EmployeeID,Project, Sunday, Monday,....Saturday, ProjectHours, SELECT(SUM(ProjectHours) FROM dbo.TableABC ap GROUP BY FiscalWeek),
FROM
dbo.TableABC a

I got this to work one time before, but now I am getting the following error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

## SQL Server 2012 :: Creating Running Total Based On Single (SUM) Opening Balance

Jun 7, 2015

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

[Code] ....

Please see attachment to view output.

## Total Page Writes/total Amount Of Data Change In A Set Period Of Time

Jun 9, 2004

Does anyone know how I can determine the number of page writes that have been performed during a set period of time? I need to figure out the data churn in that time period.

TIA

## Get Total Amount By Date

Apr 10, 2008

this is my sample records in my table

Sdate Amount
January 2007 250000.00
March 2007 300000.00
January 2008 350000.00

how can i get the amount from February to
May 2007 and sum it up like this

Details
February 2007 250000.00
March 2007 300000.00
April 2007 300000.00
May 2007 300000.00

this is all that i want to get
Total Amount: 1,150,000.00

i also posted this one in new to sql server section, but im hoping to get others opinion here. thnx

## How To Know When Total Salary Is At Certain Amount

Jul 24, 2013

I would like to know how to use a criterion on this example. I want to know only when the total salary is at a certain amount

SELECT SUM (salary) as Total Salary
FROM employees
WHERE Total Salary > 25000; ---this is where i am having issue

## Need Total To Reset Inside A Trigger

Jun 2, 2008

Have the following trigger:

CREATE TRIGGER [UPDATEEGBKMUTREBATERECORDS] ON [dbo].[GBKMUT]
after INSERT
AS
begin
DECLARE@Sum Float
SELECT@Sum = SUM(bdr_hfl)
FROMinserted
WHEREfreefield3 = 'Rebate'

SET@Sum = COALESCE(@Sum, 0)
UPDATEgbkmut
SETbdr_hfl = bdr_hfl - @Sum
WHEREreknr = ' 1040'
end

I need @Sum to reset to zero if the ord_no changes. I'm inserting discount records that need to subtract from another account's amount.
As records are inserted for one ord_no and Inv_no I need to sum bdr_hfl field. When the ord_no and Inv_no change, I need to subtract that from the amount in the bdr_hfl where the account number is 1040 and the inserted records ord_no and Inv_no match the ord_no and Inv_no where the account is 1040. Then I need the @sum to reset to zero and start summing again.

## Total Amount Of Triggers Per Table

Aug 1, 2006

Hi

Just a quick question taht I hope someone can answer, What it the total amount of trigger per table?

I understand that it is better to have as least as possible for performance

Thanks Rich

## Reset Total Page Number In A Group

Sep 26, 2006

I know how to reset the page numbers with each group, but how do you reset the total page number within each group.

EX. Code for page of total pages

="Page " & Globals.PageNumber & " of " & Globals.TotalPages

EX. Code to reset within a group
Custom Code:
Shared offset as Integer
Shared currentgroup as object

Public Function GetGroupPageNumber(group as Object, pagenumber as Integer) as Object
If not (group = currentgroup)
offset = pagenumber - 1
currentgroup= group
end if
return pagenumber - offset
end function

=Code.GetGroupPageNumber(ReportItems!Category.Value(grouping),Globals!PageNumber)

What I need is code for a combination of the two...to display code for page of total pages that resets within a group.

Any help is greatly appreciated.
Thanks!

## Trying To Get Running Total In Server

Jun 2, 2015

get Running Total in SQL Server.I found that new OVER clause.

SELECT
CompanyId
,IMNId
,RowNumber
,Sum(Qty) OVER(ORDER BY CompanyId, IMoneyNetId, RowNumber ROWS UNBOUNDED PRECEDING) As CumulativeShareQty2
From#ReportData
WhereSequenceNumber <> 3
Group by CompanyId
,IMNId
,RowNumber

But somehow i get below error, when i try to run above query:

Msg 8120, Level 16, State 1, Line 957
Column '#ReportData.Qty' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

## Show Total Amount Of Rows In Specific Table

May 20, 2012

I need to show the total amount of rows in a specific table?

The query is as follows:

As part of the planning process to expand the database that supports Northwind operations, the IT manager would like to know how many rows are currently in specific tables so that he can conduct capacity planning.

The results needed include two columns, TableName( containing all the tables in the database and Rows, which contain the total amount of all the rows per table).

## Transact SQL :: How To Get Running Total In Server

Oct 21, 2015

I need to get a cumulative total for row by row basis. I need this grouped on name, id, year and month. ID is not a auto incremented number. ID is  a unique number same as name. The out put I need is as below,

Name     ID     Year   Month  Value  RunningValue
XX         11     2013  Jan      25          25
xx          11     2013  Feb      50          75
yy          22     2015   Jan     100        100
yy          22     2015   Mar     200        300

How I could get this query written? I am unable to use SQL Server 2012 version syntaxes. Writing a cursor would slow the process down because there is a large data set.

## SQL Server 2012 :: Divide Amount Between Months

Mar 18, 2015

Background:

Void Start Date: When a property becomes empty or vacant

Let Date: When the property is filled in again

I have the sample data below and like to show the void loss per month basis as below:

1) Allocate the amount from voidloss column between months based on voiddays:

for example for propcode 3698 the amount 13,612.56 needs to be divided between September and October based on the VoidDays. i.e of the 39 voiddays, 25 where in September and 14 in October hence 8726 will be allocated to September and 4886.56 to October

2) After allocating the amount sum the amount by controlgroup and total the voiddays per month. It will be great if we can divide the voiddays between months and sum them by controlgroup as well.

So in the end result we should have

ControlGroup, Month, Year, VoidLoss, VoidsdayinMonth
106 September 2014 8726 25
106 October 2014 4886.56 14
106 December 2014 2940 7

Declare @voidloss Table
( History_IND INT
,PropCode VARCHAR(10)
,VoidCategory VARCHAR(10)
,ControlGroup VARCHAR(10)
,VoidStartDate date

[Code] .....

## Transact SQL :: Running Total In Server 2008

Nov 20, 2015

Is it possible to assign to a variable, then add to it later on?  When I run the below, all I get is 3 rows affected I never see the value printed.  What i am wanting to do is each loop sum the numbers so 2+1+3 =6 so in the end @sumofallnumbers
= 6
Create Table #Test ( randarnumbers int )
Insert Into #Test Values ('2'), ('1'), ('3')
Declare @sumofallnumbers int, @nbr int
Declare c1 Cursor For
Select randarnumbers
FROM #Test

[code]..

Jun 17, 2015

I have a local instance of SQL 2012 express,

Is there anyway to reset this password without re-installing SQL server.

## SQL Server 2012 :: How To Remove Next And Previous Record Amount Equal To 0

Jun 2, 2014

Having below data. SHCOMP (Customer ID), CBLNAM ( Customer name), SHDESC (service description), SHAMT (service charge), SHTYPE (F-> From T-> To)

CREATE TABLE #Temp(
[SHCOMP] [numeric](7, 0) NOT NULL,
[SHDESC] [char](35) NOT NULL,
[SHTYPE] [char](1) NOT NULL,
[SHAMT] [numeric](9, 2) NOT NULL,

[Code] ....

I need to remove records that have the same ID, Name, Description and Amount summary = 0, For example

SHCOMP CBLNAM SHDESC SHAMT SHTYPE

123 cust1 desc1 45 F remove
123 cust1 desc1 -45 T remove
123 cust1 desc1 45 F remove
123 cust1 desc1 -45 T remove
123 cust1 desc1 45 F

[Code] ....

Results

SHCOMP CBLNAM SHDESC SHAMT SHTYPE

123 cust1 desc1 45 F

123 cust1 desc1 -35 T

234 cust3 desc2 30 F

here is what I did but didn't work because sum is <> from 0 so is leaving all records

select SHCUST, SHDESC, ABS(SHAMT) SHAMT
into #t1
FROM #Temp
group by SHCUST, SHDESC, ABS(SHAMT)
having SUM(SHAMT)=0
order by SHCUST

delete S from #Temp S
join #t1 T on T.SHCUST = S.SHCUST and T.SHDESC = S.SHDESC

## SQL Server 2012 :: Create View To Allocate Amount Per Month - Financial Year

Mar 21, 2015

I like to create an SQL view to divide amount 300,000 between 12 month starting from Month July 2014 to June 2015 as shown below

Amount Month Year
25,000 July 2014
25,000 August 2014
25,000 September 2014
25,000 October 2014
25,000 November 2014
25,000 December 2014
25,000 January 2015
25,000 February 2015
.
.
.
.

25,000 June 2015

## Problem Running Package With 'larger' Amount Of Data

Jun 9, 2006

Dear,

I created a package getting data from files and database sources, doing some transformations, retrieving dimension id's and then inserting it into a fact table.

Running this package with a limited amount of data (about a couple of 100.000 records) does not result in any errors and everything goes fine.

Now running the same package (still in debug mode) with more data (about 2.000.000 rows) doesn't result in any errors as well, but it just stops running. In fact, it doesn't really stop, but it doesn't continue as well. If I've only been waiting for some minutes or hours, I could think it's still processing, but I waited for about a day and it still is 'processing' the same step.

Any ideas on how to dig further into this in order to find the problem? Or is this a known problem?

Jievie

## SQL Server 2012 :: Add Total To Query

Dec 18, 2013

I have a table with the Group name and Total Count by group . I need to add a 'Total' and summation of all counts at the end .

CREATE TABLE #TempTable
(GroupName VARCHAR(10),NumberOfCases INT
INSERT INTO #Temp Table (GroupName,NumberOfCases)
VALUES ('Grp A',10)
INSERT INTO #Temp Table (GroupName,NumberOfCases)
VALUES ('Grp B',20)

[code]....

## SQL Server 2012 :: Calculate Total Between Two Columns

Sep 14, 2015

I have update schema and I upload image with my desire result.

CREATE TABLE #NONAMETABLE(
sinGroup NVARCHAR(10)
,column1 INT
,column2 int

[Code] .....

## Calculate Total Amount Of Order Details Based On Particular Order

Apr 10, 2014

I have a query that calculate the total amount of order details based on a particular order:

Select a.OrderID,SUM(UnitPrice*Quantity-Discount)
From [Order Details]
Inner Join Orders a
On a.OrderID=[Order Details].OrderID
Group by a.OrderID

My question is what if I wanted to create a formula to something like:

UnitPrice * Quantity - DiscountAmount Where DiscountAmount = UnitPrice Quantity * Discount

Do I need to create a function for that? Also is it possible to have m y query as a table variable?

## Transact SQL :: Query For Month Wise Running Totals Of Sales Amount?

Nov 28, 2012

I have a sales tables which looks as below.

DEPARTMENT
Barnd_Name
Item_Group
S_DATE
S_AMOUNT
IBM

[code]....

Now i need Month Wise Running Totals.but i should check the following group as show below i that order

1) DEPARTMENT
1) Brand
3) Item Group
4) Month

## SQL Server 2012 :: Select Top X% From Group Based On Total?

Mar 21, 2014

What I need to do it select the top 80 percent of records per group based on the group total. To be clear I am not trying to just grab the top x percent of rows.

Table 1:

DealerID RepairID
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
2 11
2 12
2 13

Table 2:

RepairID Tire
1 225/65R17 102T
2 225/65R17 102T
3 225/65R17 102T
4 235/60R18 102V
5 235/60R18 102V
6 235/60R18 102V
7 235/60R18 102V
8 205/55R16 89H
9 205/70R15 89H
13 225/65R17 102T

Table 1 has the total number of repair orders per dealer. This can be obtained by simply grouping on DealerID and counting the number of RepairIDs.

Table 2 has information on some of the repair orders and it is needed to select the top 80% of tire sizes. This table will be joined to Table 1 and grouped by DealerID and Tire.

Desired Output:

DealerIDTire RepairsOfThisTireRepairCount PercentOfTotalRepairOrders
1 235/60R18 102V4 10 40
1 225/65R17 102T3 10 30
1 205/55R16 89H1 10 10
2 225/65R17 102T1 3 33

The equation I am given to calculate the top tires per dealer is as follows: Total # of tires for the size / Total # of repair orders per dealer.

Here is what I have so far though I think I might have to rewrite all of it.

SELECT
DealerID ,
COUNT(RepairID)
INTO #TotalDealerRepairOrders
FROM
dbo.Table1
GROUP BY
DealerID
SELECT

[code].....

## SQL Server 2012 :: Calculate Total On-peak And Off-values For A Month

Nov 25, 2014

SQL query to calculate the total on-peak and off-values for a month as well as the Max/highest on-peak/offPeak hourly value for that month.

On a daily basis i store the hourly values of the meter in a SQL table.

On-Peak

Summer: Apr-Oct hours(7-22) on weekdays (M-F)
Winter: Nov-Mar hours(8-23) on weekdays (M-F)

off-Peak

Summer: Apr-Oct hours(0-6,23,24); Weekends (Saturday & sunday) ; all public holidays during those months as to be considered as off peak

Winter: Nov-Mar hours(0-7,24);Weekends (Saturday & sunday); all public holidays during those months as to be considered as off peak

Here is the DB Table Structure:

Column Name & Data Types
HourId - Uniqueidentifier
CustomerName - nvarchar(50)
IntegratedHour - TinyInt
Generation - Decimal (18,4)
LastModified - Datetime
ModifiedBy - nvarchar(50)

## SQL Server 2012 :: Add Column Names As Total And Subtotal For NULL Values?

Jan 21, 2014

How do I add column names as Total and SubTotal for NULL values.

SELECT DISTINCT
--[Group]
[Month]
,[Market]
,[Environment]
,[type]
, COUNT(*)

[code]....

## Running Total

Mar 8, 2006

Help can anyone see anything wrong with this I am trying to get a running total to show on my form for the users to see, as a team member makes a payment they should be able to see the remaining amount

SELECT SUM(DISTINCT TotalPayments) AS Payment, SUM(AmountDue) AS Due, SUM(FinePayment) AS Fine, [TM #]
FROM dbo.FinePayments_Tbl
GROUP BY [TM #]
HAVING ([TM #] = 9282)