나는 그룹화 집합을 사용해보십시오. 샘플 데이터 -
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
너무 걱정하지 마십시오. DBMS는 이러한 일을 정확하게 수행하도록 만들어졌습니다. 여기에 해시 조인을 사용할 수 있습니다. 데이터가 이미 집계 되었기 때문에 조인 할 필요가있는 레코드가 거의 없다는 것을 기억하십시오. –