T-SQL (SS2K8) :: Carry Forward Values From Previous Rows

Mar 23, 2014

I am working on a rewards program and I have a table whenever customer completes a trip, his total fare,business points earned for that particular trip and respective Promotional points gets inserted.

Now I have a scenario whenever customer business points accumulates to 10 then need to award 3 promotional points.

If Business Points=14 for a single trip then for the first 10 points respective Promo points will be awarded and the remaining 4 points should get carry forward for the next trip and this 4 points should get accumulated with the next trip Business Points and so on.

Basically need to check for every 10 Business points accumulated award some Promo points and carry forward remaining points.

Here is the sample table structure and data :

CREATE TABLE [dbo].[tblRedeems]
(
[Mobileno] [varchar](50) NOT NULL,
[TripNo] [int] NOT NULL,
[CustomerName] [varchar](50) NULL,
[TripEndTime] DATETIME NOT NULL,

[Code] .....

View 5 Replies


ADVERTISEMENT

T-SQL (SS2K8) :: Set Current Row Using Values In Previous Row

Feb 25, 2015

I've tried all sorts of code i.e. cross apply, running totals, etc. Cannot get this to work. I am trying to add a previous row value but only doing it for each group.

Source records
DECLARE @tbl table (Item int, Sequence int, StartTime datetime, Duration int)
INSERT INTO @tbl (Item,Sequence,StartTime, Duration) VALUES (1,1,'2/25/2015 12:00 am',10),(1,2,null,20),(1,3, null,22),(2,1,'2/25/2015 1:00 am',15),(2,2,null,30),(2,3, null,45),(2,4, null,5)
select * from @tbl

ItemSequenceStartTimeDuration
1102/25/15 0:0010
12null 20
13null 22
2102/25/15 1:0015
22null 30
23null 45
2 4 null 5

I would like to set the start time of the next row to be equal to the previous row time + duration. I know the start time of each group of 'Items' when the 'Sequence' number = 1. The last 'duration' value in the group would be ignored.

My expected output would be:

ItemSequenceStartTimeDuration
1102/25/15 0:0010
1202/25/15 0:1020
1302/25/15 0:3022
2102/25/15 1:0015
2202/25/15 1:1530
2302/25/15 1:4545
2402/25/15 2:305

View 7 Replies View Related

T-SQL (SS2K8) :: Getting Sum Values For Non Overlapping Rows By Datetime?

Oct 13, 2014

I want to count persons for non overlapping intervalls by room number. Here the data:

SET DATEFORMAT mdy;
DECLARE @PersonTime TABLE
(
ID INT,
Person INT,
Room INT,
Coming DATETIME,
Going DATETIME

[code]....

View 4 Replies View Related

T-SQL (SS2K8) :: Subtraction Of Values From Consecutive Rows

May 31, 2015

I've;

Id.........|......type....|.....Value
2001................1...............20
2001................2...............32
2002................1...............19
2002................2...............21
2003................1............... 3
2003................2...............30

I want;

Id........|.......Value
2001.................12
2002..................2
2003.................27

View 7 Replies View Related

T-SQL (SS2K8) :: Search Through Rows With Specific Values

Sep 16, 2015

I've a table that stores operationcode for each jobnumber. The jobnumber can have multiple operationcode. From the below DDL, I need to show all the jobs that have operation codes as 2001 and 2002. In the below DDL Jobnumber 80011 has both the operation codes 2001 and 2002 so this job will display on the report.

On the other hand Job 80021 only has operationcode 2001 and I do not want this job to show up on the report.

I need to show all the operationcodes for a job if it has operationcode 2001 and 2002.

USE tempdb;
GO
DECLARE @TEST_DATA TABLE
(
DT_ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED
, OperationCodeVARCHAR(10) NOT NULL
, EmployeeCode VARCHAR(10) NOT NULL

[Code] ....

View 9 Replies View Related

T-SQL (SS2K8) :: Fast Forward Cursors Are Read Only But Are They Insensitive

Oct 2, 2014

A fast_forward cursor is read only by definition, meaning the rows can't be updated, but I'm not sure if they are insensitive or not. Do they reflect the changes in the database after the cursor is opened?

View 6 Replies View Related

T-SQL (SS2K8) :: Can It Change Columns Of A Table Values To Rows

May 14, 2014

I have a table with this info:

NrCard numberPersonAuto123456789101112
11111111111111111111User1VW Jetta6,46,46,46,45,825,825,825,825,825,825,826,4
22222222222222222222User2Honda CR-V 13,2113,2113,2112,0112,0112,0112,0112,0112,0112,0113,2113,21

How I can get this result:

NrCard numberPersonAutomonthvalue
11111111111111111111User1VW Jetta16,4
11111111111111111111User1VW Jetta26,4
11111111111111111111User1VW Jetta36,4
11111111111111111111User1VW Jetta45,82
11111111111111111111User1VW Jetta55,82
11111111111111111111User1VW Jetta65,82

[code]....

Should I use unpivot or pivot?

View 2 Replies View Related

How To Not Auto Generate A Report, How To Use A Null Checkbox On A Param With Available Values, How To Add Back/forward Buttons?

Apr 3, 2008

Hey all,

1) I have a report with many parameters that I want users to be able to pick from. Allow them to pick 1, many or all to build their report dynamically. I'm all set on the TSQL side, but on the Reporting Services side I have to allow each parameter to be null with a default of NULL. In by doing this, the report will auto run, which I do not want to happen. The only resolution I've found thus far was by adding a parameter that does nothing, with a NULL default value. Yet It sticks out like a sore thumb on the report and I want to get rid of it. If I check in "Hidden" in the parameter options, my report errors out stating that the parameter requires a value.

2) Is it possible to have a parameter that has available values from a dataset have a NULL checkbox like those of parameters that do not have available values?


3) Is it possible to add back/forward buttons inside of a report instead of just at the report header by default?


Thanks!

View 8 Replies View Related

Retriving Previous 5 Rows And Next 5 Rows And The Searched Record

Mar 30, 2008

Dear All

I have a table with the following structure in sql server 2005

create table app(
sno int,
name varchar(50),
add varchar(50),
city varchar(50),
state varchar(50)
)

it contains the follwing data
------------------------------------------
sno name add city state
------------------------------------------
1 mark street no1 newcity newstate
2 mark street no1 newcity newstate
3 mark street no1 newcity newstate
4 mark street no1 newcity newstate
5 mark street no1 newcity newstate
6 mark street no1 newcity newstate
7 mark street no1 newcity newstate
8 mark street no1 newcity newstate
9 mark street no1 newcity newstate
10 mark street no1 newcity newstate
11 mark street no1 newcity newstate
12 mark street no1 newcity newstate
13 mark street no1 newcity newstate
14 mark street no1 newcity newstate
15 mark street no1 newcity newstate
16 mark street no1 newcity newstate
17 mark street no1 newcity newstate
18 mark street no1 newcity newstate
19 mark street no1 newcity newstate
20 mark street no1 newcity newstate

----------------------------------------

I want to retrive previous 5 records, next 5 records and the record that meet the where condition of a select query.


When I run

select sno,add,name,city,state from app where sno=7

I want the following result

------------------------------------------
sno name add city state
------------------------------------------
2 mark street no1 newcity newstate |
3 mark street no1 newcity newstate |
4 mark street no1 newcity newstate | -- previous 5 records
5 mark street no1 newcity newstate |
6 mark street no1 newcity newstate |
7 mark street no1 newcity newstate --- searched record
8 mark street no1 newcity newstate |
9 mark street no1 newcity newstate |
10 mark street no1 newcity newstate |--- next 5 records
11 mark street no1 newcity newstate |
12 mark street no1 newcity newstate |
----------------------------------------

if there is a method to get the above result set, kindly post the query.

View 14 Replies View Related

T-SQL (SS2K8) :: Set Value Based On Previous Row

Apr 11, 2014

I am trying to code a rule at the moment which sets a value based on the value of the previous row. This is as far as I have got so far. I am trying to run it as a set based command and I believe I may need to make use of a numbers table.

Anyway the code is....

declare @data table
(ID int identity(1,1),
DeviceID int,
EventTypeID int,
EventID int)

[Code] ....

So the output is currently incorrect. Each DeviceID needs to have a ID assigned to the MIN(ID) which isn't yet in the code above. This ID has to be sequential across the full table and not dependent on ID.

Next the rule is coded in the case statement above.

So for each DeviceID, when the EventType goes from 1, 2 or 4, to 0 or 3, the following record after the 0 or 3 will have a new EventID. And conversely when the EventType goes from 0 or 3 to 1,2, or 4, the record that is the 1, 2 or 4 will have a new EventID.

View 6 Replies View Related

T-SQL (SS2K8) :: Add Balance Of Previous Row To Current Row

Jul 2, 2014

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.

View 9 Replies View Related

T-SQL (SS2K8) :: Compare Next Row With Previous Row Of Same Table?

Sep 16, 2014

I need to compare the next row with the previous row of same table and produce nonidentical column.for eg... say my table has

Row 1 => 1001 Abhas 120 150 180
Row 2 => 1001 Abhas 150 150 180

then my output would be as below:

StudId Name fee1 fee2 fee3
1001 120
1001 Abhas 150 150 150

i.e in first row of resultset, i want to show only those values which are changed alongwith studID and next row should display all values.

View 9 Replies View Related

T-SQL (SS2K8) :: Compare With Previous Records

Oct 20, 2014

I am having a table which contains data of students like:

StudentID,StudentName,Term,RESult.

Sample data :

StudentID,StudentName,Term,RESult.
1,ABC,Term1,Pass
1,ABC,Term2,Fail
1,ABC,Term3,Pass
1,ABC,Term4,Pass
1,ABC,Term5,Pass

Now i want to compare Result and dislay prevterm where student fail:

Now my output would be as: Now I want to compare latest term i.e. Term5 with prev Terms and if found Mismatch in result then i want to display as below:

studentID PrevFailTerm, CurrentTerm
1,Term2,Term5

View 1 Replies View Related

T-SQL (SS2K8) :: Get First Day Previous Quarter From Todays Date

Aug 22, 2014

How do I get first day of last month of previous quarter from today's date? I know my question is little confusing. I need to get 06/01/2014 using t-sql.

View 2 Replies View Related

T-SQL (SS2K8) :: Find Previous Date From Table

Nov 4, 2015

I want to find previous date from selected date. below is the sample data.

DECLARE @StartDate SMALLDATETIME = '1/11/2016'

declare @tempdat table(repdate smalldatetime)
insert into @tempdat values ('10/26/2015')
insert into @tempdat values ('10/29/2015')
insert into @tempdat values ('11/1/2015')
insert into @tempdat values ('11/27/2015')
insert into @tempdat values ('11/25/2015')
insert into @tempdat values ('11/20/2015')
insert into @tempdat values ('11/10/2015')
insert into @tempdat values ('11/10/2015')
insert into @tempdat values ('11/11/2015')
insert into @tempdat values ('11/11/2015')

Now if i pass the date '10/26/2015' then i want select prev date of passed date. in this example no prev date is available, so result set would be nothing.

if i pass the date '11/10/2015' then result should be '11/1/2015' which is prev small date available in table.

View 4 Replies View Related

T-SQL (SS2K8) :: Calculate And Return Previous Date At 18:00 Hours

Mar 4, 2014

How can I calculate and return the previous Date at 18:00 Hours?

Here is a miserable attempt:

DECLARE @RunDate SmallDateTime
DECLARE @CurrentDate SmallDateTime
DECLARE @RunDateWoTime SmallDateTime
SET @CurrentDate = GETDATE()

SET @RunDate = DATEADD(day,-1,@CurrentDate)-- AS CurrentDate
SELECT @RunDate AS RunDate

-- Desired Result is the following:

-- 2014-03-03 18:00

View 9 Replies View Related

T-SQL (SS2K8) :: Date Logic - How To Get Previous 6 Months Data

Sep 29, 2014

I am working in sqlserver 2008 R2 and below is my sample research query. I am trying to get previous 6 months data.

WITH CutomMonths
AS (
SELECT UPPER(convert(VARCHAR(3), datename(month, DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) - N, 0)))) Month
,DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) - N, 0) startdate
,DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) - N + 1, 0) enddate
FROM (
VALUES (1)

[Code] ...

Current output what i am getting:

Expected Output:

I found why the April month i didn't get the $20 because the startdate of my perks CTE '2014-04-03'. If it is '2014-04-01' then i will get the expected output.

But i should not change the the date on perks. How to neglect this date issue and consider the month instead to get the expected output.

View 6 Replies View Related

T-SQL (SS2K8) :: Finding Previous Even Numbered Month And Appropriate Year From Given Date

Mar 25, 2014

I'm trying to write some T-SQL to return the previous even numbered month and appropriate year from given date.

Examples given:
03-25-2014 should return 02-xx-2014
01-01-2014 should return 12-xx-2013

View 2 Replies View Related

T-SQL (SS2K8) :: Pass Dates For Previous Months Start And End Date

Mar 16, 2015

I've SSRS sales report to which I need to pass the dates for previous month's start date and end date which I am able to pass using below code. However, since the sales report has data from the past year(2014) I need to pass the dates for last year as well. The below code gives StartDate1 as 2015-02-01 and EndDate1 as 2015-02-28. I need to get the dates for past year like 2014-02-01 as StartDate2 and 2014-02-28 as EndDate2

SELECT DATEADD(MONTH, DATEDIFF(MONTH, '19000201', GETDATE()), '19000101') AS StartDate1,
DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '18991231') AS EndDate1

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

How To Sum Previous Row Values?

May 15, 2008

Hi,

I need your help for my SQL query. I have a table like this

ClmA ClmB ClmType
------+------+----------
1 | 10 | 0
2 | 20 | 0
3 | 30 | 1
4 | 40 | 0
5 | 50 | 1

And its the result that i want to get.

ClmA ClmB ClmType ClmResult
------+------+---------+-------
1 | 10 | 0 | 10
2 | 20 | 0 | 30
3 | 30 | 1 | 30
4 | 40 | 0 | 70
5 | 50 | 1 | 80


Let me explain. When retrieving a row, an extra column should be added.It's value should be the sum of previous rows whose type is the same with the encountered one. I made it with a function but it's performance was terible with large tables. I have tables larger then fifty housands rows.

View 7 Replies View Related

T-SQL (SS2K8) :: Table With Score Info For Groups - Ranking For Current And Previous Week

Jan 21, 2015

I have a table with score info for each group, and the table also contains historical data, I need to get the ranking for the current week and previous week, here is what I did and the result is apparently wrong:

select CurRank = row_number() OVER (ORDER BY cr.CurScore desc) , cr.group_name,cr.CurScore
, lastWeek.PreRank, lastWeek.group_name,lastWeek.PreScore
from
(select group_name,
Avg(case when datediff(day, asAtDate, getdate()) <= 7 then sumscore else 0 end) as CurScore

[Code] ....

The query consists two parts: from current week and previous week respectively. Each part returns correct result, the final merged result is wrong.

View 3 Replies View Related

Getting Previous Values Of A Field

Mar 15, 2006

Hi,In oracle I have a LAG function using which I could get the previousvalue of a field.Do we have anything similar to that in SQL Server or access?ThanksDevi

View 4 Replies View Related

Most Effecient Way To Get Previous Row Values?

Jan 23, 2007

Wow, this board has gotten really busy lately - maybe 2007 is the year that a lot more people start using SSIS :)

Anyway my question is this: If I have an ordered set of data in the data flow and I want to add a column, lets just say "previousID" that basically has the ID value of a column from the row immediately before it - what is the most effecient way of doing that?

I've done much more complicated things with running averages, mean, etc by creating an asynchronous script transformation, pushing the data into a datatable in memory and looping through row by row using variables etc to do the calcs... but I just have this feeling that there is a "lighter, faster, easier" way for just getting previous row's value (with some special rows like first row has a null etc) than looping through a datatable row by row.

Can you push the buffer into an array (if so anyone have an example script) and use simple "n-1" logic? (ie using the array index)

 

 

View 13 Replies View Related

Copy Values From Previous Row

Aug 26, 2006

I'm guessing this is a fairly straight forward need, but want to make sure I am using the correct set of tasks:

In the dataflow, some values I need to carry forward from the previous row, such as a balance that I need to carry forward for the current customer record. This is similar to a running total, only I am not summing anything, but just carrying over from the previous records value (assuming dataset is sorted correctly, first by customer #, then by date).

Do I need the Dervied Column transform, and use a variable to store the previous value, or is there another transform that would be better suited?

Thanks

Kory

View 4 Replies View Related

Average Of Previous Values

May 9, 2008


How to write Stored Procedure to convert All seconds to Minutes AND finding average.

Ex:

My Table1:

SYMBOL TIME PRICE

EUR A0-FX 2008-05-09 11:37:31.203 1.54035
EUR A0-FX 2008-05-09 11:37:30.030 1.54034
EUR A0-FX 2008-05-09 11:37:28.860 1.54033
EUR A0-FX 2008-05-09 11:37:41.673 1.54032
EUR A0-FX 2008-05-09 11:37:59.720 1.54031

EUR A0-FX 2008-05-09 11:38:09.000 1.54033
EUR A0-FX 2008-05-09 11:38:35.877 1.54032
EUR A0-FX 2008-05-09 11:38:59.767 1.54041


OutPut:

SYMBOL TIME PRICE

EUR A0-FX 11:37 1.54031
EUR A0-FX 11:38 1.54041

I know this how to write ..




;WITH cte
AS
(
SELECT
SYMBOL,
[Time],
Price,
ROW_NUMBER() OVER(PARTITION BY CONVERT(CHAR(5), CAST(Time AS DATETIME), 114) ORDER BY CAST(Time AS DATETIME) ASC) AS rn_1,
ROW_NUMBER() OVER(PARTITION BY CONVERT(CHAR(5), CAST(Time AS DATETIME), 114) ORDER BY CAST(Time AS DATETIME) DESC) AS rn_2
FROM
Table1 WHERE SYMBOL='EUR A0-FX'
)

SELECT SYMBOL='EUR A0-FX',CONVERT(CHAR(5), CAST(Time AS DATETIME), 114) AS [Time],MAX(CASE WHEN rn_2 = 1 THEN Price ELSE NULL END) AS [Close] FROM cte

GROUP BY
CONVERT(CHAR(5), CAST(Time AS DATETIME), 114)
ORDER BY
CAST(CONVERT(CHAR(5), CAST(Time AS DATETIME), 114) AS DATETIME);



But I want to add some additional code in my procedure like AVERAGE of Previous 5 Price Values.

Ex:

SYMBOL TIME PRICE

EUR A0-FX 11:37 1.54031 ß1
EUR A0-FX 11:38 1.54041 ß2
EUR A0-FX 11:39 1.54021 ß3
EUR A0-FX 11:40 1.54081 ß4
EUR A0-FX 11:41 1.54071 ß5 Previous 5 Average PRICE Values.
(1.54061)

EUR A0-FX 11:42 1.54091 ß6
EUR A0-FX 11:43 1.54021 ß7
EUR A0-FX 11:44 1.54081 ß8


My Final
Out Put:

SYMBOL TIME PRICE AVERAGE
EUR A0-FX 11:42 1.54091 ß6 (1.54061)
EUR A0-FX 11:43 1.54021 ß7 (1.54091)
EUR A0-FX 11:44 1.54081 ß8 (1.54071)

At 11.42 time average is 1-5 price values
At 11.43 time average is 2-6 price values
At 11.44 time average is 3-7 price values


View 2 Replies View Related

Reference Previous Rows

Jun 20, 2006

I am doing some calculations with a table and would like to know how to reference a previous row without having to alter the dates in a query at the start of each month.

For example I have to find a percentage change for a series of values. The table has three columns, is based on end of month dates, and the "return" column is the calculated column where the value is. In the example the return value for date 2006-04-30 is Index of (2006-04-30/ Index 2006-03-31)-1.

Date Index return
2006-03-31 6535 .05130
2006-04-30 6949.29 .06333

View 3 Replies View Related

Total Of Previous Rows

May 13, 2008



Hi,

I have a table like this.









Portfolio
Name
Value

ALL UP
Charge Off
47

ALL UP
CLTV
212

ALL UP
DSR
441

ALL UP
Exc Total
719

ALL UP
FICO
11


I want to add a row to the bottom of the table so that it will give the total of all values above.
It's something like this.
SELECT Portfolio, Name, Value , Total
FROM table

Total is equal to sum of all above values. Can anyone help me to write this query?

Thanks


View 5 Replies View Related

Total Of Previous Rows

May 15, 2008

I have a table like this.


Name Amount

CBank 5
InstLend 4
DTC 1



Now i want write a query which give me the out put like this.



Name Amount

CBank 5
InstLend 4
DTC 1

Total 10

can any one help me to write this please?

View 5 Replies View Related

T-SQL (SS2K8) :: Count Number Of Values That Exist In A Row Based On Values From Array Of Numbers

Apr 16, 2014

How to count the number of values that exist in a row based on the values from an array of numbers. Basically the the array of numbers I want to look for are in row 1 of table [test 1] and I want to search for them and count the "out of" in table [test 2]. Excuse me for not using the easiest way to convey my question below. I guess in short I have 10 numbers and like to find how many of those numbers exist in each row. short example:

Table Name: test1
Columns: m1 (int), m2 (int), m3 (int) >>> etc
Array/Row1: 1 2 3 4 5 6 7 8 9 10

------
Table Name: test2
Columns: n1 (int), n2 (int), n3 (int), n4 (int), n5 (int)

Row 1: 3, 8, 18, 77, 12
Row 2: 1, 4, 5, 7,18, 21
Row 3: 2, 4, 6, 8, 10

Answer: 2 out of 5
Answer: 4 out of 5
Answer: 5 out of 5

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

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







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