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


ADVERTISEMENT

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

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

Transact SQL :: Get One Record By ID Which Has Max Date

May 4, 2015

I have records like this

id      address1          date
1      xyz                 01/01/2013
1       abd                01/01/2014
2       dfg                 01/03/2015

Now what I want is just 1 record by id which has max date,if there is 2 records for same id, if there is 1 record then it should come.

So here result should be

1       abd                01/01/2014
2       dfg                 01/03/2015

View 12 Replies View Related

Transact SQL :: Select First And Last Record For Certain Date Range

Jun 16, 2015

I have a situation where an agent has number of activities for a certain date range. If an agent has multiple activities within certain date range, I would like BALANCE BEFORE from the first activity and BALANCE AFTER from the last activity. Here is my current SQL query that returns the following data:

DECLARE @BeginDate Datetime
DECLARE @EndDate Datetime
Set @BeginDate = '05-1-2015'
Set @EndDate = '05-31-2015'
SELECT
a.AgentName,
R.BALANCEBEFORE,

[Code] ....

AGENTNAME          BALANCE BEFORE  BALANCE AFTER          DATE
DOUGLAS              9738.75                9782.75                     2015-05-11
DOUGLAS              9782.75                9804.75                     2015-05-12
DOUGLAS              9804.75                9837.75                     2015-05-13

In the sample data above, ideally I would like my query to return data as follow:

AGENTNAME          BALANCE BEFORE                  BALANCE AFTER
DOUGLAS              9738.75 (from first activity)    9837.75 (from last activity)

Not sure how I can write sql query to accomplish this.

View 7 Replies View Related

Transact SQL :: Add Position Of Record Based On Certain Date Of Transaction

Aug 4, 2015

I built the following query to add the position of a record based on a certain date of the transaction of a customer:

select
CustomerID
, Product
, purchasedate

[code]....

View 6 Replies View Related

Transact SQL :: Last Record Not In Past 9 Months From Todays Date?

Aug 20, 2015

I would like to display Car records to retrieve last Maintenance request for all customer who did not make request in past 9 months from current date.

MC refers to Maintenance.

MCLog data:

carId: SGY12345 (repeated)
mcDate: 2010-01-30
mcDate: 2012-03-30
carId: SGX55661 (repeated)
mcDate: 2015-05-30
mcDate: 2015-06-15

[Code] .....

Here is my Table:

CREATE TABLE Car (
carId Char (20) NOT NULL,
model Char (20) NOT NULL,
importDate smalldatetime NOT NULL,
custId Varchar (50) NOT NULL,
CONSTRAINT Car_PK PRIMARY KEY (carId));

[code]....

View 6 Replies View Related

Date Of Previous Year Previous Month

Sep 10, 2013

Need getting a query which I will get previous year, previous month first day everytime i run the query.

Ex: If i run the script on 9/10/2013 then result should be 8/1/2012. (MM/DD/YYYY)

View 4 Replies View Related

Transact SQL :: Date Time Casting - Comparing Values And If Not Same Then Populating Record

Sep 9, 2015

I am trying to pull the records which are being affected i.e, comparing the values and if not same then populating the record.

I am using the below condition in where clause however i am getting runt time error as "Conversion failure when converting date and/or time from character string"

Condition in Where clause:

cast(isNull(tab1.Col1,'') as datetime) <> cast(isNull(tab2.col1,'') as datetime) 

Note: Both col1 columns are of type nvarchar 

View 6 Replies View Related

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 newsgroupa few days ago and got no response so I thought I'd try here. If I canprovide 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 calculatedcolumnsBeginningBalance: For the first record, this is equal to the loan amountfrom the loan table. For each additional record this is equal to the endingbalance from the previous payment record.Interest: BeginningBalance * the monthly interest rate from the loantablePrincipal: PaymentAMT - InterestEndingBalance: BeginningBalance - PrincipalIt might seem I could use a subquery to calculate the Beginning Balance asin:SELECT LoanID, PaymentPeriod, PaymentAMT,(SELECT SUM(PaymentAMT) FROM tblPayment AS tbl1WHERE tbl1.LoanID = tblPayment.LoanID AND tbl1.PaymentPeriod <tblPayment.PaymentPeriod) AS BeginBalanceFROM tblPaymentWHERE (LoanID = @LoanID)But this will not work, because the interest is calculated on the previousmonth's balance. I need to find a way to loop through the recordset. Isthis possible?Thank you,--Derek CooperDatabase9www.database9.com

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

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

T-SQL (SS2K8) :: How To Add Previous Row End Date As Next Row Start Date

Mar 14, 2014

Let's say the first row returned has StartDate = 1/1/2014 and EndDate is 1/2/2014. The next row I want the StartDate to equal the previous row EndDate so it would be 1/2/2014 as StartDate. This compounds every row basically the third row StartDate would be the second row EndDate. All in one select statement if it can be done. Using SQL2008r2.

View 9 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

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

Transact SQL :: First And Last Day Of Previous Month From Getdate

Dec 10, 2010

How to get First day of previous month and last day of previous month(From getdate()) using SQL..?

View 13 Replies View Related

Transact SQL :: Replacing Isnull With Previous Value

May 25, 2015

I am having table like below,

Period Pointvaluemonth area
NULLNULLNULLApril tn
NULLNULLNULLMaytn
NULLNULLNULLJunetn
NULLNULLNULLJulytn
NULLNULLNULLAugusttn
201109 100 10Septembertn

[Code] ....

Then i want to copy september value for october and november and Jan value for feb & mar like next null values should get replaced with previous not null value ...

My desired output is ,

Expected Output is…..

Period Pointvaluemonth area
NULLNULLNULLApril tn
NULLNULLNULLMay tn
NULLNULLNULLJune tn
NULLNULLNULLJuly tn
NULLNULLNULLAugust tn
201109 100 10September tn

[Code] ....

View 7 Replies View Related

Transact SQL :: Copy Previous Non Null Value

Aug 10, 2015

I have a table with data like below

SampleDateTime Value

2015-08-08 01:00 AM 0.5
2015-08-08 02:00 AM Null
2015-08-08 03:00 AM Null
2015-08-08 04:00 AM Null

[code]....

Using subquery I thought of a couple of ways but that didn't work.

View 6 Replies View Related







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