我嘗試使用分組集。 樣本數據 -
declare @temp table (
ServiceID int not null,
Created Datetime null,
Authorised DateTime null,
Closed Datetime null
)
insert into @temp
select 1, '2016-08-03', '2016-07-03', '2016-02-03' union
select 2, '2016-10-03', '2016-04-03', '2016-08-03' union
select 3, '2016-04-03', '2016-02-03', '2016-12-03' union
select 4, '2016-04-03', '2016-01-03', '2016-10-03'
實際代碼 -
;with grouped as (
select created = format(created, 'yyyyMM'),
authorised = format(authorised, 'yyyyMM'),
closed = format(closed, 'yyyyMM'),
count_val = count(*)
from @temp
group by grouping sets(
format(created, 'yyyyMM'),
format(authorised, 'yyyyMM'),
format(closed, 'yyyyMM'))
)
,combined as(
select [Month]=right(created,2),[year]=left(created,4), created=count_val, authorised, closed
from grouped
where created is not null
union all
select [Month]=right(authorised,2),[year]=left(authorised,4), created, authorised=count_val, closed
from grouped
where authorised is not null
union all
select [Month]=right(closed,2),[year]=left(closed,4), created, authorised, closed=count_val
from grouped
where closed is not null
)
select [Month],[year],created=sum(created),authroised=sum(authorised),closed=sum(closed)
from combined
group by [Month],[year]
哇。這是少數。我需要看看是否可以修改,因爲我的真正表格實際上有更多的日期/時間列。它看起來不是一個好主意,使8全外連接! – navigator
不要太擔心。數據庫管理系統是做這種事情的。它可能在這裏使用散列連接,這應該很快。請記住,只有少數記錄需要連接,因爲數據已經彙總。 –