;--start of CTEs
with cte_sortableACPrimaryUser as
--this cte gives an extra sortable date column wrapping around table Inv_AeX_AC_Primary_User
(
select
_id,
_ResourceGuid,
[Month],
[User],
[Domain],
[Server Generated],
[Year],
case when [Month] = 'December' then cast(cast([Year] as varchar(20)) + '-Dec-01' as datetime)
when [Month] = 'November' then cast(cast([Year] as varchar(20)) + '-Nov-01' as datetime)
when [Month] = 'October' then cast(cast([Year] as varchar(20)) + '-Oct-01' as datetime)
when [Month] = 'September' then cast(cast([Year] as varchar(20)) + '-Sep-01' as datetime)
when [Month] = 'August' then cast(cast([Year] as varchar(20)) + '-Aug-01' as datetime)
when [Month] = 'July' then cast(cast([Year] as varchar(20)) + '-Jul-01' as datetime)
when [Month] = 'June' then cast(cast([Year] as varchar(20)) + '-Jun-01' as datetime)
when [Month] = 'May' then cast(cast([Year] as varchar(20)) + '-May-01' as datetime)
when [Month] = 'April' then cast(cast([Year] as varchar(20)) + '-Apr-01' as datetime)
when [Month] = 'March' then cast(cast([Year] as varchar(20)) + '-Mar-01' as datetime)
when [Month] = 'February' then cast(cast([Year] as varchar(20)) + '-Feb-01' as datetime)
when [Month] = 'January' then cast(cast([Year] as varchar(20)) + '-Jan-01' as datetime)
end as [SortableDate]
from
Inv_AeX_AC_Primary_User
),
cte_NoPrimaryUser as
--this cte gives all this month's records which have no user info
(
select
_id,
_ResourceGuid,
[SortableDate]
from
cte_sortableACPrimaryUser
where
(
([User] is null)
or
(ltrim(rtrim([User])) = '')
)
and
[Month] = datename(month, getdate())
and
[Year] = year(getdate())
),
cte_PrevMonthPrimaryUser as
--this CTE looks for previous month's records and tries to locate the primary user
(
select
npu._id,
npu._ResourceGuid,
npu.[SortableDate],
spu.[User],
spu.[Domain],
spu.[Server Generated]
from
cte_sortableACPrimaryUser spu
join cte_NoPrimaryUser npu on spu._ResourceGuid = npu._ResourceGuid and datediff(month, spu.[SortableDate], npu.[SortableDate]) = 1
where
(spu.[User] is not null)
and
(ltrim(rtrim(spu.[User])) != '')
)
select
apu._id,
apu._ResourceGuid,
apu.[Month],
isnull(apu.[User], pmpu.[User]) as [User],
isnull(apu.[Domain], pmpu.[Domain]) as [Domain],
isnull(apu.[Server Generated], pmpu.[Server Generated]) as [Server Generated],
apu.[Year]
from
Inv_AeX_AC_Primary_User apu
left join cte_PrevMonthPrimaryUser pmpu on apu._id = pmpu._id /* and apu._ResourceGuid = pmpu._ResourceGuid */
;--end of CTEs
Dave, can you please give this monster query a go and let me know if there is a problem? Hope it help!