使用下表和数据
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')
如何使用tql创建输出,显示给定帐户处于状态的持续时间?
值是不可变的,永远不会更新。
我正在寻找
Status | Start | End | Duration
我有一个真正的大脑冻结。
由于
答案 0 :(得分:1)
如果我已正确理解您的问题,我会使用以下方法。 请注意,代码未经过测试,因为您没有提供数据(我编写代码"在空中")。 如果你发布DDL& amp;会让你的答案变得简单得多。数据与您的问题。
-- 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
答案 1 :(得分:0)
假设开始和结束有一行:
SELECT Status,
MIN(DateChanged) AS [Start],
MAX(DateChanged) AS [End],
MAX(DateChanged) - MIN(DateChanged) AS [Duration]
FROM AccountStatus
GROUP BY Status
您必须使用Duration
CONVERT