Question

using the following table and data

CREATE TABLE [dbo].[AccountStatus](
[Id] [INT] NOT NULL,
[AccountId] [VARCHAR](15) NOT NULL,
[Status] [VARCHAR](15) NOT NULL,
[DateChanged] [DATETIME] NOT NULL
)

INSERT AccountStatus (Id,AccountId,Status,DateChanged) VALUES (1 , 'A', 'Imported', '1/1/2014')
INSERT AccountStatus (Id,AccountId,Status,DateChanged) VALUES (1 , 'A', 'Validated', '1/12/2014')
INSERT AccountStatus (Id,AccountId,Status,DateChanged) VALUES (1 , 'A', 'Contacted', '1/21/2014')
INSERT AccountStatus (Id,AccountId,Status,DateChanged) VALUES (1 , 'A', 'Qualified', '2/1/2014')
INSERT AccountStatus (Id,AccountId,Status,DateChanged) VALUES (1 , 'A', 'Closed', '2/10/2014')

How would one create output using tql showing the duration a given account was in a status?

The values are immutable and will never be updated.

I am looking for

Status | Start | End | Duration

I am have a real brain freeze.

Thanks

G

Was it helpful?

Solution

If I've understood your problem correctly, I would use the following approach. Please note that the code is not tested as you did not supply data (I wrote the code "in the air"). You would be making it a lot simpler to get answers if you post DDL & Data with your questions.

--  First sequence all Statuses, on a per account basis
;WITH StatusSeq AS
(
    SELECT   Id 
            ,Seq    = ROW_NUMBER() OVER (PARTITION BY AccountID ORDER BY DateChanged)
            ,AccountId
            ,[Status]
            ,DateChanged
    FROM dbo.AccountStatus
)
--  Second: Join the table to itself, so that on the right hand side
--          of the current row, you read the Status tha immediately followed
SELECT   T1.AccountID
        ,T1.[Status]
        ,StartDT    = T1.DateChanged
        ,EndDT      = T2.DateChanged
        --  I've chosen to show the date difference as days here, 
        --  you may want to choose something else
        ,Duration   = DATEDIFF(DAY, T1.DateChanged, T2.DateChanged)
FROM StatusSeq  T1
JOIN StatusSeq  T2  ON T1.Seq = T2.Seq - 1

OTHER TIPS

Assuming there is a row for Start and End:

SELECT Status,
  MIN(DateChanged) AS [Start],
  MAX(DateChanged) AS [End],
  MAX(DateChanged) - MIN(DateChanged) AS [Duration]
FROM AccountStatus
GROUP BY Status

You will have to play around with Duration using CONVERT

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top