Value Of A Record Based On A Previous Record

Jul 20, 2005

I hope you can help me. I posted this in the microsoft sql server newsgroup
a few days ago and got no response so I thought I'd try here. If I can
provide any clarification I'll be glad to do so.

I'm trying to calculate a column based on the value of the previous record.
I'm not very experienced with SQL-Server.

I'm using the following table:
CREATE TABLE tblPayment
(
[PaymentID] [int] IDENTITY (1, 1) NOT NULL ,
[LoanID] [int] NULL ,
[PaymentPeriod] [int] NULL ,
[PaymentRecDate] [datetime] NULL ,
[PaymentAMT] [money] NULL
)

I have a view based on this table. That view has the following calculated
columns

BeginningBalance: For the first record, this is equal to the loan amount
from the loan table. For each additional record this is equal to the ending
balance from the previous payment record.

Interest: BeginningBalance * the monthly interest rate from the loan
table
Principal: PaymentAMT - Interest
EndingBalance: BeginningBalance - Principal

It might seem I could use a subquery to calculate the Beginning Balance as
in:

SELECT LoanID, PaymentPeriod, PaymentAMT,
(SELECT SUM(PaymentAMT) FROM tblPayment AS tbl1
WHERE tbl1.LoanID = tblPayment.LoanID AND tbl1.PaymentPeriod <
tblPayment.PaymentPeriod) AS BeginBalance
FROM tblPayment
WHERE (LoanID = @LoanID)

But this will not work, because the interest is calculated on the previous
month's balance. I need to find a way to loop through the recordset. Is
this possible?

Thank you,

--
Derek Cooper
Database9
www.database9.com

View 5 Replies


ADVERTISEMENT

Delete Record Based On Existence Of Another Record In Same Table?

Jul 20, 2005

Hi All,I have a table in SQL Server 2000 that contains several million memberids. Some of these member ids are duplicated in the table, and eachrecord is tagged with a 1 or a 2 in [recsrc] to indicate where theycame from.I want to remove all member ids records from the table that have arecsrc of 1 where the same member id also exists in the table with arecsrc of 2.So, if the member id has a recsrc of 1, and no other record exists inthe table with the same member id and a recsrc of 2, I want it leftuntouched.So, in a theortetical dataset of member id and recsrc:0001, 10002, 20001, 20003, 10004, 2I am looking to only delete the first record, because it has a recsrcof 1 and there is another record in the table with the same member idand a recsrc of 2.I'd very much appreciate it if someone could help me achieve this!Much warmth,Murray

View 3 Replies View Related

Update A Record Based Of A Record In The Same Table

Aug 16, 2006

I am trying to update a record in a table based off of criteria of another record in the table.

So suppose I have 2 records

ID owner type

1 5678 past due

2 5678 late

So, I want to update the type field to "collections" only if the previous record for the same record is "past due". Any ideas?

View 5 Replies View Related

Next/previous Record

May 2, 2007

Hi. Is it possible in SQL query to find record previous or next in comparison with record found with clause WHERE (example of query below)? I need to find record with ProblemID less than or greater than 10. Regards Pawelek.
SELECT     ProblemIDFROM         dbo.tblProblemsWHERE     (ProblemID = 10)

View 2 Replies View Related

Get Previous Record

Dec 5, 2005

Please see DDL and INSERT statements below.Let's say that some process throws out the second row, where theClocktime = '02/01/2005 12:34'Without the use of a cursor, how can I retrieve the PREVIOUS value forthat employee? Pseudo SQL might be something like:SELECT*FROMtblTestWHEREfldCLocktime = THE-ONE-IMMEDIATELY-BEFORE '02/01/2005 12:34'ANDfldEmployeeID = 1TIAEdwardif exists (select * from dbo.sysobjects where id =object_id(N'[dbo].[tblTest]') and OBJECTPROPERTY(id, N'IsUserTable') =1)drop table [dbo].[tblTest]GOCREATE TABLE [dbo].[tblTest] ([fldTestID] [int] IDENTITY (1, 1) NOT NULL ,[fldEmployeeID] [int] NULL ,[fldClocktime] [datetime] NULL ,) ON [PRIMARY]GOINSERT INTO tblTest(fldEmployeeID,fldClocktime)VALUES(1,'01/01/2005 12:34')INSERT INTO tblTest(fldEmployeeID,fldClocktime)VALUES(1,'02/01/2005 12:34')INSERT INTO tblTest(fldEmployeeID,fldClocktime)VALUES(1,'03/01/2005 12:34')

View 3 Replies View Related

How To Get Previous Record Thru Sql Query

Feb 1, 2007

How to Get previous record thru sql query
For the example
my table:
1  usera    item1    1.00    01/02/072  usera    item1    2.00    02/02/073  userc    item2    3.00    03/02/07
--how to use the query to make them join became like this (get/join with the next record)
1  usera    item1    1.00    01/02/07  item1    2.00    02/02/073  userc    item2    3.00    03/02/07  null       null     null
 >.<need help ... thanks alot

View 4 Replies View Related

Selecting Next And Previous Record

Jun 25, 2004

I'm trying to add a next and previous button to a popup window I have on a photo gallery -

Having trouble with the sql

I know I would have 2 select statements that would each return 1 result set.

I know how to get the top ( and bottom by ordering descending and doing Select Top 1)

But how would I get the next one up!

I would hate returning the entire image section and perform the calcuation in the business tier :(

View 4 Replies View Related

Select Next And Previous Record

Aug 28, 2001

Hi!

I need to select a spesific record using the recordkey and then select the previous and the next record as well. (which leaves me with a recordset containing three records)

Is this possible?

View 3 Replies View Related

RANK Get Previous Record But Not Always

Apr 16, 2014

I need to get the previous price for all my PROMOTION records but not when the previous record is a type PROMOTION also it needs to keep going back to get the price.

I have created a table with RANK in which works OK to get previous price for all but how can I say if previous price is type PROMOTION go to next previous prices...

Bets way to show an example is with a jpeg image I have but having trouble inserting into this message...

SELECT a.[StartPrice]
,a.[ProductID]
,a.[Colour]
,ISNULL(b.[Price],a.[Price]) AS [Price Before]
,a.[Price] AS [Promotion Price]

[Code] ...

Table

PriceCodeStartPriceEndPriceProductIDColourPriceRank
RETAIL21-Oct-1324-Dec-13Bike15BLUE39.001
PROMOTION29-Nov-1301-Dec-13Bike15BLUE31.202
PROMOTION12-Dec-1323-Dec-13Bike15BLUE31.203
MARKDOWN25-Dec-1314-Jan-14Bike15BLUE31.204

[Code] ....

Want I'm trying to do select PriceCode PROMOTION and get previous price:

Get previous price
PROMOTION29-Nov-1301-Dec-13Wheel1BLACK31.2039.00

But in this example it picks up the PROMOTION before and I need to ignore this and get rank 1 price for both

PROMOTION29-Nov-1301-Dec-13Bike15BLUE31.2039.00
PROMOTION12-Dec-1323-Dec-13Bike15BLUE31.2039.00

View 8 Replies View Related

How To Reference A Previous Record

Mar 31, 2015

I have a query that shows me a list of what employees that are on site assuming that employee badged in correctly. My problem is I need to know when an employee has two entries in a row that are "In" without have an "Out" entry.

For example, if John badges in at 8:00 Am and leaves without badging out, when he arrives the next day at 8:00 AM and badges in the system simply would show him as in with no record of him ever leaving correctly.

I am not sure how to return the correct result. Can I formulate a query that would display a Who's In list where the previous entry was NOT and Out?

View 16 Replies View Related

How To Retrive 1st, Next, Previous & Last Record ?

Apr 20, 2007

Hi, I am new to using SQL. Currently, I'm using the following statemens to retrive a specific record from my MS Access DB via VB.net.

SELECT * FROM table_name WHERE Field_Name = Criteria

Can someone please tell me, after selecting this record, If I want to go to the FIRST, or NEXT or PREVIOUS of the record just retrived or the LAST record. Can someone please tell me how can write the SQL statment to achieve this ?

Regards

View 3 Replies View Related

Getting Previous Record From Another Table

Apr 9, 2008

Hello

just wondering, if I can get help with a table (Table A) , where there are few dates and numbers, I have to relate this table to another table (Table B) , where I have whole year working dates

I want to write an expression while making dataset, that if date in table B matches table A, it just get the number from the next column from table A, if it does not matches - it should go back to the date (in table A) - where there is a number.

Like table B has working dates for march, but there are only two dates in table A , for 3/2 (and number is 300) and 3/20 (number 200). So In dataset I want all dates from table B and from 3/2 to 3/19 300 in number column and 200 on 3/20.

Thanks in advance for your help

View 3 Replies View Related

Get Next Record In A Table Rather Than Previous

May 19, 2008

I'm creating a report in SSRS where we want to do a week-over-week or month-over-month analysis. We have each month and the metrics in a table. By sorting the table ascending, I can grab the previous record using the Previous function in a cell. However, when I order the table descending the previous record is not the correct record to get. In that case I want to grab the next record rather than the previous record. How can I invert the previous function? Or how can i grab the next record in the table rather than the previous?

Thanks!

View 3 Replies View Related

How To Check Previous And Next Record Values

May 22, 2008

Hi all,

I wanted to check the previous and next record values.

For example:

sKey NextKey PreviousKey

1 2 Null
2 8 1
8 5 2
5 null 8

I wanted to check the value of NextKey of Prev record and Skey of Next record.

Any idea?

Regards
Helen

View 5 Replies View Related

Compare Previous To Current Record Row

Mar 3, 2014

My current code returns account_number with multiple start_date regardless of the value is same or not. However, I would like to get only the account number when the value on start_date is different within same account_number.

select
acct_number
count(start_date) from table_A
group by acct_number, start_date
having(count(start_date) > 1)

View 5 Replies View Related

Fast Way To Get Values From Previous Record

Jul 20, 2005

Hello,I know that I've seen this question asked on here before, but I can'tfind an answer that gives me the performance that I need.I have a table that stores events for users:CREATE TABLE Lead_Action_History (lead_action_seq INT IDENTITY NOT NULL,lead_action_date DATETIME NOT NULL,lead_seq INT NULL,operator_id VARCHAR(20) NOT NULL,call_time INT NOT NULL,CONSTRAINT PK_Lead_Action_History PRIMARY KEY (lead_action_seq) )GOThe table has a foreign key to another table through the lead_seqcolumn:CREATE TABLE Lead_Master (lead_seq INT IDENTITY NOT NULL,state CHAR(2) NOT NULL,CONSTRAINT PK_Lead_Master PRIMARY KEY (lead_seq) )GOI need to write a query that will give me a sum of call_time brokendown by a column that is in the table joined through the lead_seq.However, if the lead_seq for a row is NULL then I need to use thelead_seq for the previous row (based on lead_action_date) for the sameoperator.This is what I came up with:SELECT LM.state, SUM(call_time)FROM Lead_Action_History LAHINNER JOIN Lead_Master LM ON (LM.lead_seq = LAH.lead_seq)OR (LAH.lead_seq IS NULLAND LM.lead_seq = (SELECT TOP 1LAH2.lead_seqFROMLead_Action_History LAH2WHERELAH2.operator_id = LAH.operator_idAND LAH2.lead_seqIS NOT NULLORDER BYLAH2.lead_action_date DESC))GROUP BY LM.stateThe problem is that Lead_Action_History has millions of records andany solution that I've found involves one or more subqueries on itwhich kills performance. I am going to look at using a covering indexwith the solution above, but I thought that someone here might haveanother way of doing this.I can't really change the structure, but I can play with the indexing.I would still be curious though how other people model this type oftemporal data in a way that makes it easy to work with.Thanks!-Tom.

View 4 Replies View Related

Transact SQL :: Previous Log Date For Each Record

Sep 22, 2015

I have one table :

file _target

which has below records..

file_target_ID is identity column which will repeat per files_ID

Now, i just shown Target log  for file_ID 77796 see the last Target Date i want another column which returns a previous log Target date for each files beside Target date  column

Like this ..

Target Date                     New Column
2015-09-09 00:00:00.000   2015-09-16 00:00:00.000
2015-09-16 00:00:00.000   2015-09-25 00:00:00.000
2015-09-25 00:00:00.000   New Target date after 25-9-2015

how to do this in SQL Server ??

using Cross Apply ?? Row_Number() ??

View 3 Replies View Related

How To Check Previous And Next Record Values

May 22, 2008

Hi all,

I wanted to check the previous and next record values.

For example:

sKey NextKey PreviousKey

1 2 Null
2 8 1
8 5 2
5 null 8


Ex : In the first record of the table, the NextKey is pointing to 2.
So the next record of Skey will be 2. The Next Key for this record is 8. Like wise the next record of this should have the Skey as 8.

Now I need to check whether the NextKey and SKey are correct for all rows.

For that I need to check the previous record of "Next key" and next record of "Skey".

Any idea?

Regards
Helen

View 5 Replies View Related

How To Make Automated Update On The Previous Record...

May 9, 2008

Hello...i have a table that record all the reading meter....so when i change one of the reader meter data...in logical it will automatically change the normalized fields...

Reading teble
-------------------
-id[PK]
-meter
-normalized
-date
when i insert new record..i just insert data about date and meter...an normalized is automated calculate using my function..the problem is..when i have data more than one...when i try insert or update or delete data...it nee to be automatically calculate back the normalized..i know this is needed the temperory table and then reinsert back..how can i solve this problem???

View 1 Replies View Related

How To Automatically Populate A Field With A Value From A Previous Record?

Mar 16, 2008



Was wondering if there is easy anyway to autopopulate a field by pulling a value from a field in the previous record?

For example, I have a table with fields name "Dist_From" and "Dist_To". When I add a new record I would like it to populate the "Dist_From" field with the "Dist_to" value from the previous record.

TIA

Todd

View 3 Replies View Related

Insert Previous Record In A Blank Or A Null Field

Nov 29, 2000

Data from as400 imports into SQL with blank fields which is the way as400 outputs records. How can you insert previous record of data null or blank field. ex:

ONETWO
a1
2
3
b1
2
3

Would want:

ONETWO
a1
a2
a3
b1
b2
b3

View 5 Replies View Related

SQL Server 2012 :: Trigger For Updates On A Row Using Previous Record Value?

Mar 9, 2015

I am looking to update a record from a previous row. So if there is a value of total goods in week 1, i want that value to carry forward to the value of goods in week 2. Is there any SQL as an example of the best way to accomplish this? I can query it using lag() which works great but i need the source data itself to update as the end-users are accessing the data via lightswitch, so when they save a change, i want the trigger (or whatever you recommend) to update the source table.

View 9 Replies View Related

Use A Date To Select Out Previous 14 Days Record From The Table

Dec 10, 2007

May I know how to use a "date" to select out previous 14 days record from the table? and find the duplicated records?


-- sort out duplicate order from tblOrder

Select * FROM tblOrder

WHERE DDay > @prmDDay("day", -14, getDate())

Group by DDay



Many thanks~~~~~
Fr New Learner

View 3 Replies View Related

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

View 5 Replies View Related

T-SQL (SS2K8) :: Update DateTime Field With Date-inserted From Previous Record?

Jan 14, 2015

My goal is to update the "PriorInsert" field with the "DateInserted" from the previously inserted record where the WorkOrder, MachineNo, and Operator are all in the same group.

While trying to get to the correct previous record, I wrote the query below.

P.S. The attached .txt file includes a create and insert tbl_tmp sampling.

select top 1
a.ID,
a.WorkOrder,
a.MachineNo,
a.Operator,
a.PriorInsert,

[code]...

View 2 Replies View Related

Update Based On Another Record

Mar 13, 2014

We are developing a database in SQL and we are trialing some of our typical analysis undertaken on out dataset.

I have a problem with a update function. ID direction Holiday Lat Long Speed obstime - Datestamp LicenseID - varchar(7) status - int (0 or 1) O-Unoccipied, 1-occupied Pickup - Boolean Dropoff - Boolean

I am trying to update the 'Pickup' or 'Dropoff' when the status changes from 0 to 1 or from 1 to 0 if the difference in the datestamp is less than 2 minutes. Pickup is when the status goes from 0 to 1 Drop off is when the status goes from 1 to 0

View 2 Replies View Related

Record Based Security

Feb 15, 2008

Hi,

We are currently developing a crm that has the following main tables: client, sales, actions, contacts and employees with up to 4 million records. The db contains several other tables with extra information but these aren't relevant for this problem.
Clients have sales, contacts and actions. sales and actions can have seperate contacts as well, and contacts can be related to employees in a way.

Offcourse a security model was implemented but this only provides the option to hide or show all the records of these main tables. Now people noticed that it is a must to let people see for example only companies they created or do sales with. In other words access must be given at a record level.

The first thing that pops in my head is to create a client_security, sales_security, ... table that contains the employee_id and client_id or sales_id, or ... And add a join with one of these security tables for each select that is executed.

I wonder (because of the huge amount of data) if there isn't a better way to get this done?

Another possible issue that came to mind was, that when some data doesn't need protection or some people have the rigth to see everything, we would have to create the records in the security table anyways, resulting in probably hundreds of thousands of records.

Feedback on our solution (if we can call it that allready), or even keywords to find more about this issue via google (record based security really isn't the best description I guess) are most appreciated.

thx in advance.

View 5 Replies View Related

Select Record Based On Max Date

Sep 12, 2012

I have the following table:

Occ_Num Feature_Num Trans_Date Peril_Desc
123 1 1-2-2012 Water
123 1 1-11-2012 Ice
123 2 1-2-2012 Other
123 2 1-13-2012 Other
123 2 1-19-2012 Wind

I want to select each Occ_Num, Feature_NUM, Trans_Date, and PERIL_Desc but with only the Peril that was part of the max trans_date.

So i would want the following from above:

Occ_Num Feature_Num Trans_Date Peril_Desc
123 1 1-11-2012 Ice
123 2 1-19-2012 Wind

I'm having trouble with the syntax need to accomplish this.

View 2 Replies View Related

View To Get Record Based On A Column Value

Jul 24, 2013

I have a view where the results would be like this.(userid,name,rolekey are my col names with data)

userid name rolekey
test1 tname rolekey1
test1 tname rolekey2
test1 tname rolekey3

is this possible to retireve data from view where i need only userid with rolekey1.? tried with a function but its taking more time? any options in doing it in the view itself?

View 5 Replies View Related

Select X Record Based On Row Passed In URL

Aug 3, 2007

Hi all - this one has me stumped... PLEASE HELP!!!

I have a back/forward navigation link that passes a URL.startrow number (lets call it n) - based on n - I only want to select the record that is the n'th record based on a sort order (gall_order) - (SQL SERVER).

<cfquery name="gallHomePic1st" datasource="id" maxrows="1">
SELECT id
FROM gall_home
ORDER BY gall_order asc
</cfquery>

For e.g. - I want the 7th (14th - 21st etc) record based on gall_order asc.

Thanks guys - this has me stumped!

View 4 Replies View Related

Create Record Based On Count

Nov 9, 2007

I have the following data,

CustomerID EngID EngCount
1 A11 2
2 B12 1
3 C10 3

I need to display it as,

CustomerID EngID EngCount
1 A11 1
1 A11 1
2 B12 1
3 C10 1
3 C10 1
3 C10 1

Create a record based on the EngCount. So CustomerID of 3 has 3 records as shown above.

How to do?

View 5 Replies View Related

Grouping Record Based On A Condtion

Aug 11, 2006


Technology Type Size
XYZ A 200
XYZ1 A 200
XYZ2 A 300
XYZ3 A 300
ABC1 X 238
ABC2 X 238
PQR B 320
MNO C 330

I have written a query on a table whose output will look like the above. I need to know if i should store this in a record set or create a temp table to get the following fuctionality.

Now I need to concatenate the Technology based on Type and size.

As you can see in Type A we have two sizes 200 and 300.

We need to group the Technology of type A with same size together.

So the output of the procedure should be

XYZ + XYZ1
XYZ2+ XYZ3
ABC1 + ABC2 etc.

We need to concatenate the Technology string with the next technology if they have the same type and size.

Can somebody please help or send any sample code.

Any help is greatly appreciated

Thanks
Swapna

View 11 Replies View Related

TOUGH INSERT: Copy Sale Record/Line Items For Duplicate Record

Jul 20, 2005

I have a client who needs to copy an existing sale. The problem isthe Sale is made up of three tables: Sale, SaleEquipment, SaleParts.Each sale can have multiple pieces of equipment with correspondingparts, or parts without equipment. My problem in copying is when I goto copy the parts, how do I get the NEW sale equipment ids updatedcorrectly on their corresponding parts?I can provide more information if necessary.Thank you!!Maria

View 6 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved