これは多くの解釈が可能です。私はこれを読んで、あなたがBreak以外の各StatusKeyとそれぞれのブレークを合計したいと思っています。価値があるものについては、あなたのStatusKeyを別のテーブルに正規化することをお勧めしますが、それはたぶん別の日のトピックです。
ここで最初に挑戦するのは、他の人が実際にあなたの問題に容易に対応できるようにデータを投稿する必要があるということです。ここでは、サンプルデータを投稿するためのより良い方法の例を示します。
if OBJECT_ID('tempdb..#something') is not null
drop table #something
create table #something
(
UserID varchar(10)
, StartTime datetime
, EndTime datetime
, StatusKey varchar(10)
, StateDuration int
)
insert #something
select 'amjackson', '2016-04-25 12:12:14', '2016-04-25 12:12:19', 'followup', '5' union all
select 'amjackson', '2016-04-25 12:12:19', '2016-04-25 12:13:23', 'Break', '64' union all
select 'amjackson', '2016-04-25 12:13:23', '2016-04-25 12:13:42', 'available', '19' union all
select 'amjackson', '2016-04-25 12:13:42', '2016-04-25 12:19:42', 'Break', '360' union all
select 'amjackson', '2016-04-25 12:19:42', '2016-04-25 12:21:55', 'available', '133';
援助を受ける可能性が指数関数的に上昇するのを手助けするのは、誰かにとって非常に簡単です。
これは、この問題を解決する方法の1つです。これはもちろん、実際のデータと実際の要件について多くの仮定をしています。ここでのテクニックはクロス集計と呼ばれ、時には条件付き集計とも呼ばれます。 PIVOTを使用することもできます。私は文法が私にはあまり鈍く、少し速くなることが証明されているので、クロスタブを好む。これはおそらくあなたが述べた望ましい出力を返す少し単純化することができます。
with GroupedValues as
(
select UserID
, convert(date, StartTime) as Date
, StatusKey
, StateDuration
, StartTime
from #something
where StatusKey = 'Break'
union all
select UserID
, convert(date, max(StartTime)) as Date
, StatusKey
, SUM(StateDuration) as TotalDuration
, Min(StartTime)
from #something
where StatusKey <> 'Break'
group by UserID
, StatusKey
)
, SortedValues as
(
select *
, ROW_NUMBER() over(order by StartTime) as RowNum
from GroupedValues
)
select UserID
, Date
, Max(case when RowNum = 1 then StateDuration end) as Followup
, Max(case when RowNum = 2 then StateDuration end) as Break1
, Max(case when RowNum = 3 then StateDuration end) as Available
, Max(case when RowNum = 4 then StateDuration end) as Break2
from SortedValues
group by UserID
, Date
あなたが所望の出力の例を追加することはできますか?私はあなたに何を求めているのか分かりません – m4tt1mus